diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/CannotGetMongoDbConnectionException.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/CannotGetMongoDbConnectionException.java index 6d21b8cf7..341ffdd51 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/CannotGetMongoDbConnectionException.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/CannotGetMongoDbConnectionException.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2012 the original author or authors. + * Copyright 2010-2017 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. @@ -17,16 +17,18 @@ package org.springframework.data.mongodb; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.data.authentication.UserCredentials; +import org.springframework.lang.Nullable; /** * Exception being thrown in case we cannot connect to a MongoDB instance. - * + * * @author Oliver Gierke + * @author Mark Paluch */ public class CannotGetMongoDbConnectionException extends DataAccessResourceFailureException { private final UserCredentials credentials; - private final String database; + private final @Nullable String database; private static final long serialVersionUID = 1172099106475265589L; @@ -40,7 +42,7 @@ public class CannotGetMongoDbConnectionException extends DataAccessResourceFailu this(msg, null, UserCredentials.NO_CREDENTIALS); } - public CannotGetMongoDbConnectionException(String msg, String database, UserCredentials credentials) { + public CannotGetMongoDbConnectionException(String msg, @Nullable String database, UserCredentials credentials) { super(msg); this.database = database; this.credentials = credentials; @@ -48,7 +50,7 @@ public class CannotGetMongoDbConnectionException extends DataAccessResourceFailu /** * Returns the {@link UserCredentials} that were used when trying to connect to the MongoDB instance. - * + * * @return */ public UserCredentials getCredentials() { @@ -57,9 +59,10 @@ public class CannotGetMongoDbConnectionException extends DataAccessResourceFailu /** * Returns the name of the database trying to be accessed. - * + * * @return */ + @Nullable public String getDatabase() { return database; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java index 00f381e32..d94d93e05 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java @@ -24,6 +24,7 @@ import org.springframework.data.mongodb.core.convert.DbRefResolver; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; import org.springframework.data.mongodb.core.convert.MappingMongoConverter; import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.lang.Nullable; import com.mongodb.MongoClient; @@ -84,6 +85,7 @@ AbstractMongoConfiguration extends MongoConfigurationSupport { * @deprecated use {@link #getMappingBasePackages()} instead. */ @Deprecated + @Nullable protected String getMappingBasePackage() { Package mappingBasePackage = getClass().getPackage(); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java index 19baf1211..d2f8731bf 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java @@ -1,11 +1,11 @@ /* - * Copyright 2011-2017 by the original author(s). + * Copyright 2011-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -33,6 +33,7 @@ import org.springframework.beans.factory.xml.ParserContext; import org.springframework.data.config.BeanComponentDefinitionBuilder; import org.springframework.data.mongodb.core.MongoClientFactoryBean; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; +import org.springframework.lang.Nullable; import org.springframework.util.StringUtils; import org.w3c.dom.Element; @@ -42,12 +43,13 @@ import com.mongodb.MongoURI; /** * {@link BeanDefinitionParser} to parse {@code db-factory} elements into {@link BeanDefinition}s. - * + * * @author Jon Brisbin * @author Oliver Gierke * @author Thomas Darimont * @author Christoph Strobl * @author Viktor Khoroshko + * @author Mark Paluch */ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { @@ -62,7 +64,7 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { MONGO_URI_ALLOWED_ADDITIONAL_ATTRIBUTES = Collections.unmodifiableSet(mongoUriAllowedAdditionalAttributes); } - /* + /* * (non-Javadoc) * @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#resolveId(org.w3c.dom.Element, org.springframework.beans.factory.support.AbstractBeanDefinition, org.springframework.beans.factory.xml.ParserContext) */ @@ -74,7 +76,7 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { return StringUtils.hasText(id) ? id : BeanNames.DB_FACTORY_BEAN_NAME; } - /* + /* * (non-Javadoc) * @see org.springframework.beans.factory.xml.AbstractBeanDefinitionParser#parseInternal(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) */ @@ -119,7 +121,7 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { /** * Registers a default {@link BeanDefinition} of a {@link Mongo} instance and returns the name under which the * {@link Mongo} instance was registered under. - * + * * @param element must not be {@literal null}. * @param parserContext must not be {@literal null}. * @return @@ -138,11 +140,12 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { * attributes.
* Errors when configured element contains {@literal uri} or {@literal client-uri} along with other attributes except * {@literal write-concern} and/or {@literal id}. - * + * * @param element must not be {@literal null}. * @param parserContext * @return {@literal null} in case no client-/uri defined. */ + @Nullable private BeanDefinition getMongoUri(Element element, ParserContext parserContext) { boolean hasClientUri = element.hasAttribute("client-uri"); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/ServerAddressPropertyEditor.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/ServerAddressPropertyEditor.java index a61ba8ea4..38a60ef84 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/ServerAddressPropertyEditor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/ServerAddressPropertyEditor.java @@ -31,7 +31,7 @@ import com.mongodb.ServerAddress; /** * Parse a {@link String} to a {@link ServerAddress} array. The format is host1:port1,host2:port2,host3:port3. - * + * * @author Mark Pollack * @author Oliver Gierke * @author Thomas Darimont @@ -80,10 +80,11 @@ public class ServerAddressPropertyEditor extends PropertyEditorSupport { /** * Parses the given source into a {@link ServerAddress}. - * + * * @param source * @return the */ + @Nullable private ServerAddress parseServerAddress(String source) { if (!StringUtils.hasText(source)) { @@ -114,7 +115,7 @@ public class ServerAddressPropertyEditor extends PropertyEditorSupport { /** * Extract the host and port from the given {@link String}. - * + * * @param addressAndPortSource must not be {@literal null}. * @return */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultIndexOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultIndexOperations.java index 5bab7a5b5..5bb007bef 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultIndexOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultIndexOperations.java @@ -98,10 +98,6 @@ public class DefaultIndexOperations implements IndexOperations { Document indexOptions = indexDefinition.getIndexOptions(); - if (indexOptions == null) { - return collection.createIndex(indexDefinition.getIndexKeys()); - } - IndexOptions ops = IndexConverters.indexDefinitionToIndexOptionsConverter().convert(indexDefinition); if (indexOptions.containsKey(PARTIAL_FILTER_EXPRESSION_KEY)) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperations.java index 4e2587dfb..6587c27b9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DefaultReactiveIndexOperations.java @@ -15,8 +15,6 @@ */ package org.springframework.data.mongodb.core; -import org.springframework.data.mongodb.core.index.ReactiveIndexOperations; -import org.springframework.lang.Nullable; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -27,7 +25,9 @@ import org.bson.Document; import org.springframework.data.mongodb.core.convert.QueryMapper; import org.springframework.data.mongodb.core.index.IndexDefinition; import org.springframework.data.mongodb.core.index.IndexInfo; +import org.springframework.data.mongodb.core.index.ReactiveIndexOperations; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import com.mongodb.client.model.IndexOptions; @@ -69,7 +69,7 @@ public class DefaultReactiveIndexOperations implements ReactiveIndexOperations { * @param type used for mapping potential partial index filter expression, must not be {@literal null}. */ public DefaultReactiveIndexOperations(ReactiveMongoOperations mongoOperations, String collectionName, - QueryMapper queryMapper, @Nullable Class type) { + QueryMapper queryMapper, Class type) { this(mongoOperations, collectionName, queryMapper, Optional.of(type)); } @@ -96,10 +96,6 @@ public class DefaultReactiveIndexOperations implements ReactiveIndexOperations { Document indexOptions = indexDefinition.getIndexOptions(); - if (indexOptions == null) { - return collection.createIndex(indexDefinition.getIndexKeys()); - } - IndexOptions ops = IndexConverters.indexDefinitionToIndexOptionsConverter().convert(indexDefinition); if (indexOptions.containsKey(PARTIAL_FILTER_EXPRESSION_KEY)) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/IndexConverters.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/IndexConverters.java index fd0dd118b..20b03673a 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/IndexConverters.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/IndexConverters.java @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.mongodb.core; import java.util.concurrent.TimeUnit; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java index 1d7c90aea..5a704d2df 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java @@ -34,8 +34,9 @@ import com.mongodb.ServerAddress; /** * Convenient factory for configuring MongoDB. - * + * * @author Christoph Strobl + * @author Mark Paluch * @since 1.7 */ public class MongoClientFactoryBean extends AbstractFactoryBean implements PersistenceExceptionTranslator { @@ -52,7 +53,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp /** * Set the {@link MongoClientOptions} to be used when creating {@link MongoClient}. - * + * * @param mongoClientOptions */ public void setMongoClientOptions(@Nullable MongoClientOptions mongoClientOptions) { @@ -61,7 +62,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp /** * Set the list of credentials to be used when creating {@link MongoClient}. - * + * * @param credentials can be {@literal null}. */ public void setCredentials(@Nullable MongoCredential[] credentials) { @@ -70,7 +71,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp /** * Set the list of {@link ServerAddress} to build up a replica set for. - * + * * @param replicaSetSeeds can be {@literal null}. */ public void setReplicaSetSeeds(@Nullable ServerAddress[] replicaSetSeeds) { @@ -79,7 +80,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp /** * Configures the host to connect to. - * + * * @param host */ public void setHost(@Nullable String host) { @@ -88,7 +89,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp /** * Configures the port to connect to. - * + * * @param port */ public void setPort(int port) { @@ -97,7 +98,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp /** * Configures the {@link PersistenceExceptionTranslator} to use. - * + * * @param exceptionTranslator */ public void setExceptionTranslator(@Nullable PersistenceExceptionTranslator exceptionTranslator) { @@ -121,7 +122,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp return exceptionTranslator.translateExceptionIfPossible(ex); } - /* + /* * (non-Javadoc) * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() */ @@ -132,14 +133,10 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp mongoClientOptions = MongoClientOptions.builder().build(); } - if (credentials == null) { - credentials = Collections.emptyList(); - } - return createMongoClient(); } - /* + /* * (non-Javadoc) * @see org.springframework.beans.factory.config.AbstractFactoryBean#destroyInstance(java.lang.Object) */ @@ -170,7 +167,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean imp /** * Returns the given array as {@link List} with all {@literal null} elements removed. - * + * * @param elements the elements to filter , can be {@literal null}. * @return a new unmodifiable {@link List#} from the given elements without {@literal null}s. */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java index b185e2cb1..78e29dfc3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java @@ -20,6 +20,7 @@ import javax.net.ssl.SSLSocketFactory; import org.springframework.beans.factory.config.AbstractFactoryBean; import org.springframework.data.mongodb.MongoDbFactory; +import org.springframework.lang.Nullable; import com.mongodb.DBDecoderFactory; import com.mongodb.DBEncoderFactory; @@ -27,7 +28,6 @@ import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import org.springframework.lang.Nullable; /** * A factory bean for construction of a {@link MongoClientOptions} instance. @@ -41,7 +41,7 @@ public class MongoClientOptionsFactoryBean extends AbstractFactoryBean persistentEntity, Update update) { + private void increaseVersionForUpdateIfNecessary(@Nullable MongoPersistentEntity persistentEntity, Update update) { if (persistentEntity != null && persistentEntity.hasVersionProperty()) { String versionFieldName = persistentEntity.getRequiredVersionProperty().getFieldName(); @@ -1465,18 +1466,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } } - private boolean documentContainsVersionProperty(Document document, MongoPersistentEntity persistentEntity) { - - if (persistentEntity != null && persistentEntity.hasVersionProperty()) { - - MongoPersistentProperty property = persistentEntity.getRequiredVersionProperty(); - - return document.containsKey(property.getFieldName()); - } - - return false; - } - @Override public DeleteResult remove(Object object) { @@ -2191,7 +2180,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, MongoPersistentEntity entity = mappingContext.getPersistentEntity(entityClass); Document mappedQuery = queryMapper.getMappedObject(query, entity); - Document mappedFields = fields == null ? null : queryMapper.getMappedObject(fields, entity); + Document mappedFields = queryMapper.getMappedObject(fields, entity); if (LOGGER.isDebugEnabled()) { LOGGER.debug("findOne using query: {} fields: {} for class: {} in collection: {}", serializeToJsonSafely(query), @@ -2318,7 +2307,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } protected T doFindAndModify(String collectionName, Document query, Document fields, Document sort, - Class entityClass, Update update, FindAndModifyOptions options) { + Class entityClass, Update update, @Nullable FindAndModifyOptions options) { EntityReader readerToUse = this.mongoConverter; @@ -2469,7 +2458,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } private void executeQueryInternal(CollectionCallback> collectionCallback, - CursorPreparer preparer, DocumentCallbackHandler callbackHandler, String collectionName) { + @Nullable CursorPreparer preparer, DocumentCallbackHandler callbackHandler, String collectionName) { try { @@ -2502,17 +2491,20 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, return exceptionTranslator; } + @Nullable private MongoPersistentEntity getPersistentEntity(@Nullable Class type) { return type != null ? mappingContext.getPersistentEntity(type) : null; } + @Nullable private MongoPersistentProperty getIdPropertyFor(Class type) { MongoPersistentEntity persistentEntity = getPersistentEntity(type); return persistentEntity != null ? persistentEntity.getIdProperty() : null; } - private String determineEntityCollectionName(T obj) { + @Nullable + private String determineEntityCollectionName(@Nullable T obj) { if (null != obj) { return determineCollectionName(obj.getClass()); } @@ -2520,7 +2512,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, return null; } - String determineCollectionName(Class entityClass) { + String determineCollectionName(@Nullable Class entityClass) { if (entityClass == null) { throw new InvalidDataAccessApiUsageException( @@ -2530,7 +2522,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, return mappingContext.getRequiredPersistentEntity(entityClass).getCollection(); } - private static final MongoConverter getDefaultMongoConverter(MongoDbFactory factory) { + private static MongoConverter getDefaultMongoConverter(MongoDbFactory factory) { DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory); MongoCustomConversions conversions = new MongoCustomConversions(Collections.emptyList()); @@ -2570,8 +2562,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, */ private Document addFieldsForProjection(Document fields, Class domainType, Class targetType) { - if ((fields != null && !fields.isEmpty()) || !targetType.isInterface() - || ClassUtils.isAssignable(domainType, targetType)) { + if (!fields.isEmpty() || !targetType.isInterface() || ClassUtils.isAssignable(domainType, targetType)) { return fields; } @@ -2615,7 +2606,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, public FindOneCallback(Document query, Document fields) { this.query = query; - this.fields = Optional.ofNullable(fields).filter(it -> !ObjectUtils.isEmpty(fields)); + this.fields = Optional.of(fields).filter(it -> !ObjectUtils.isEmpty(fields)); } public Document doInCollection(MongoCollection collection) throws MongoException, DataAccessException { @@ -2701,7 +2692,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, private final Document sort; private final Optional collation; - public FindAndRemoveCallback(Document query, Document fields, Document sort, Collation collation) { + public FindAndRemoveCallback(Document query, Document fields, Document sort, @Nullable Collation collation) { this.query = query; this.fields = fields; @@ -2790,7 +2781,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } @Nullable - public T doWith(@Nullable Document object) { + public T doWith(Document object) { if (null != object) { maybeEmitEvent(new AfterLoadEvent(object, type, collectionName)); } @@ -2878,8 +2869,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, class QueryCursorPreparer implements CursorPreparer { - private final Query query; - private final Class type; + private final @Nullable Query query; + private final @Nullable Class type; public QueryCursorPreparer(@Nullable Query query, @Nullable Class type) { @@ -3001,7 +2992,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, @AllArgsConstructor(access = AccessLevel.PACKAGE) static class CloseableIterableCursorAdapter implements CloseableIterator { - private volatile MongoCursor cursor; + private volatile @Nullable MongoCursor cursor; private PersistenceExceptionTranslator exceptionTranslator; private DocumentCallback objectReadCallback; @@ -3023,6 +3014,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, @Override public boolean hasNext() { + MongoCursor cursor = this.cursor; + if (cursor == null) { return false; } @@ -3034,6 +3027,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } } + @Nullable @Override public T next() { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java index 117943bf0..6019229e3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReactiveMongoTemplate.java @@ -230,7 +230,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati mappingContext = this.mongoConverter.getMappingContext(); // We create indexes based on mapping events - if (null != mappingContext && mappingContext instanceof MongoMappingContext) { + if (mappingContext instanceof MongoMappingContext) { indexCreator = new MongoPersistentEntityIndexCreator((MongoMappingContext) mappingContext, (collectionName) -> IndexOperationsAdapter.blocking(indexOps(collectionName))); eventPublisher = new MongoMappingEventPublisher(indexCreator); @@ -643,7 +643,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati * (non-Javadoc) * @see org.springframework.data.mongodb.core.ReactiveMongoOperations#find(org.springframework.data.mongodb.core.query.Query, java.lang.Class, java.lang.String) */ - public Flux find(final Query query, Class entityClass, String collectionName) { + public Flux find(@Nullable Query query, Class entityClass, String collectionName) { if (query == null) { return findAll(entityClass, collectionName); @@ -908,7 +908,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati * (non-Javadoc) * @see org.springframework.data.mongodb.core.ReactiveMongoOperations#count(org.springframework.data.mongodb.core.query.Query, java.lang.Class, java.lang.String) */ - public Mono count(final Query query, @Nullable Class entityClass, String collectionName) { + public Mono count(@Nullable Query query, @Nullable Class entityClass, String collectionName) { Assert.hasText(collectionName, "Collection name must not be null or empty!"); @@ -1055,7 +1055,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati Mono>> prepareDocuments = Flux.fromIterable(batchToSave) .flatMap(new Function>>() { @Override - public Flux> apply(@Nullable T o) { + public Flux> apply(T o) { initializeVersionProperty(o); maybeEmitEvent(new BeforeConvertEvent(o, collectionName)); @@ -1245,7 +1245,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati } private MongoCollection prepareCollection(MongoCollection collection, - WriteConcern writeConcernToUse) { + @Nullable WriteConcern writeConcernToUse) { MongoCollection collectionToUse = collection; if (writeConcernToUse != null) { @@ -1359,7 +1359,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati return doUpdate(collectionName, query, update, entityClass, false, true); } - protected Mono doUpdate(final String collectionName, final Query query, final Update update, + protected Mono doUpdate(final String collectionName, @Nullable Query query, @Nullable Update update, @Nullable Class entityClass, final boolean upsert, final boolean multi) { MongoPersistentEntity entity = entityClass == null ? null : getPersistentEntity(entityClass); @@ -1411,7 +1411,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati return result.next(); } - private void increaseVersionForUpdateIfNecessary(MongoPersistentEntity persistentEntity, Update update) { + private void increaseVersionForUpdateIfNecessary(@Nullable MongoPersistentEntity persistentEntity, Update update) { if (persistentEntity != null && persistentEntity.hasVersionProperty()) { String versionFieldName = persistentEntity.getRequiredVersionProperty().getFieldName(); @@ -1421,7 +1421,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati } } - private boolean dbObjectContainsVersionProperty(Document document, MongoPersistentEntity persistentEntity) { + private boolean dbObjectContainsVersionProperty(Document document, + @Nullable MongoPersistentEntity persistentEntity) { if (persistentEntity == null || !persistentEntity.hasVersionProperty()) { return false; @@ -1894,15 +1895,14 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati * For cases where {@code fields} is {@literal null} or {@literal empty} add fields required for creating the * projection (target) type if the {@code targetType} is a {@literal closed interface projection}. * - * @param fields can be {@literal null}. + * @param fields must not be {@literal null}. * @param domainType must not be {@literal null}. * @param targetType must not be {@literal null}. * @return {@link Document} with fields to be included. */ private Document addFieldsForProjection(Document fields, Class domainType, Class targetType) { - if ((fields != null && !fields.isEmpty()) || !targetType.isInterface() - || ClassUtils.isAssignable(domainType, targetType)) { + if (!fields.isEmpty() || !targetType.isInterface() || ClassUtils.isAssignable(domainType, targetType)) { return fields; } @@ -1915,9 +1915,10 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati return fields; } - protected CreateCollectionOptions convertToCreateCollectionOptions(CollectionOptions collectionOptions) { + protected CreateCollectionOptions convertToCreateCollectionOptions(@Nullable CollectionOptions collectionOptions) { CreateCollectionOptions result = new CreateCollectionOptions(); + if (collectionOptions != null) { collectionOptions.getCapped().ifPresent(result::capped); @@ -1925,6 +1926,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati collectionOptions.getMaxDocuments().ifPresent(result::maxDocuments); collectionOptions.getCollation().map(Collation::toMongoCollation).ifPresent(result::collation); } + return result; } @@ -2071,18 +2073,20 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati * The returned {@link WriteConcern} will be defaulted to {@link WriteConcern#ACKNOWLEDGED} when * {@link WriteResultChecking} is set to {@link WriteResultChecking#EXCEPTION}. * - * @param mongoAction any WriteConcern already configured or null - * @return The prepared WriteConcern or null + * @param mongoAction any WriteConcern already configured or {@literal null}. + * @return The prepared WriteConcern or {@literal null}. * @see #setWriteConcern(WriteConcern) * @see #setWriteConcernResolver(WriteConcernResolver) */ + @Nullable protected WriteConcern prepareWriteConcern(MongoAction mongoAction) { WriteConcern wc = writeConcernResolver.resolve(mongoAction); return potentiallyForceAcknowledgedWrite(wc); } - private WriteConcern potentiallyForceAcknowledgedWrite(WriteConcern wc) { + @Nullable + private WriteConcern potentiallyForceAcknowledgedWrite(@Nullable WriteConcern wc) { if (ObjectUtils.nullSafeEquals(WriteResultChecking.EXCEPTION, writeResultChecking) && MongoClientVersion.isMongo3Driver()) { @@ -2126,7 +2130,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati * * @param collectionCallback the callback to retrieve the {@link FindPublisher} with, must not be {@literal null}. * @param preparer the {@link FindPublisherPreparer} to potentially modify the {@link FindPublisher} before iterating - * over it, may be {@literal null} + * over it, may be {@literal null}. * @param objectCallback the {@link DocumentCallback} to transform {@link Document}s into the actual domain type, must * not be {@literal null}. * @param collectionName the collection to be queried, must not be {@literal null}. @@ -2189,17 +2193,23 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati return resolved == null ? ex : resolved; } - private MongoPersistentEntity getPersistentEntity(Class type) { + @Nullable + private MongoPersistentEntity getPersistentEntity(@Nullable Class type) { return type == null ? null : mappingContext.getPersistentEntity(type); } - private MongoPersistentProperty getIdPropertyFor(Class type) { + @Nullable + private MongoPersistentProperty getIdPropertyFor(@Nullable Class type) { + + if (type == null) { + return null; + } MongoPersistentEntity persistentEntity = mappingContext.getPersistentEntity(type); return persistentEntity != null ? persistentEntity.getIdProperty() : null; } - private String determineEntityCollectionName(T obj) { + private String determineEntityCollectionName(@Nullable T obj) { if (null != obj) { return determineCollectionName(obj.getClass()); @@ -2296,7 +2306,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati private final Optional fields; private final Optional collation; - FindOneCallback(Document query, Document fields, Collation collation) { + FindOneCallback(Document query, @Nullable Document fields, @Nullable Collation collation) { this.query = query; this.fields = Optional.ofNullable(fields); this.collation = Optional.ofNullable(collation); @@ -2332,8 +2342,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati */ private static class FindCallback implements ReactiveCollectionQueryCallback { - private final Document query; - private final Document fields; + private final @Nullable Document query; + private final @Nullable Document fields; FindCallback(@Nullable Document query) { this(query, null); @@ -2375,7 +2385,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati private final Document sort; private final Optional collation; - FindAndRemoveCallback(Document query, Document fields, Document sort, Collation collation) { + FindAndRemoveCallback(Document query, Document fields, Document sort, @Nullable Collation collation) { this.query = query; this.fields = fields; @@ -2514,7 +2524,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati this.collectionName = collectionName; } - public T doWith(Document object) { + public T doWith(@Nullable Document object) { if (null != object) { maybeEmitEvent(new AfterLoadEvent(object, type, collectionName)); @@ -2545,7 +2555,8 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati private final @NonNull Class targetType; private final @NonNull String collectionName; - public T doWith(Document object) { + @Nullable + public T doWith(@Nullable Document object) { if (object == null) { return null; @@ -2609,10 +2620,10 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati */ class QueryFindPublisherPreparer implements FindPublisherPreparer { - private final Query query; - private final Class type; + private final @Nullable Query query; + private final @Nullable Class type; - QueryFindPublisherPreparer(Query query, Class type) { + QueryFindPublisherPreparer(@Nullable Query query, @Nullable Class type) { this.query = query; this.type = type; @@ -2699,6 +2710,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati } @Override + @Nullable public DBRef createDbRef(org.springframework.data.mongodb.core.mapping.DBRef annotation, MongoPersistentEntity entity, Object id) { return null; @@ -2711,7 +2723,7 @@ public class ReactiveMongoTemplate implements ReactiveMongoOperations, Applicati @Override public List bulkFetch(List dbRefs) { - return null; + return Collections.emptyList(); } } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java index a56bd8f59..dab1f69fe 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Aggregation.java @@ -32,6 +32,7 @@ import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.CriteriaDefinition; import org.springframework.data.mongodb.core.query.NearQuery; import org.springframework.data.mongodb.core.query.SerializationUtils; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -619,7 +620,7 @@ public class Aggregation { * @param fieldRef may be {@literal null}. * @return */ - public static boolean isReferingToSystemVariable(String fieldRef) { + public static boolean isReferingToSystemVariable(@Nullable String fieldRef) { if (fieldRef == null || !fieldRef.startsWith(PREFIX) || fieldRef.length() <= 2) { return false; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationExpressionTransformer.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationExpressionTransformer.java index ee08f35db..84b5ec081 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationExpressionTransformer.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationExpressionTransformer.java @@ -1,5 +1,5 @@ /* - * Copyright 2013 the original author or authors. + * Copyright 2013-2017 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. @@ -21,14 +21,16 @@ import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldRefe import org.springframework.data.mongodb.core.spel.ExpressionNode; import org.springframework.data.mongodb.core.spel.ExpressionTransformationContextSupport; import org.springframework.data.mongodb.core.spel.ExpressionTransformer; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Interface to type an {@link ExpressionTransformer} to the contained * {@link AggregationExpressionTransformationContext}. - * + * * @author Oliver Gierke * @author Christoph Strobl + * @author Mark Paluch * @since 1.4 */ interface AggregationExpressionTransformer @@ -36,7 +38,7 @@ interface AggregationExpressionTransformer /** * A special {@link ExpressionTransformationContextSupport} to be aware of the {@link AggregationOperationContext}. - * + * * @author Oliver Gierke * @author Thomas Darimont */ @@ -47,14 +49,14 @@ interface AggregationExpressionTransformer /** * Creates an {@link AggregationExpressionTransformationContext}. - * + * * @param currentNode must not be {@literal null}. - * @param parentNode - * @param previousOperationObject + * @param parentNode may be {@literal null}. + * @param previousOperationObject may be {@literal null}. * @param aggregationContext must not be {@literal null}. */ - public AggregationExpressionTransformationContext(T currentNode, ExpressionNode parentNode, - Document previousOperationObject, AggregationOperationContext context) { + public AggregationExpressionTransformationContext(T currentNode, @Nullable ExpressionNode parentNode, + @Nullable Document previousOperationObject, AggregationOperationContext context) { super(currentNode, parentNode, previousOperationObject); @@ -64,7 +66,7 @@ interface AggregationExpressionTransformer /** * Returns the underlying {@link AggregationOperationContext}. - * + * * @return */ public AggregationOperationContext getAggregationContext() { @@ -73,7 +75,7 @@ interface AggregationExpressionTransformer /** * Returns the {@link FieldReference} for the current {@link ExpressionNode}. - * + * * @return */ public FieldReference getFieldReference() { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationOptions.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationOptions.java index 7fefc4682..7a50de10d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationOptions.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationOptions.java @@ -71,7 +71,8 @@ public class AggregationOptions { * @param collation collation for string comparison. Can be {@literal null}. * @since 2.0 */ - public AggregationOptions(boolean allowDiskUse, boolean explain, Document cursor, Collation collation) { + public AggregationOptions(boolean allowDiskUse, boolean explain, @Nullable Document cursor, + @Nullable Collation collation) { this.allowDiskUse = allowDiskUse; this.explain = explain; @@ -301,7 +302,7 @@ public class AggregationOptions { * @param collation can be {@literal null}. * @return */ - public Builder collation(Collation collation) { + public Builder collation(@Nullable Collation collation) { this.collation = collation; return this; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationResults.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationResults.java index c45d34a82..725a9c0fe 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationResults.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/AggregationResults.java @@ -20,11 +20,12 @@ import java.util.Iterator; import java.util.List; import org.bson.Document; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Collects the results of executing an aggregation operation. - * + * * @author Tobias Trelle * @author Oliver Gierke * @author Thomas Darimont @@ -37,11 +38,11 @@ public class AggregationResults implements Iterable { private final List mappedResults; private final Document rawResults; - private final String serverUsed; + private final @Nullable String serverUsed; /** * Creates a new {@link AggregationResults} instance from the given mapped and raw results. - * + * * @param mappedResults must not be {@literal null}. * @param rawResults must not be {@literal null}. */ @@ -57,7 +58,7 @@ public class AggregationResults implements Iterable { /** * Returns the aggregation results. - * + * * @return */ public List getMappedResults() { @@ -66,10 +67,11 @@ public class AggregationResults implements Iterable { /** * Returns the unique mapped result. Assumes no result or exactly one. - * + * * @return * @throws IllegalArgumentException in case more than one result is available. */ + @Nullable public T getUniqueMappedResult() { Assert.isTrue(mappedResults.size() < 2, "Expected unique result or null, but got more than one!"); return mappedResults.size() == 1 ? mappedResults.get(0) : null; @@ -85,16 +87,17 @@ public class AggregationResults implements Iterable { /** * Returns the server that has been used to perform the aggregation. - * + * * @return */ + @Nullable public String getServerUsed() { return serverUsed; } /** * Returns the raw result that was returned by the server. - * + * * @return * @since 1.6 */ @@ -102,6 +105,7 @@ public class AggregationResults implements Iterable { return rawResults; } + @Nullable private String parseServerUsed() { Object object = rawResults.get("serverUsed"); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ArithmeticOperators.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ArithmeticOperators.java index 43f0c3d1a..54f3c430b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ArithmeticOperators.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ArithmeticOperators.java @@ -92,7 +92,7 @@ public class ArithmeticOperators { * @return */ public Abs abs() { - return fieldReference != null ? Abs.absoluteValueOf(fieldReference) : Abs.absoluteValueOf(expression); + return usesFieldRef() ? Abs.absoluteValueOf(fieldReference) : Abs.absoluteValueOf(expression); } /** @@ -134,7 +134,7 @@ public class ArithmeticOperators { } private Add createAdd() { - return fieldReference != null ? Add.valueOf(fieldReference) : Add.valueOf(expression); + return usesFieldRef() ? Add.valueOf(fieldReference) : Add.valueOf(expression); } /** @@ -144,7 +144,7 @@ public class ArithmeticOperators { * @return */ public Ceil ceil() { - return fieldReference != null ? Ceil.ceilValueOf(fieldReference) : Ceil.ceilValueOf(expression); + return usesFieldRef() ? Ceil.ceilValueOf(fieldReference) : Ceil.ceilValueOf(expression); } /** @@ -186,7 +186,7 @@ public class ArithmeticOperators { } private Divide createDivide() { - return fieldReference != null ? Divide.valueOf(fieldReference) : Divide.valueOf(expression); + return usesFieldRef() ? Divide.valueOf(fieldReference) : Divide.valueOf(expression); } /** @@ -195,7 +195,7 @@ public class ArithmeticOperators { * @return */ public Exp exp() { - return fieldReference != null ? Exp.expValueOf(fieldReference) : Exp.expValueOf(expression); + return usesFieldRef() ? Exp.expValueOf(fieldReference) : Exp.expValueOf(expression); } /** @@ -205,7 +205,7 @@ public class ArithmeticOperators { * @return */ public Floor floor() { - return fieldReference != null ? Floor.floorValueOf(fieldReference) : Floor.floorValueOf(expression); + return usesFieldRef() ? Floor.floorValueOf(fieldReference) : Floor.floorValueOf(expression); } /** @@ -215,7 +215,7 @@ public class ArithmeticOperators { * @return */ public Ln ln() { - return fieldReference != null ? Ln.lnValueOf(fieldReference) : Ln.lnValueOf(expression); + return usesFieldRef() ? Ln.lnValueOf(fieldReference) : Ln.lnValueOf(expression); } /** @@ -258,7 +258,7 @@ public class ArithmeticOperators { } private Log createLog() { - return fieldReference != null ? Log.valueOf(fieldReference) : Log.valueOf(expression); + return usesFieldRef() ? Log.valueOf(fieldReference) : Log.valueOf(expression); } /** @@ -267,7 +267,7 @@ public class ArithmeticOperators { * @return */ public Log10 log10() { - return fieldReference != null ? Log10.log10ValueOf(fieldReference) : Log10.log10ValueOf(expression); + return usesFieldRef() ? Log10.log10ValueOf(fieldReference) : Log10.log10ValueOf(expression); } /** @@ -310,7 +310,7 @@ public class ArithmeticOperators { } private Mod createMod() { - return fieldReference != null ? Mod.valueOf(fieldReference) : Mod.valueOf(expression); + return usesFieldRef() ? Mod.valueOf(fieldReference) : Mod.valueOf(expression); } /** @@ -350,7 +350,7 @@ public class ArithmeticOperators { } private Multiply createMultiply() { - return fieldReference != null ? Multiply.valueOf(fieldReference) : Multiply.valueOf(expression); + return usesFieldRef() ? Multiply.valueOf(fieldReference) : Multiply.valueOf(expression); } /** @@ -390,7 +390,7 @@ public class ArithmeticOperators { } private Pow createPow() { - return fieldReference != null ? Pow.valueOf(fieldReference) : Pow.valueOf(expression); + return usesFieldRef() ? Pow.valueOf(fieldReference) : Pow.valueOf(expression); } /** @@ -399,7 +399,7 @@ public class ArithmeticOperators { * @return */ public Sqrt sqrt() { - return fieldReference != null ? Sqrt.sqrtOf(fieldReference) : Sqrt.sqrtOf(expression); + return usesFieldRef() ? Sqrt.sqrtOf(fieldReference) : Sqrt.sqrtOf(expression); } /** @@ -439,7 +439,7 @@ public class ArithmeticOperators { } private Subtract createSubtract() { - return fieldReference != null ? Subtract.valueOf(fieldReference) : Subtract.valueOf(expression); + return usesFieldRef() ? Subtract.valueOf(fieldReference) : Subtract.valueOf(expression); } /** @@ -448,7 +448,7 @@ public class ArithmeticOperators { * @return */ public Trunc trunc() { - return fieldReference != null ? Trunc.truncValueOf(fieldReference) : Trunc.truncValueOf(expression); + return usesFieldRef() ? Trunc.truncValueOf(fieldReference) : Trunc.truncValueOf(expression); } /** @@ -457,7 +457,7 @@ public class ArithmeticOperators { * @return */ public Sum sum() { - return fieldReference != null ? AccumulatorOperators.Sum.sumOf(fieldReference) + return usesFieldRef() ? AccumulatorOperators.Sum.sumOf(fieldReference) : AccumulatorOperators.Sum.sumOf(expression); } @@ -467,7 +467,7 @@ public class ArithmeticOperators { * @return */ public Avg avg() { - return fieldReference != null ? AccumulatorOperators.Avg.avgOf(fieldReference) + return usesFieldRef() ? AccumulatorOperators.Avg.avgOf(fieldReference) : AccumulatorOperators.Avg.avgOf(expression); } @@ -477,7 +477,7 @@ public class ArithmeticOperators { * @return */ public Max max() { - return fieldReference != null ? AccumulatorOperators.Max.maxOf(fieldReference) + return usesFieldRef() ? AccumulatorOperators.Max.maxOf(fieldReference) : AccumulatorOperators.Max.maxOf(expression); } @@ -487,7 +487,7 @@ public class ArithmeticOperators { * @return */ public Min min() { - return fieldReference != null ? AccumulatorOperators.Min.minOf(fieldReference) + return usesFieldRef() ? AccumulatorOperators.Min.minOf(fieldReference) : AccumulatorOperators.Min.minOf(expression); } @@ -497,7 +497,7 @@ public class ArithmeticOperators { * @return */ public StdDevPop stdDevPop() { - return fieldReference != null ? AccumulatorOperators.StdDevPop.stdDevPopOf(fieldReference) + return usesFieldRef() ? AccumulatorOperators.StdDevPop.stdDevPopOf(fieldReference) : AccumulatorOperators.StdDevPop.stdDevPopOf(expression); } @@ -507,9 +507,13 @@ public class ArithmeticOperators { * @return */ public StdDevSamp stdDevSamp() { - return fieldReference != null ? AccumulatorOperators.StdDevSamp.stdDevSampOf(fieldReference) + return usesFieldRef() ? AccumulatorOperators.StdDevSamp.stdDevSampOf(fieldReference) : AccumulatorOperators.StdDevSamp.stdDevSampOf(expression); } + + private boolean usesFieldRef() { + return fieldReference != null; + } } /** diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ComparisonOperators.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ComparisonOperators.java index 282463423..59f79e4ca 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ComparisonOperators.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ComparisonOperators.java @@ -1,5 +1,5 @@ /* - * Copyright 2016. the original author or authors. + * Copyright 2016-2017 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. diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFields.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFields.java index ce51f4062..3b4bc2423 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFields.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFields.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 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. @@ -22,14 +22,14 @@ import java.util.Iterator; import java.util.List; import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField; -import org.springframework.data.mongodb.core.aggregation.Fields.AggregationField; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CompositeIterator; import org.springframework.util.ObjectUtils; /** * Value object to capture the fields exposed by an {@link AggregationOperation}. - * + * * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch @@ -43,9 +43,19 @@ public final class ExposedFields implements Iterable { private final List originalFields; private final List syntheticFields; + /** + * Returns an empty {@link ExposedFields} instance. + * + * @return + * @since 2.0 + */ + public static ExposedFields empty() { + return EMPTY; + } + /** * Creates a new {@link ExposedFields} instance from the given {@link ExposedField}s. - * + * * @param fields must not be {@literal null}. * @return */ @@ -55,7 +65,7 @@ public final class ExposedFields implements Iterable { /** * Creates a new {@link ExposedFields} instance from the given {@link ExposedField}s. - * + * * @param fields must not be {@literal null}. * @return */ @@ -72,7 +82,7 @@ public final class ExposedFields implements Iterable { /** * Creates synthetic {@link ExposedFields} from the given {@link Fields}. - * + * * @param fields must not be {@literal null}. * @return */ @@ -82,7 +92,7 @@ public final class ExposedFields implements Iterable { /** * Creates non-synthetic {@link ExposedFields} from the given {@link Fields}. - * + * * @param fields must not be {@literal null}. * @return */ @@ -92,7 +102,7 @@ public final class ExposedFields implements Iterable { /** * Creates a new {@link ExposedFields} instance for the given fields in either synthetic or non-synthetic way. - * + * * @param fields must not be {@literal null}. * @param synthetic * @return @@ -111,7 +121,7 @@ public final class ExposedFields implements Iterable { /** * Creates a new {@link ExposedFields} with the given originals and synthetics. - * + * * @param originals must not be {@literal null}. * @param synthetic must not be {@literal null}. */ @@ -123,7 +133,7 @@ public final class ExposedFields implements Iterable { /** * Creates a new {@link ExposedFields} adding the given {@link ExposedField}. - * + * * @param field must not be {@literal null}. * @return */ @@ -140,10 +150,11 @@ public final class ExposedFields implements Iterable { /** * Returns the field with the given name or {@literal null} if no field with the given name is available. - * + * * @param name * @return */ + @Nullable public ExposedField getField(String name) { for (ExposedField field : this) { @@ -157,7 +168,7 @@ public final class ExposedFields implements Iterable { /** * Returns whether the {@link ExposedFields} exposes no non-synthetic fields at all. - * + * * @return */ boolean exposesNoNonSyntheticFields() { @@ -166,7 +177,7 @@ public final class ExposedFields implements Iterable { /** * Returns whether the {@link ExposedFields} exposes a single non-synthetic field only. - * + * * @return */ boolean exposesSingleNonSyntheticFieldOnly() { @@ -175,7 +186,7 @@ public final class ExposedFields implements Iterable { /** * Returns whether the {@link ExposedFields} exposes no fields at all. - * + * * @return */ boolean exposesNoFields() { @@ -184,7 +195,7 @@ public final class ExposedFields implements Iterable { /** * Returns whether the {@link ExposedFields} exposes a single field only. - * + * * @return */ boolean exposesSingleFieldOnly() { @@ -198,7 +209,7 @@ public final class ExposedFields implements Iterable { return originalFields.size() + syntheticFields.size(); } - /* + /* * (non-Javadoc) * @see java.lang.Iterable#iterator() */ @@ -219,7 +230,7 @@ public final class ExposedFields implements Iterable { /** * A single exposed field. - * + * * @author Oliver Gierke */ static class ExposedField implements Field { @@ -229,7 +240,7 @@ public final class ExposedFields implements Iterable { /** * Creates a new {@link ExposedField} with the given key. - * + * * @param key must not be {@literal null} or empty. * @param synthetic whether the exposed field is synthetic. */ @@ -239,7 +250,7 @@ public final class ExposedFields implements Iterable { /** * Creates a new {@link ExposedField} for the given {@link Field}. - * + * * @param delegate must not be {@literal null}. * @param synthetic whether the exposed field is synthetic. */ @@ -249,7 +260,7 @@ public final class ExposedFields implements Iterable { this.synthetic = synthetic; } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.Field#getKey() */ @@ -285,7 +296,7 @@ public final class ExposedFields implements Iterable { /** * Returns whether the field can be referred to using the given name. - * + * * @param name * @return */ @@ -302,7 +313,7 @@ public final class ExposedFields implements Iterable { return String.format("AggregationField: %s, synthetic: %s", field, synthetic); } - /* + /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @@ -364,7 +375,7 @@ public final class ExposedFields implements Iterable { /** * A reference to an {@link ExposedField}. - * + * * @author Oliver Gierke */ static class DirectFieldReference implements FieldReference { @@ -373,7 +384,7 @@ public final class ExposedFields implements Iterable { /** * Creates a new {@link FieldReference} for the given {@link ExposedField}. - * + * * @param field must not be {@literal null}. */ public DirectFieldReference(ExposedField field) { @@ -408,14 +419,14 @@ public final class ExposedFields implements Iterable { @Override public String toString() { - if(getRaw().startsWith("$")) { + if (getRaw().startsWith("$")) { return getRaw(); } return String.format("$%s", getRaw()); } - /* + /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @@ -435,7 +446,7 @@ public final class ExposedFields implements Iterable { return this.field.equals(that.field); } - /* + /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFieldsAggregationOperationContext.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFieldsAggregationOperationContext.java index 1817eadfa..377a9fca6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFieldsAggregationOperationContext.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ExposedFieldsAggregationOperationContext.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 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. @@ -16,9 +16,10 @@ package org.springframework.data.mongodb.core.aggregation; import org.bson.Document; -import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField; import org.springframework.data.mongodb.core.aggregation.ExposedFields.DirectFieldReference; +import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField; import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldReference; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -53,7 +54,7 @@ class ExposedFieldsAggregationOperationContext implements AggregationOperationCo this.rootContext = rootContext; } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getMappedObject(org.bson.Document) */ @@ -62,7 +63,7 @@ class ExposedFieldsAggregationOperationContext implements AggregationOperationCo return rootContext.getMappedObject(document); } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getReference(org.springframework.data.mongodb.core.aggregation.ExposedFields.AvailableField) */ @@ -71,7 +72,7 @@ class ExposedFieldsAggregationOperationContext implements AggregationOperationCo return getReference(field, field.getTarget()); } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getReference(java.lang.String) */ @@ -83,11 +84,11 @@ class ExposedFieldsAggregationOperationContext implements AggregationOperationCo /** * Returns a {@link FieldReference} to the given {@link Field} with the given {@code name}. * - * @param field may be {@literal null} - * @param name must not be {@literal null} + * @param field may be {@literal null}. + * @param name must not be {@literal null}. * @return */ - private FieldReference getReference(Field field, String name) { + private FieldReference getReference(@Nullable Field field, String name) { Assert.notNull(name, "Name must not be null!"); @@ -100,13 +101,15 @@ class ExposedFieldsAggregationOperationContext implements AggregationOperationCo } /** - * Resolves a {@link field}/{@link name} for a {@link FieldReference} if possible. + * Resolves a {@link Field}/{@code name} for a {@link FieldReference} if possible. * - * @param field may be {@literal null} - * @param name must not be {@literal null} - * @return the resolved reference or {@literal null} + * @param field may be {@literal null}. + * @param name must not be {@literal null}. + * @return the resolved reference or {@literal null}. */ - protected FieldReference resolveExposedField(Field field, String name) { + @Nullable + protected FieldReference resolveExposedField(@Nullable Field field, String name) { + ExposedField exposedField = exposedFields.getField(name); if (exposedField != null) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Fields.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Fields.java index 2ba33412a..059285d6d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Fields.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/Fields.java @@ -23,13 +23,14 @@ import java.util.Iterator; import java.util.List; import java.util.Map; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Value object to capture a list of {@link Field} instances. - * + * * @author Oliver Gierke * @author Thomas Darimont * @since 1.3 @@ -46,7 +47,7 @@ public final class Fields implements Iterable { /** * Creates a new {@link Fields} instance from the given {@link Fields}. - * + * * @param fields must not be {@literal null} or empty. * @return */ @@ -58,7 +59,7 @@ public final class Fields implements Iterable { /** * Creates a new {@link Fields} instance for {@link Field}s with the given names. - * + * * @param names must not be {@literal null}. * @return */ @@ -77,7 +78,7 @@ public final class Fields implements Iterable { /** * Creates a {@link Field} with the given name. - * + * * @param name must not be {@literal null} or empty. * @return */ @@ -101,7 +102,7 @@ public final class Fields implements Iterable { /** * Creates a new {@link Fields} instance using the given {@link Field}s. - * + * * @param fields must not be {@literal null}. */ private Fields(List fields) { @@ -139,7 +140,7 @@ public final class Fields implements Iterable { /** * Creates a new {@link Fields} instance with a new {@link Field} of the given name added. - * + * * @param name must not be {@literal null}. * @return */ @@ -166,6 +167,7 @@ public final class Fields implements Iterable { return result; } + @Nullable public Field getField(String name) { for (Field field : fields) { @@ -177,7 +179,7 @@ public final class Fields implements Iterable { return null; } - /* + /* * (non-Javadoc) * @see java.lang.Iterable#iterator() */ @@ -196,7 +198,7 @@ public final class Fields implements Iterable { /** * Value object to encapsulate a field in an aggregation operation. - * + * * @author Oliver Gierke */ static class AggregationField implements Field { @@ -207,7 +209,7 @@ public final class Fields implements Iterable { /** * Creates an aggregation field with the given {@code name}. - * + * * @see AggregationField#AggregationField(String, String). * @param name must not be {@literal null} or empty */ @@ -220,15 +222,15 @@ public final class Fields implements Iterable { *

* The {@code name} serves as an alias for the actual backing document field denoted by {@code target}. If no target * is set explicitly, the name will be used as target. - * + * * @param name must not be {@literal null} or empty * @param target */ - public AggregationField(String name, String target) { + public AggregationField(String name, @Nullable String target) { raw = name; - String nameToSet = cleanUp(name); - String targetToSet = cleanUp(target); + String nameToSet = name != null ? cleanUp(name) : null; + String targetToSet = target != null ? cleanUp(target) : null; Assert.hasText(nameToSet, "AggregationField name must not be null or empty!"); @@ -241,11 +243,7 @@ public final class Fields implements Iterable { } } - private static final String cleanUp(String source) { - - if (source == null) { - return source; - } + private static String cleanUp(String source) { if (Aggregation.SystemVariable.isReferingToSystemVariable(source)) { return source; @@ -301,7 +299,7 @@ public final class Fields implements Iterable { return raw; } - /* + /* * (non-Javadoc) * @see java.lang.Object#toString() */ @@ -310,7 +308,7 @@ public final class Fields implements Iterable { return String.format("AggregationField - name: %s, target: %s", name, target); } - /* + /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @@ -330,7 +328,7 @@ public final class Fields implements Iterable { return this.name.equals(that.name) && ObjectUtils.nullSafeEquals(this.target, that.target); } - /* + /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/FieldsExposingAggregationOperation.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/FieldsExposingAggregationOperation.java index c17aeb7fa..96cb88c1d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/FieldsExposingAggregationOperation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/FieldsExposingAggregationOperation.java @@ -36,8 +36,6 @@ public interface FieldsExposingAggregationOperation extends AggregationOperation /** * Marker interface for {@link AggregationOperation} that inherits fields from previous operations. */ - static interface InheritsFieldsAggregationOperation extends FieldsExposingAggregationOperation { - - } + interface InheritsFieldsAggregationOperation extends FieldsExposingAggregationOperation {} } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/GroupOperation.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/GroupOperation.java index 6e3d4ab17..ed311bc2d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/GroupOperation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/GroupOperation.java @@ -19,25 +19,25 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; -import java.util.Locale; import org.bson.Document; import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField; import org.springframework.data.mongodb.core.aggregation.ExposedFields.FieldReference; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; -import org.springframework.util.StringUtils; /** * Encapsulates the aggregation framework {@code $group}-operation. *

* We recommend to use the static factory method {@link Aggregation#group(Fields)} instead of creating instances of this * class directly. - * + * * @author Sebastian Herold * @author Thomas Darimont * @author Oliver Gierke * @author Gustavo de Geus * @author Christoph Strobl + * @author Mark Paluch * @since 1.3 * @see MongoDB Aggregation Framework: $group */ @@ -52,7 +52,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link GroupOperation} including the given {@link Fields}. - * + * * @param fields must not be {@literal null}. */ public GroupOperation(Fields fields) { @@ -63,7 +63,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link GroupOperation} from the given {@link GroupOperation}. - * + * * @param groupOperation must not be {@literal null}. */ protected GroupOperation(GroupOperation groupOperation) { @@ -72,7 +72,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link GroupOperation} from the given {@link GroupOperation} and the given {@link Operation}s. - * + * * @param groupOperation * @param nextOperations */ @@ -89,7 +89,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link GroupOperation} from the current one adding the given {@link Operation}. - * + * * @param operation must not be {@literal null}. * @return */ @@ -99,7 +99,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Builder for {@link GroupOperation}s on a field. - * + * * @author Thomas Darimont */ public static final class GroupOperationBuilder { @@ -109,7 +109,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link GroupOperationBuilder} from the given {@link GroupOperation} and {@link Operation}. - * + * * @param groupOperation * @param operation */ @@ -124,7 +124,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Allows to specify an alias for the new-operation operation. - * + * * @param alias * @return */ @@ -138,7 +138,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { *

* Count expressions are emulated via {@code $sum: 1}. *

- * + * * @return */ public GroupOperationBuilder count() { @@ -147,7 +147,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for a {@code $sum}-expression for the given field-reference. - * + * * @param reference * @return */ @@ -155,13 +155,13 @@ public class GroupOperation implements FieldsExposingAggregationOperation { return sum(reference, null); } - private GroupOperationBuilder sum(String reference, Object value) { + private GroupOperationBuilder sum(@Nullable String reference, @Nullable Object value) { return newBuilder(GroupOps.SUM, reference, value); } /** * Generates an {@link GroupOperationBuilder} for an {@code $add_to_set}-expression for the given field-reference. - * + * * @param reference * @return */ @@ -171,7 +171,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $add_to_set}-expression for the given value. - * + * * @param value * @return */ @@ -179,13 +179,13 @@ public class GroupOperation implements FieldsExposingAggregationOperation { return addToSet(null, value); } - private GroupOperationBuilder addToSet(String reference, Object value) { + private GroupOperationBuilder addToSet(@Nullable String reference, @Nullable Object value) { return newBuilder(GroupOps.ADD_TO_SET, reference, value); } /** * Generates an {@link GroupOperationBuilder} for an {@code $last}-expression for the given field-reference. - * + * * @param reference * @return */ @@ -196,7 +196,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $last}-expression for the given * {@link AggregationExpression}. - * + * * @param expr * @return */ @@ -206,7 +206,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for a {@code $first}-expression for the given field-reference. - * + * * @param reference * @return */ @@ -217,7 +217,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for a {@code $first}-expression for the given * {@link AggregationExpression}. - * + * * @param expr * @return */ @@ -227,7 +227,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $avg}-expression for the given field-reference. - * + * * @param reference * @return */ @@ -238,7 +238,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $avg}-expression for the given * {@link AggregationExpression}. - * + * * @param expr * @return */ @@ -248,7 +248,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $push}-expression for the given field-reference. - * + * * @param reference * @return */ @@ -258,7 +258,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $push}-expression for the given value. - * + * * @param value * @return */ @@ -266,13 +266,13 @@ public class GroupOperation implements FieldsExposingAggregationOperation { return push(null, value); } - private GroupOperationBuilder push(String reference, Object value) { + private GroupOperationBuilder push(@Nullable String reference, @Nullable Object value) { return newBuilder(GroupOps.PUSH, reference, value); } /** * Generates an {@link GroupOperationBuilder} for an {@code $min}-expression that for the given field-reference. - * + * * @param reference * @return */ @@ -283,7 +283,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $min}-expression that for the given * {@link AggregationExpression}. - * + * * @param expr * @return */ @@ -293,7 +293,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $max}-expression that for the given field-reference. - * + * * @param reference * @return */ @@ -304,7 +304,7 @@ public class GroupOperation implements FieldsExposingAggregationOperation { /** * Generates an {@link GroupOperationBuilder} for an {@code $max}-expression that for the given * {@link AggregationExpression}. - * + * * @param expr * @return */ @@ -325,7 +325,8 @@ public class GroupOperation implements FieldsExposingAggregationOperation { } /** - * Generates an {@link GroupOperationBuilder} for an {@code $stdDevSamp}-expression that for the given {@link AggregationExpression}. + * Generates an {@link GroupOperationBuilder} for an {@code $stdDevSamp}-expression that for the given + * {@link AggregationExpression}. * * @param expr must not be {@literal null}. * @return never {@literal null}. @@ -347,7 +348,8 @@ public class GroupOperation implements FieldsExposingAggregationOperation { } /** - * Generates an {@link GroupOperationBuilder} for an {@code $stdDevPop}-expression that for the given {@link AggregationExpression}. + * Generates an {@link GroupOperationBuilder} for an {@code $stdDevPop}-expression that for the given + * {@link AggregationExpression}. * * @param expr must not be {@literal null}. * @return never {@literal null}. @@ -357,11 +359,11 @@ public class GroupOperation implements FieldsExposingAggregationOperation { return newBuilder(GroupOps.STD_DEV_POP, null, expr); } - private GroupOperationBuilder newBuilder(Keyword keyword, String reference, Object value) { + private GroupOperationBuilder newBuilder(Keyword keyword, @Nullable String reference, @Nullable Object value) { return new GroupOperationBuilder(this, new Operation(keyword, null, reference, value)); } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.AggregationOperationContext#getFields() */ @@ -421,7 +423,8 @@ public class GroupOperation implements FieldsExposingAggregationOperation { private static enum GroupOps implements Keyword { - SUM("$sum"), LAST("$last"), FIRST("$first"), PUSH("$push"), AVG("$avg"), MIN("$min"), MAX("$max"), ADD_TO_SET("$addToSet"), STD_DEV_POP("$stdDevPop"), STD_DEV_SAMP("$stdDevSamp"); + SUM("$sum"), LAST("$last"), FIRST("$first"), PUSH("$push"), AVG("$avg"), MIN("$min"), MAX("$max"), ADD_TO_SET( + "$addToSet"), STD_DEV_POP("$stdDevPop"), STD_DEV_SAMP("$stdDevSamp"); private String mongoOperator; @@ -429,7 +432,6 @@ public class GroupOperation implements FieldsExposingAggregationOperation { this.mongoOperator = mongoOperator; } - @Override public String toString() { return mongoOperator; @@ -439,11 +441,11 @@ public class GroupOperation implements FieldsExposingAggregationOperation { static class Operation implements AggregationOperation { private final Keyword op; - private final String key; - private final String reference; - private final Object value; + private final @Nullable String key; + private final @Nullable String reference; + private final @Nullable Object value; - public Operation(Keyword op, String key, String reference, Object value) { + public Operation(Keyword op, @Nullable String key, @Nullable String reference, @Nullable Object value) { this.op = op; this.key = key; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperation.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperation.java index f5d512131..2d868313f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/ProjectionOperation.java @@ -22,13 +22,13 @@ import java.util.Collections; import java.util.List; import org.bson.Document; -import org.springframework.data.mongodb.core.aggregation.VariableOperators.Let.ExpressionVariable; import org.springframework.data.mongodb.core.aggregation.ConditionalOperators.Cond; import org.springframework.data.mongodb.core.aggregation.ConditionalOperators.IfNull; import org.springframework.data.mongodb.core.aggregation.ExposedFields.ExposedField; import org.springframework.data.mongodb.core.aggregation.Fields.AggregationField; import org.springframework.data.mongodb.core.aggregation.ProjectionOperation.ProjectionOperationBuilder.FieldProjection; import org.springframework.data.mongodb.core.aggregation.VariableOperators.Let.ExpressionVariable; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -39,14 +39,15 @@ import org.springframework.util.Assert; *

* We recommend to use the static factory method {@link Aggregation#project(Fields)} instead of creating instances of * this class directly. - * + * * @author Tobias Trelle * @author Thomas Darimont * @author Oliver Gierke * @author Christoph Strobl * @author Mark Paluch * @since 1.3 - * @see MongoDB Aggregation Framework: $project + * @see MongoDB Aggregation Framework: + * $project */ public class ProjectionOperation implements FieldsExposingAggregationOperation { @@ -65,7 +66,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link ProjectionOperation} including the given {@link Fields}. - * + * * @param fields must not be {@literal null}. */ public ProjectionOperation(Fields fields) { @@ -75,7 +76,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Copy constructor to allow building up {@link ProjectionOperation} instances from already existing * {@link Projection}s. - * + * * @param current must not be {@literal null}. * @param projections must not be {@literal null}. */ @@ -91,18 +92,18 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link ProjectionOperation} with the current {@link Projection}s and the given one. - * + * * @param projection must not be {@literal null}. * @return */ private ProjectionOperation and(Projection projection) { - return new ProjectionOperation(this.projections, Arrays.asList(projection)); + return new ProjectionOperation(this.projections, Collections.singletonList(projection)); } /** * Creates a new {@link ProjectionOperation} with the current {@link Projection}s replacing the last current one with * the given one. - * + * * @param projection must not be {@literal null}. * @return */ @@ -110,12 +111,12 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { List projections = this.projections.isEmpty() ? Collections. emptyList() : this.projections.subList(0, this.projections.size() - 1); - return new ProjectionOperation(projections, Arrays.asList(projection)); + return new ProjectionOperation(projections, Collections.singletonList(projection)); } /** * Creates a new {@link ProjectionOperationBuilder} to define a projection for the field with the given name. - * + * * @param name must not be {@literal null} or empty. * @return */ @@ -133,7 +134,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Excludes the given fields from the projection. - * + * * @param fieldNames must not be {@literal null}. * @return */ @@ -150,7 +151,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Includes the given fields into the projection. - * + * * @param fieldNames must not be {@literal null}. * @return */ @@ -162,7 +163,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Includes the given fields into the projection. - * + * * @param fields must not be {@literal null}. * @return */ @@ -184,7 +185,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { fields = fields == null ? ExposedFields.from(field) : fields.and(field); } - return fields; + return fields != null ? fields : ExposedFields.empty(); } /* @@ -205,7 +206,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Base class for {@link ProjectionOperationBuilder}s. - * + * * @author Thomas Darimont */ private static abstract class AbstractProjectionOperationBuilder implements AggregationOperation { @@ -215,7 +216,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link AbstractProjectionOperationBuilder} fot the given value and {@link ProjectionOperation}. - * + * * @param value must not be {@literal null}. * @param operation must not be {@literal null}. */ @@ -228,7 +229,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { this.operation = operation; } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) */ @@ -239,7 +240,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Returns the finally to be applied {@link ProjectionOperation} with the given alias. - * + * * @param alias will never be {@literal null} or empty. * @return */ @@ -266,7 +267,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * An {@link ProjectionOperationBuilder} that is used for SpEL expression based projections. - * + * * @author Thomas Darimont */ public static class ExpressionProjectionOperationBuilder extends ProjectionOperationBuilder { @@ -277,7 +278,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link ExpressionProjectionOperationBuilder} for the given value, {@link ProjectionOperation} and * parameters. - * + * * @param expression must not be {@literal null}. * @param operation must not be {@literal null}. * @param parameters @@ -325,7 +326,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * A {@link Projection} based on a SpEL expression. - * + * * @author Thomas Darimont * @author Oliver Gierke */ @@ -338,7 +339,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link ExpressionProjection} for the given field, SpEL expression and parameters. - * + * * @param field must not be {@literal null}. * @param expression must not be {@literal null} or empty. * @param parameters must not be {@literal null}. @@ -354,7 +355,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { this.params = parameters.clone(); } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.ProjectionOperation.Projection#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) */ @@ -372,7 +373,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Builder for {@link ProjectionOperation}s on a field. - * + * * @author Oliver Gierke * @author Thomas Darimont * @author Christoph Strobl @@ -382,19 +383,19 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { private static final String NUMBER_NOT_NULL = "Number must not be null!"; private static final String FIELD_REFERENCE_NOT_NULL = "Field reference must not be null!"; - private final String name; - private final OperationProjection previousProjection; + private final @Nullable String name; + private final @Nullable OperationProjection previousProjection; /** * Creates a new {@link ProjectionOperationBuilder} for the field with the given name on top of the given * {@link ProjectionOperation}. - * + * * @param name must not be {@literal null} or empty. * @param operation must not be {@literal null}. * @param previousProjection the previous operation projection, may be {@literal null}. */ public ProjectionOperationBuilder(String name, ProjectionOperation operation, - OperationProjection previousProjection) { + @Nullable OperationProjection previousProjection) { super(name, operation); this.name = name; @@ -404,13 +405,13 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link ProjectionOperationBuilder} for the field with the given value on top of the given * {@link ProjectionOperation}. - * + * * @param value * @param operation * @param previousProjection */ protected ProjectionOperationBuilder(Object value, ProjectionOperation operation, - OperationProjection previousProjection) { + @Nullable OperationProjection previousProjection) { super(value, operation); @@ -421,28 +422,28 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Projects the result of the previous operation onto the current field. Will automatically add an exclusion for * {@code _id} as what would be held in it by default will now go into the field just projected into. - * + * * @return */ public ProjectionOperation previousOperation() { return this.operation.andExclude(Fields.UNDERSCORE_ID) // - .and(new PreviousOperationProjection(name)); + .and(new PreviousOperationProjection(getRequiredName())); } /** * Defines a nested field binding for the current field. - * + * * @param fields must not be {@literal null}. * @return */ public ProjectionOperation nested(Fields fields) { - return this.operation.and(new NestedFieldProjection(name, fields)); + return this.operation.and(new NestedFieldProjection(getRequiredName(), fields)); } /** * Allows to specify an alias for the previous projection operation. - * + * * @param alias * @return */ @@ -457,7 +458,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { return this.operation.and(new ExpressionProjection(Fields.field(alias), (AggregationExpression) value)); } - return this.operation.and(new FieldProjection(Fields.field(alias, name), null)); + return this.operation.and(new FieldProjection(Fields.field(alias, getRequiredName()), null)); } /* @@ -468,7 +469,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { public ProjectionOperation applyCondition(Cond cond) { Assert.notNull(cond, "ConditionalOperator must not be null!"); - return this.operation.and(new ExpressionProjection(Fields.field(name), cond)); + return this.operation.and(new ExpressionProjection(Fields.field(getRequiredName()), cond)); } /* @@ -479,12 +480,12 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { public ProjectionOperation applyCondition(IfNull ifNull) { Assert.notNull(ifNull, "IfNullOperator must not be null!"); - return this.operation.and(new ExpressionProjection(Fields.field(name), ifNull)); + return this.operation.and(new ExpressionProjection(Fields.field(getRequiredName()), ifNull)); } /** * Generates an {@code $add} expression that adds the given number to the previously mentioned field. - * + * * @param number * @return */ @@ -496,7 +497,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $add} expression that adds the value of the given field to the previously mentioned field. - * + * * @param fieldReference * @return */ @@ -508,7 +509,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $subtract} expression that subtracts the given number to the previously mentioned field. - * + * * @param number * @return */ @@ -521,7 +522,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $subtract} expression that subtracts the value of the given field to the previously mentioned * field. - * + * * @param fieldReference * @return */ @@ -547,7 +548,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $multiply} expression that multiplies the given number with the previously mentioned field. - * + * * @param number * @return */ @@ -560,7 +561,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $multiply} expression that multiplies the value of the given field with the previously * mentioned field. - * + * * @param fieldReference * @return */ @@ -586,7 +587,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $divide} expression that divides the previously mentioned field by the given number. - * + * * @param number * @return */ @@ -600,7 +601,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $divide} expression that divides the value of the given field by the previously mentioned * field. - * + * * @param fieldReference * @return */ @@ -627,7 +628,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Generates an {@code $mod} expression that divides the previously mentioned field by the given number and returns * the remainder. - * + * * @param number * @return */ @@ -789,7 +790,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder filter(String as, AggregationExpression condition) { - return this.operation.and(ArrayOperators.Filter.filter(name).as(as).by(condition)); + return this.operation.and(ArrayOperators.Filter.filter(getRequiredName()).as(as).by(condition)); } // SET OPERATORS @@ -894,7 +895,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder absoluteValue() { - return this.operation.and(ArithmeticOperators.Abs.absoluteValueOf(name)); + return this.operation.and(ArithmeticOperators.Abs.absoluteValueOf(getRequiredName())); } /** @@ -905,7 +906,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder ceil() { - return this.operation.and(ArithmeticOperators.Ceil.ceilValueOf(name)); + return this.operation.and(ArithmeticOperators.Ceil.ceilValueOf(getRequiredName())); } /** @@ -916,7 +917,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder exp() { - return this.operation.and(ArithmeticOperators.Exp.expValueOf(name)); + return this.operation.and(ArithmeticOperators.Exp.expValueOf(getRequiredName())); } /** @@ -927,7 +928,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder floor() { - return this.operation.and(ArithmeticOperators.Floor.floorValueOf(name)); + return this.operation.and(ArithmeticOperators.Floor.floorValueOf(getRequiredName())); } /** @@ -938,7 +939,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder ln() { - return this.operation.and(ArithmeticOperators.Ln.lnValueOf(name)); + return this.operation.and(ArithmeticOperators.Ln.lnValueOf(getRequiredName())); } /** @@ -950,7 +951,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder log(String baseFieldRef) { - return this.operation.and(ArithmeticOperators.Log.valueOf(name).log(baseFieldRef)); + return this.operation.and(ArithmeticOperators.Log.valueOf(getRequiredName()).log(baseFieldRef)); } /** @@ -962,7 +963,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder log(Number base) { - return this.operation.and(ArithmeticOperators.Log.valueOf(name).log(base)); + return this.operation.and(ArithmeticOperators.Log.valueOf(getRequiredName()).log(base)); } /** @@ -974,7 +975,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder log(AggregationExpression base) { - return this.operation.and(ArithmeticOperators.Log.valueOf(name).log(base)); + return this.operation.and(ArithmeticOperators.Log.valueOf(getRequiredName()).log(base)); } /** @@ -985,7 +986,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder log10() { - return this.operation.and(ArithmeticOperators.Log10.log10ValueOf(name)); + return this.operation.and(ArithmeticOperators.Log10.log10ValueOf(getRequiredName())); } /** @@ -997,7 +998,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder pow(String exponentFieldRef) { - return this.operation.and(ArithmeticOperators.Pow.valueOf(name).pow(exponentFieldRef)); + return this.operation.and(ArithmeticOperators.Pow.valueOf(getRequiredName()).pow(exponentFieldRef)); } /** @@ -1009,7 +1010,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder pow(Number exponent) { - return this.operation.and(ArithmeticOperators.Pow.valueOf(name).pow(exponent)); + return this.operation.and(ArithmeticOperators.Pow.valueOf(getRequiredName()).pow(exponent)); } /** @@ -1021,7 +1022,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder pow(AggregationExpression exponentExpression) { - return this.operation.and(ArithmeticOperators.Pow.valueOf(name).pow(exponentExpression)); + return this.operation.and(ArithmeticOperators.Pow.valueOf(getRequiredName()).pow(exponentExpression)); } /** @@ -1032,7 +1033,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder sqrt() { - return this.operation.and(ArithmeticOperators.Sqrt.sqrtOf(name)); + return this.operation.and(ArithmeticOperators.Sqrt.sqrtOf(getRequiredName())); } /** @@ -1042,7 +1043,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder trunc() { - return this.operation.and(ArithmeticOperators.Trunc.truncValueOf(name)); + return this.operation.and(ArithmeticOperators.Trunc.truncValueOf(getRequiredName())); } /** @@ -1089,7 +1090,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder toLower() { - return this.operation.and(StringOperators.ToLower.lowerValueOf(name)); + return this.operation.and(StringOperators.ToLower.lowerValueOf(getRequiredName())); } /** @@ -1100,7 +1101,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder toUpper() { - return this.operation.and(StringOperators.ToUpper.upperValueOf(name)); + return this.operation.and(StringOperators.ToUpper.upperValueOf(getRequiredName())); } /** @@ -1171,7 +1172,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder isArray() { - return this.operation.and(ArrayOperators.IsArray.isArray(name)); + return this.operation.and(ArrayOperators.IsArray.isArray(getRequiredName())); } /** @@ -1181,7 +1182,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder asLiteral() { - return this.operation.and(LiteralOperators.Literal.asLiteral(name)); + return this.operation.and(LiteralOperators.Literal.asLiteral(getRequiredName())); } /** @@ -1193,7 +1194,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { * @since 1.10 */ public ProjectionOperationBuilder dateAsFormattedString(String format) { - return this.operation.and(DateOperators.DateToString.dateOf(name).toString(format)); + return this.operation.and(DateOperators.DateToString.dateOf(getRequiredName()).toString(format)); } /** @@ -1225,6 +1226,13 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { return this.operation.and(VariableOperators.Let.define(variables).andApply(in)); } + private String getRequiredName() { + + Assert.state(name != null, "Projection field name must not be null!"); + + return name; + } + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.AggregationOperation#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) @@ -1236,7 +1244,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Adds a generic projection for the current field. - * + * * @param operation the operation key, e.g. {@code $add}. * @param values the values to be set for the projection operation. * @return @@ -1249,7 +1257,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * A {@link Projection} to pull in the result of the previous operation. - * + * * @author Oliver Gierke */ static class PreviousOperationProjection extends Projection { @@ -1258,7 +1266,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link PreviousOperationProjection} for the field with the given name. - * + * * @param name must not be {@literal null} or empty. */ public PreviousOperationProjection(String name) { @@ -1266,7 +1274,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { this.name = name; } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.ProjectionOperation.Projection#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) */ @@ -1278,7 +1286,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * A {@link FieldProjection} to map a result of a previous {@link AggregationOperation} to a new field. - * + * * @author Oliver Gierke * @author Thomas Darimont * @author Mark Paluch @@ -1286,11 +1294,11 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { static class FieldProjection extends Projection { private final Field field; - private final Object value; + private final @Nullable Object value; /** * Creates a new {@link FieldProjection} for the field of the given name, assigning the given value. - * + * * @param name must not be {@literal null} or empty. * @param value */ @@ -1298,7 +1306,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { this(Fields.field(name), value); } - private FieldProjection(Field field, Object value) { + private FieldProjection(Field field, @Nullable Object value) { super(new ExposedField(field.getName(), true)); @@ -1309,7 +1317,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Factory method to easily create {@link FieldProjection}s for the given {@link Fields}. Fields are projected as * references with their given name. A field {@code foo} will be projected as: {@code foo : 1 } . - * + * * @param fields the {@link Fields} to in- or exclude, must not be {@literal null}. * @return */ @@ -1319,12 +1327,12 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Factory method to easily create {@link FieldProjection}s for the given {@link Fields}. - * + * * @param fields the {@link Fields} to in- or exclude, must not be {@literal null}. * @param value to use for the given field. * @return */ - public static List from(Fields fields, Object value) { + public static List from(Fields fields, @Nullable Object value) { Assert.notNull(fields, "Fields must not be null!"); List projections = new ArrayList(); @@ -1336,7 +1344,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { return projections; } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.ProjectionOperation.Projection#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) */ @@ -1375,12 +1383,12 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link OperationProjection} for the given field. - * + * * @param field the name of the field to add the operation projection for, must not be {@literal null} or empty. * @param operation the actual operation key, must not be {@literal null} or empty. * @param values the values to pass into the operation, must not be {@literal null}. */ - public OperationProjection(Field field, String operation, Object[] values) { + OperationProjection(Field field, String operation, Object[] values) { super(field); @@ -1429,7 +1437,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Returns the field that holds the {@link OperationProjection}. - * + * * @return */ protected Field getField() { @@ -1452,11 +1460,11 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new instance of this {@link OperationProjection} with the given alias. - * + * * @param alias the alias to set * @return */ - public OperationProjection withAlias(String alias) { + OperationProjection withAlias(String alias) { final Field aliasedField = Fields.field(alias, this.field.getName()); return new OperationProjection(aliasedField, operation, values.toArray()) { @@ -1486,14 +1494,14 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { private final String name; private final Fields fields; - public NestedFieldProjection(String name, Fields fields) { + NestedFieldProjection(String name, Fields fields) { super(Fields.field(name)); this.name = name; this.fields = fields; } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.ProjectionOperation.Projection#toDocument(org.springframework.data.mongodb.core.aggregation.AggregationOperationContext) */ @@ -1512,7 +1520,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the minute from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractMinute() { @@ -1521,7 +1529,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the hour from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractHour() { @@ -1530,7 +1538,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the second from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractSecond() { @@ -1539,7 +1547,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the millisecond from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractMillisecond() { @@ -1548,7 +1556,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the year from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractYear() { @@ -1557,7 +1565,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the month from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractMonth() { @@ -1566,7 +1574,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the week from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractWeek() { @@ -1575,7 +1583,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the dayOfYear from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractDayOfYear() { @@ -1584,7 +1592,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the dayOfMonth from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractDayOfMonth() { @@ -1593,7 +1601,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Extracts the dayOfWeek from a date expression. - * + * * @return */ public ProjectionOperationBuilder extractDayOfWeek() { @@ -1603,7 +1611,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Base class for {@link Projection} implementations. - * + * * @author Oliver Gierke */ private static abstract class Projection { @@ -1612,7 +1620,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates new {@link Projection} for the given {@link Field}. - * + * * @param field must not be {@literal null}. */ public Projection(Field field) { @@ -1623,7 +1631,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Returns the field exposed by the {@link Projection}. - * + * * @return will never be {@literal null}. */ public ExposedField getExposedField() { @@ -1633,7 +1641,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Renders the current {@link Projection} into a {@link Document} based on the given * {@link AggregationOperationContext}. - * + * * @param context will never be {@literal null}. * @return */ @@ -1650,7 +1658,7 @@ public class ProjectionOperation implements FieldsExposingAggregationOperation { /** * Creates a new {@link ExpressionProjection}. - * + * * @param field * @param expression */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformer.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformer.java index d76d2b367..a0b041f8b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformer.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/SpelExpressionTransformer.java @@ -43,6 +43,7 @@ import org.springframework.expression.spel.ast.PropertyOrFieldReference; import org.springframework.expression.spel.standard.SpelExpression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.NumberUtils; import org.springframework.util.ObjectUtils; @@ -64,7 +65,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { /** * Creates a new {@link SpelExpressionTransformer}. */ - public SpelExpressionTransformer() { + SpelExpressionTransformer() { List> conversions = new ArrayList>(); conversions.add(new OperatorNodeConversion(this)); @@ -190,12 +191,12 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { * the previous context. * * @param node must not be {@literal null}. - * @param parent - * @param operation + * @param parent may be {@literal null}. + * @param operation may be {@literal null}. * @param context must not be {@literal null}. * @return */ - protected Object transform(ExpressionNode node, ExpressionNode parent, Document operation, + protected Object transform(ExpressionNode node, @Nullable ExpressionNode parent, @Nullable Document operation, AggregationExpressionTransformationContext context) { Assert.notNull(node, "ExpressionNode must not be null!"); @@ -290,7 +291,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { } private Object convertUnaryMinusOp(ExpressionTransformationContextSupport context, - Object leftResult) { + @Nullable Object leftResult) { Object result = leftResult instanceof Number ? leftResult : new Document("$multiply", Arrays. asList(Integer.valueOf(-1), leftResult)); @@ -320,7 +321,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { */ private static class IndexerNodeConversion extends ExpressionNodeConversion { - public IndexerNodeConversion(AggregationExpressionTransformer transformer) { + IndexerNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } @@ -350,7 +351,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { */ private static class InlineListNodeConversion extends ExpressionNodeConversion { - public InlineListNodeConversion(AggregationExpressionTransformer transformer) { + InlineListNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } @@ -358,6 +359,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { * (non-Javadoc) * @see org.springframework.data.mongodb.core.aggregation.SpelExpressionTransformer.SpelNodeWrapper#convertSpelNodeToMongoObjectExpression(org.springframework.data.mongodb.core.aggregation.SpelExpressionTransformer.ExpressionConversionContext) */ + @Nullable @Override protected Object convert(AggregationExpressionTransformationContext context) { @@ -389,7 +391,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { */ private static class PropertyOrFieldReferenceNodeConversion extends ExpressionNodeConversion { - public PropertyOrFieldReferenceNodeConversion(AggregationExpressionTransformer transformer) { + PropertyOrFieldReferenceNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } @@ -422,7 +424,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { */ private static class LiteralNodeConversion extends ExpressionNodeConversion { - public LiteralNodeConversion(AggregationExpressionTransformer transformer) { + LiteralNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } @@ -469,7 +471,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { */ private static class MethodReferenceNodeConversion extends ExpressionNodeConversion { - public MethodReferenceNodeConversion(AggregationExpressionTransformer transformer) { + MethodReferenceNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } @@ -483,6 +485,8 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { MethodReferenceNode node = context.getCurrentNode(); AggregationMethodReference methodReference = node.getMethodReference(); + Assert.state(methodReference != null, "Cannot resolve current node to AggregationMethodReference!"); + Object args = null; if (ObjectUtils.nullSafeEquals(methodReference.getArgumentType(), ArgumentType.SINGLE)) { @@ -519,7 +523,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { */ private static class CompoundExpressionNodeConversion extends ExpressionNodeConversion { - public CompoundExpressionNodeConversion(AggregationExpressionTransformer transformer) { + CompoundExpressionNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } @@ -561,7 +565,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { * * @param transformer must not be {@literal null}. */ - public NotOperatorNodeConversion(AggregationExpressionTransformer transformer) { + NotOperatorNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } @@ -603,7 +607,7 @@ class SpelExpressionTransformer implements AggregationExpressionTransformer { * * @param transformer must not be {@literal null}. */ - public ValueRetrievingNodeConversion(AggregationExpressionTransformer transformer) { + ValueRetrievingNodeConversion(AggregationExpressionTransformer transformer) { super(transformer); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/StringOperators.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/StringOperators.java index 2f6188d58..01f8e8c9d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/StringOperators.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/StringOperators.java @@ -1,5 +1,5 @@ /* - * Copyright 2016. the original author or authors. + * Copyright 2016-2017 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. @@ -26,6 +26,7 @@ import org.springframework.util.Assert; * Gateway to {@literal String} aggregation operations. * * @author Christoph Strobl + * @author Mark Paluch * @since 1.10 */ public class StringOperators { @@ -122,7 +123,7 @@ public class StringOperators { } private Concat createConcat() { - return fieldReference != null ? Concat.valueOf(fieldReference) : Concat.valueOf(expression); + return usesFieldRef() ? Concat.valueOf(fieldReference) : Concat.valueOf(expression); } /** @@ -149,7 +150,7 @@ public class StringOperators { } private Substr createSubstr() { - return fieldReference != null ? Substr.valueOf(fieldReference) : Substr.valueOf(expression); + return usesFieldRef() ? Substr.valueOf(fieldReference) : Substr.valueOf(expression); } /** @@ -158,7 +159,7 @@ public class StringOperators { * @return */ public ToLower toLower() { - return fieldReference != null ? ToLower.lowerValueOf(fieldReference) : ToLower.lowerValueOf(expression); + return usesFieldRef() ? ToLower.lowerValueOf(fieldReference) : ToLower.lowerValueOf(expression); } /** @@ -167,7 +168,7 @@ public class StringOperators { * @return */ public ToUpper toUpper() { - return fieldReference != null ? ToUpper.upperValueOf(fieldReference) : ToUpper.upperValueOf(expression); + return usesFieldRef() ? ToUpper.upperValueOf(fieldReference) : ToUpper.upperValueOf(expression); } /** @@ -210,7 +211,7 @@ public class StringOperators { } private StrCaseCmp createStrCaseCmp() { - return fieldReference != null ? StrCaseCmp.valueOf(fieldReference) : StrCaseCmp.valueOf(expression); + return usesFieldRef() ? StrCaseCmp.valueOf(fieldReference) : StrCaseCmp.valueOf(expression); } /** @@ -256,7 +257,7 @@ public class StringOperators { } private IndexOfBytes.SubstringBuilder createIndexOfBytesSubstringBuilder() { - return fieldReference != null ? IndexOfBytes.valueOf(fieldReference) : IndexOfBytes.valueOf(expression); + return usesFieldRef() ? IndexOfBytes.valueOf(fieldReference) : IndexOfBytes.valueOf(expression); } /** @@ -302,7 +303,7 @@ public class StringOperators { } private IndexOfCP.SubstringBuilder createIndexOfCPSubstringBuilder() { - return fieldReference != null ? IndexOfCP.valueOf(fieldReference) : IndexOfCP.valueOf(expression); + return usesFieldRef() ? IndexOfCP.valueOf(fieldReference) : IndexOfCP.valueOf(expression); } /** @@ -339,7 +340,7 @@ public class StringOperators { } private Split createSplit() { - return fieldReference != null ? Split.valueOf(fieldReference) : Split.valueOf(expression); + return usesFieldRef() ? Split.valueOf(fieldReference) : Split.valueOf(expression); } /** @@ -349,7 +350,7 @@ public class StringOperators { * @return */ public StrLenBytes length() { - return fieldReference != null ? StrLenBytes.stringLengthOf(fieldReference) + return usesFieldRef() ? StrLenBytes.stringLengthOf(fieldReference) : StrLenBytes.stringLengthOf(expression); } @@ -360,7 +361,7 @@ public class StringOperators { * @return */ public StrLenCP lengthCP() { - return fieldReference != null ? StrLenCP.stringLengthOfCP(fieldReference) : StrLenCP.stringLengthOfCP(expression); + return usesFieldRef() ? StrLenCP.stringLengthOfCP(fieldReference) : StrLenCP.stringLengthOfCP(expression); } /** @@ -387,7 +388,11 @@ public class StringOperators { } private SubstrCP createSubstrCP() { - return fieldReference != null ? SubstrCP.valueOf(fieldReference) : SubstrCP.valueOf(expression); + return usesFieldRef() ? SubstrCP.valueOf(fieldReference) : SubstrCP.valueOf(expression); + } + + private boolean usesFieldRef() { + return fieldReference != null; } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/VariableOperators.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/VariableOperators.java index 07cbc086f..14bd9f213 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/VariableOperators.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/aggregation/VariableOperators.java @@ -22,6 +22,7 @@ import java.util.List; import org.bson.Document; import org.springframework.data.mongodb.core.aggregation.VariableOperators.Let.ExpressionVariable; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -334,8 +335,8 @@ public class VariableOperators { */ public static class ExpressionVariable { - private final String variableName; - private final Object expression; + private final @Nullable String variableName; + private final @Nullable Object expression; /** * Creates new {@link ExpressionVariable}. @@ -343,7 +344,7 @@ public class VariableOperators { * @param variableName can be {@literal null}. * @param expression can be {@literal null}. */ - private ExpressionVariable(String variableName, Object expression) { + private ExpressionVariable(@Nullable String variableName, @Nullable Object expression) { this.variableName = variableName; this.expression = expression; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/AbstractMongoConverter.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/AbstractMongoConverter.java index 64a005059..e1df60048 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/AbstractMongoConverter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/AbstractMongoConverter.java @@ -102,7 +102,7 @@ public abstract class AbstractMongoConverter implements MongoConverter, Initiali */ @Override public ConversionService getConversionService() { - return conversionService != null ? conversionService : new DefaultConversionService(); + return conversionService; } /* (non-Javadoc) diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DbRefProxyHandler.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DbRefProxyHandler.java index a5612d8ab..6b6a43170 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DbRefProxyHandler.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DbRefProxyHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 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. @@ -16,13 +16,15 @@ package org.springframework.data.mongodb.core.convert; import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; +import org.springframework.lang.Nullable; import com.mongodb.DBRef; /** * @author Oliver Gierke + * @author Mark Paluch */ public interface DbRefProxyHandler { - Object populateId(MongoPersistentProperty property, DBRef source, Object proxy); + Object populateId(MongoPersistentProperty property, @Nullable DBRef source, Object proxy); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefProxyHandler.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefProxyHandler.java index 00e832b25..089a47354 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefProxyHandler.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefProxyHandler.java @@ -23,6 +23,7 @@ import org.springframework.data.mapping.model.SpELContext; import org.springframework.data.mapping.model.SpELExpressionEvaluator; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; +import org.springframework.lang.Nullable; import com.mongodb.DBRef; @@ -56,7 +57,7 @@ class DefaultDbRefProxyHandler implements DbRefProxyHandler { * @see org.springframework.data.mongodb.core.convert.DbRefProxyHandler#populateId(com.mongodb.DBRef, java.lang.Object) */ @Override - public Object populateId(MongoPersistentProperty property, DBRef source, Object proxy) { + public Object populateId(MongoPersistentProperty property, @Nullable DBRef source, Object proxy) { if (source == null) { return proxy; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java index b5a3393a7..c203d9389 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java @@ -32,7 +32,6 @@ import java.util.stream.Stream; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.bson.Document; -import org.jetbrains.annotations.NotNull; import org.springframework.aop.framework.ProxyFactory; import org.springframework.cglib.proxy.Callback; import org.springframework.cglib.proxy.Enhancer; @@ -91,7 +90,7 @@ public class DefaultDbRefResolver implements DbRefResolver { */ @Override public Object resolveDbRef(MongoPersistentProperty property, DBRef dbref, DbRefResolverCallback callback, - DbRefProxyHandler handler) { + DbRefProxyHandler handler) { Assert.notNull(property, "Property must not be null!"); Assert.notNull(callback, "Callback must not be null!"); @@ -179,8 +178,8 @@ public class DefaultDbRefResolver implements DbRefResolver { * @param callback must not be {@literal null}. * @return */ - private Object createLazyLoadingProxy(MongoPersistentProperty property, DBRef dbref, DbRefResolverCallback callback, - DbRefProxyHandler handler) { + private Object createLazyLoadingProxy(MongoPersistentProperty property, @Nullable DBRef dbref, + DbRefResolverCallback callback, DbRefProxyHandler handler) { Class propertyType = property.getType(); LazyLoadingInterceptor interceptor = new LazyLoadingInterceptor(property, dbref, exceptionTranslator, callback); @@ -234,7 +233,7 @@ public class DefaultDbRefResolver implements DbRefResolver { /** * Returns document with the given identifier from the given list of {@link Document}s. - * + * * @param identifier * @param documents * @return @@ -265,8 +264,8 @@ public class DefaultDbRefResolver implements DbRefResolver { private final PersistenceExceptionTranslator exceptionTranslator; private volatile boolean resolved; + private final @Nullable DBRef dbref; private @Nullable Object result; - private DBRef dbref; static { try { @@ -286,7 +285,7 @@ public class DefaultDbRefResolver implements DbRefResolver { * @param dbref can be {@literal null}. * @param callback must not be {@literal null}. */ - public LazyLoadingInterceptor(MongoPersistentProperty property, DBRef dbref, + public LazyLoadingInterceptor(MongoPersistentProperty property, @Nullable DBRef dbref, PersistenceExceptionTranslator exceptionTranslator, DbRefResolverCallback callback) { Assert.notNull(property, "Property must not be null!"); @@ -312,8 +311,9 @@ public class DefaultDbRefResolver implements DbRefResolver { * (non-Javadoc) * @see org.springframework.cglib.proxy.MethodInterceptor#intercept(java.lang.Object, java.lang.reflect.Method, java.lang.Object[], org.springframework.cglib.proxy.MethodProxy) */ + @Nullable @Override - public Object intercept(@Nullable Object obj, @Nullable Method method, @Nullable Object[] args, @Nullable MethodProxy proxy) throws Throwable { + public Object intercept(Object obj, Method method, Object[] args, @Nullable MethodProxy proxy) throws Throwable { if (INITIALIZE_METHOD.equals(method)) { return ensureResolved(); @@ -360,7 +360,7 @@ public class DefaultDbRefResolver implements DbRefResolver { * @param proxy * @return */ - private String proxyToString(Object proxy) { + private String proxyToString(@Nullable Object proxy) { StringBuilder description = new StringBuilder(); if (dbref != null) { @@ -381,7 +381,7 @@ public class DefaultDbRefResolver implements DbRefResolver { * @param proxy * @return */ - private int proxyHashCode(Object proxy) { + private int proxyHashCode(@Nullable Object proxy) { return proxyToString(proxy).hashCode(); } @@ -392,7 +392,7 @@ public class DefaultDbRefResolver implements DbRefResolver { * @param that * @return */ - private boolean proxyEquals(Object proxy, Object that) { + private boolean proxyEquals(@Nullable Object proxy, Object that) { if (!(that instanceof LazyLoadingProxy)) { return false; @@ -410,6 +410,7 @@ public class DefaultDbRefResolver implements DbRefResolver { * * @return */ + @Nullable private Object ensureResolved() { if (!resolved) { @@ -453,6 +454,7 @@ public class DefaultDbRefResolver implements DbRefResolver { * * @return */ + @Nullable private synchronized Object resolve() { if (!resolved) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java index 663bea394..3f25ed95c 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultMongoTypeMapper.java @@ -18,7 +18,6 @@ package org.springframework.data.mongodb.core.convert; import java.util.Arrays; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.Set; import org.bson.Document; @@ -32,6 +31,7 @@ import org.springframework.data.mapping.PersistentEntity; import org.springframework.data.mapping.context.MappingContext; import org.springframework.data.util.ClassTypeInformation; import org.springframework.data.util.TypeInformation; +import org.springframework.lang.Nullable; import org.springframework.util.ObjectUtils; import com.mongodb.BasicDBList; @@ -57,26 +57,27 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper implements M private static final TypeInformation MAP_TYPE_INFO = ClassTypeInformation.from(Map.class); private final TypeAliasAccessor accessor; - private final String typeKey; + private final @Nullable String typeKey; public DefaultMongoTypeMapper() { this(DEFAULT_TYPE_KEY); } - public DefaultMongoTypeMapper(String typeKey) { + public DefaultMongoTypeMapper(@Nullable String typeKey) { this(typeKey, Arrays.asList(new SimpleTypeInformationMapper())); } - public DefaultMongoTypeMapper(String typeKey, MappingContext, ?> mappingContext) { + public DefaultMongoTypeMapper(@Nullable String typeKey, + MappingContext, ?> mappingContext) { this(typeKey, new DocumentTypeAliasAccessor(typeKey), mappingContext, Arrays.asList(new SimpleTypeInformationMapper())); } - public DefaultMongoTypeMapper(String typeKey, List mappers) { + public DefaultMongoTypeMapper(@Nullable String typeKey, List mappers) { this(typeKey, new DocumentTypeAliasAccessor(typeKey), null, mappers); } - private DefaultMongoTypeMapper(String typeKey, TypeAliasAccessor accessor, + private DefaultMongoTypeMapper(@Nullable String typeKey, TypeAliasAccessor accessor, MappingContext, ?> mappingContext, List mappers) { @@ -99,9 +100,9 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper implements M * @see org.springframework.data.mongodb.core.convert.MongoTypeMapper#writeTypeRestrictions(java.util.Set) */ @Override - public void writeTypeRestrictions(Document result, Set> restrictedTypes) { + public void writeTypeRestrictions(Document result, @Nullable Set> restrictedTypes) { - if (restrictedTypes == null || restrictedTypes.isEmpty()) { + if (ObjectUtils.isEmpty(restrictedTypes)) { return; } @@ -111,7 +112,7 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper implements M Alias typeAlias = getAliasFor(ClassTypeInformation.from(restrictedType)); - if (typeAlias != null && !ObjectUtils.nullSafeEquals(Alias.NONE, typeAlias) && typeAlias.isPresent()) { + if (!ObjectUtils.nullSafeEquals(Alias.NONE, typeAlias) && typeAlias.isPresent()) { restrictedMappedTypes.add(typeAlias.getValue()); } } @@ -135,9 +136,9 @@ public class DefaultMongoTypeMapper extends DefaultTypeMapper implements M */ public static final class DocumentTypeAliasAccessor implements TypeAliasAccessor { - private final String typeKey; + private final @Nullable String typeKey; - public DocumentTypeAliasAccessor(String typeKey) { + public DocumentTypeAliasAccessor(@Nullable String typeKey) { this.typeKey = typeKey; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentAccessor.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentAccessor.java index 88d6e68a0..91b45af7e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentAccessor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DocumentAccessor.java @@ -23,6 +23,7 @@ import org.bson.Document; import org.bson.conversions.Bson; import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; import org.springframework.data.mongodb.util.BsonUtils; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import com.mongodb.BasicDBObject; @@ -65,7 +66,7 @@ class DocumentAccessor { * @param prop must not be {@literal null}. * @param value */ - public void put(MongoPersistentProperty prop, Object value) { + public void put(MongoPersistentProperty prop, @Nullable Object value) { Assert.notNull(prop, "MongoPersistentProperty must not be null!"); String fieldName = prop.getFieldName(); @@ -98,6 +99,7 @@ class DocumentAccessor { * @param property must not be {@literal null}. * @return */ + @Nullable public Object get(MongoPersistentProperty property) { String fieldName = property.getFieldName(); @@ -176,6 +178,7 @@ class DocumentAccessor { * @param source can be {@literal null}. * @return */ + @Nullable @SuppressWarnings("unchecked") private static Map getAsMap(Object source) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/LazyLoadingProxy.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/LazyLoadingProxy.java index 76e352d9c..82352ee05 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/LazyLoadingProxy.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/LazyLoadingProxy.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 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. @@ -16,21 +16,23 @@ package org.springframework.data.mongodb.core.convert; import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver.LazyLoadingInterceptor; +import org.springframework.lang.Nullable; import com.mongodb.DBRef; /** * Allows direct interaction with the underlying {@link LazyLoadingInterceptor}. - * + * * @author Thomas Darimont * @author Christoph Strobl + * @author Mark Paluch * @since 1.5 */ public interface LazyLoadingProxy { /** * Initializes the proxy and returns the wrapped value. - * + * * @return * @since 1.5 */ @@ -38,9 +40,10 @@ public interface LazyLoadingProxy { /** * Returns the {@link DBRef} represented by this {@link LazyLoadingProxy}, may be null. - * + * * @return * @since 1.5 */ + @Nullable DBRef toDBRef(); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java index 2422d38cc..85b554ca3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MappingMongoConverter.java @@ -147,7 +147,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App */ public void setTypeMapper(@Nullable MongoTypeMapper typeMapper) { this.typeMapper = typeMapper == null - ? new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, mappingContext) : typeMapper; + ? new DefaultMongoTypeMapper(DefaultMongoTypeMapper.DEFAULT_TYPE_KEY, mappingContext) + : typeMapper; } /* @@ -201,8 +202,9 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App return read(type, bson, ObjectPath.ROOT); } + @Nullable @SuppressWarnings("unchecked") - private S read(TypeInformation type, Bson bson, ObjectPath path) { + private S read(TypeInformation type, @Nullable Bson bson, ObjectPath path) { if (null == bson) { return null; @@ -262,6 +264,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App path); } + @Nullable private S read(final MongoPersistentEntity entity, final Document bson, final ObjectPath path) { DefaultSpELExpressionEvaluator evaluator = new DefaultSpELExpressionEvaluator(bson, spELContext); @@ -307,8 +310,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App } private void readProperties(MongoPersistentEntity entity, PersistentPropertyAccessor accessor, - MongoPersistentProperty idProperty, DocumentAccessor documentAccessor, MongoDbPropertyValueProvider valueProvider, - DbRefResolverCallback callback) { + @Nullable MongoPersistentProperty idProperty, DocumentAccessor documentAccessor, + MongoDbPropertyValueProvider valueProvider, DbRefResolverCallback callback) { for (MongoPersistentProperty prop : entity) { @@ -554,7 +557,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App } MongoPersistentEntity entity = isSubtype(prop.getType(), obj.getClass()) - ? mappingContext.getRequiredPersistentEntity(obj.getClass()) : mappingContext.getRequiredPersistentEntity(type); + ? mappingContext.getRequiredPersistentEntity(obj.getClass()) + : mappingContext.getRequiredPersistentEntity(type); Object existingValue = accessor.get(prop); Document document = existingValue instanceof Document ? (Document) existingValue : new Document(); @@ -773,7 +777,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App } return conversions.hasCustomWriteTarget(key.getClass(), String.class) - ? (String) getPotentiallyConvertedSimpleWrite(key) : key.toString(); + ? (String) getPotentiallyConvertedSimpleWrite(key) + : key.toString(); } /** @@ -795,7 +800,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App * @param value must not be {@literal null}. * @param bson must not be {@literal null}. */ - protected void addCustomTypeKeyIfNecessary(TypeInformation type, Object value, Bson bson) { + protected void addCustomTypeKeyIfNecessary(@Nullable TypeInformation type, Object value, Bson bson) { Class reference = type != null ? type.getActualType().getType() : Object.class; Class valueType = ClassUtils.getUserClass(value.getClass()); @@ -829,7 +834,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App * @param value * @return */ - private Object getPotentiallyConvertedSimpleWrite(Object value) { + @Nullable + private Object getPotentiallyConvertedSimpleWrite(@Nullable Object value) { if (value == null) { return null; @@ -860,8 +866,9 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App * @param target must not be {@literal null}. * @return */ + @Nullable @SuppressWarnings({ "rawtypes", "unchecked" }) - private Object getPotentiallyConvertedSimpleRead(Object value, Class target) { + private Object getPotentiallyConvertedSimpleRead(@Nullable Object value, Class target) { if (value == null || target == null || target.isAssignableFrom(value.getClass())) { return value; @@ -1063,7 +1070,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App String.format("Cannot read %s. as map. Given Bson must be a Document or DBObject!", bson.getClass())); } - private static void addToMap(Bson bson, String key, Object value) { + private static void addToMap(Bson bson, String key, @Nullable Object value) { if (bson instanceof Document) { ((Document) bson).put(key, value); @@ -1114,9 +1121,10 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App * (non-Javadoc) * @see org.springframework.data.mongodb.core.convert.MongoWriter#convertToMongoType(java.lang.Object, org.springframework.data.util.TypeInformation) */ + @Nullable @SuppressWarnings("unchecked") @Override - public Object convertToMongoType(Object obj, TypeInformation typeInformation) { + public Object convertToMongoType(@Nullable Object obj, TypeInformation typeInformation) { if (obj == null) { return null; @@ -1274,7 +1282,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App * * @param source must not be {@literal null}. * @param evaluator must not be {@literal null}. - * @param path can be {@literal null}. + * @param path must not be {@literal null}. */ public MongoDbPropertyValueProvider(Bson source, SpELExpressionEvaluator evaluator, ObjectPath path) { @@ -1293,7 +1301,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App * * @param accessor must not be {@literal null}. * @param evaluator must not be {@literal null}. - * @param path can be {@literal null}. + * @param path must not be {@literal null}. */ public MongoDbPropertyValueProvider(DocumentAccessor accessor, SpELExpressionEvaluator evaluator, ObjectPath path) { @@ -1310,6 +1318,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App * (non-Javadoc) * @see org.springframework.data.convert.PropertyValueProvider#getPropertyValue(org.springframework.data.mapping.PersistentProperty) */ + @Nullable public T getPropertyValue(MongoPersistentProperty property) { String expression = property.getSpelExpression(); @@ -1359,6 +1368,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App } } + @Nullable @SuppressWarnings("unchecked") T readValue(Object value, TypeInformation type, ObjectPath path) { @@ -1379,8 +1389,10 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App } } + @Nullable @SuppressWarnings("unchecked") - private T potentiallyReadOrResolveDbRef(DBRef dbref, TypeInformation type, ObjectPath path, Class rawType) { + private T potentiallyReadOrResolveDbRef(@Nullable DBRef dbref, TypeInformation type, ObjectPath path, + Class rawType) { if (rawType.equals(DBRef.class)) { return (T) dbref; @@ -1390,7 +1402,9 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App return object != null ? object : readAndConvertDBRef(dbref, type, path, rawType); } - private T readAndConvertDBRef(DBRef dbref, TypeInformation type, ObjectPath path, final Class rawType) { + @Nullable + private T readAndConvertDBRef(@Nullable DBRef dbref, TypeInformation type, ObjectPath path, + final Class rawType) { List result = bulkReadAndConvertDBRefs(Collections.singletonList(dbref), type, path, rawType); return CollectionUtils.isEmpty(result) ? null : result.iterator().next(); @@ -1420,7 +1434,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App } List referencedRawDocuments = dbrefs.size() == 1 - ? Collections.singletonList(readRef(dbrefs.iterator().next())) : bulkReadRefs(dbrefs); + ? Collections.singletonList(readRef(dbrefs.iterator().next())) + : bulkReadRefs(dbrefs); String collectionName = dbrefs.iterator().next().getCollectionName(); List targeList = new ArrayList<>(dbrefs.size()); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java index e64beb6ff..35f64d2ad 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ObjectPath.java @@ -21,6 +21,7 @@ import java.util.ArrayList; import java.util.List; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; import org.springframework.util.ObjectUtils; @@ -54,7 +55,7 @@ class ObjectPath { * Creates a new {@link ObjectPath} from the given parent {@link ObjectPath} by adding the provided * {@link ObjectPathItem} to it. * - * @param parent can be {@literal null}. + * @param parent must not be {@literal null}. * @param item */ private ObjectPath(ObjectPath parent, ObjectPath.ObjectPathItem item) { @@ -74,7 +75,7 @@ class ObjectPath { * @param id must not be {@literal null}. * @return new instance of {@link ObjectPath}. */ - ObjectPath push(Object object, MongoPersistentEntity entity, Object id) { + ObjectPath push(Object object, MongoPersistentEntity entity, @Nullable Object id) { Assert.notNull(object, "Object must not be null!"); Assert.notNull(entity, "MongoPersistentEntity must not be null!"); @@ -92,6 +93,7 @@ class ObjectPath { * @return * @deprecated use {@link #getPathItem(Object, String, Class)}. */ + @Nullable @Deprecated Object getPathItem(Object id, String collection) { @@ -124,6 +126,7 @@ class ObjectPath { * @return {@literal null} when no match found. * @since 2.0 */ + @Nullable T getPathItem(Object id, String collection, Class type) { Assert.notNull(id, "Id must not be null!"); @@ -152,6 +155,7 @@ class ObjectPath { * * @return */ + @Nullable Object getCurrentObject() { return items.length == 0 ? null : items[items.length - 1].getObject(); } @@ -187,7 +191,7 @@ class ObjectPath { private static class ObjectPathItem { Object object; - Object idValue; + @Nullable Object idValue; String collection; } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java index c45ab1d94..c28c67517 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/QueryMapper.java @@ -240,7 +240,7 @@ public class QueryMapper { * @param mappingContext * @return */ - protected Field createPropertyField(MongoPersistentEntity entity, String key, + protected Field createPropertyField(@Nullable MongoPersistentEntity entity, String key, MappingContext, MongoPersistentProperty> mappingContext) { return entity == null ? new Field(key) : new MetadataBackedField(key, entity, mappingContext); } @@ -252,7 +252,7 @@ public class QueryMapper { * @param entity * @return */ - protected Document getMappedKeyword(Keyword keyword, MongoPersistentEntity entity) { + protected Document getMappedKeyword(Keyword keyword, @Nullable MongoPersistentEntity entity) { // $or/$nor if (keyword.isOrOrNor() || (keyword.hasIterableValue() && !keyword.isGeometry())) { @@ -302,6 +302,7 @@ public class QueryMapper { * @param newKey the key the value will be bound to eventually * @return */ + @Nullable @SuppressWarnings("unchecked") protected Object getMappedValue(Field documentField, Object value) { @@ -401,7 +402,8 @@ public class QueryMapper { * @param entity * @return */ - protected Object convertSimpleOrDocument(Object source, MongoPersistentEntity entity) { + @Nullable + protected Object convertSimpleOrDocument(Object source, @Nullable MongoPersistentEntity entity) { if (source instanceof List) { return delegateConvertToMongoType(source, entity); @@ -434,6 +436,7 @@ public class QueryMapper { * @param entity * @return the converted mongo type or null if source is null */ + @Nullable protected Object delegateConvertToMongoType(Object source, @Nullable MongoPersistentEntity entity) { return converter.convertToMongoType(source, entity == null ? null : entity.getTypeInformation()); } @@ -449,7 +452,8 @@ public class QueryMapper { * @param property * @return */ - protected Object convertAssociation(Object source, MongoPersistentProperty property) { + @Nullable + protected Object convertAssociation(@Nullable Object source, @Nullable MongoPersistentProperty property) { if (property == null || source == null || source instanceof Document || source instanceof DBObject) { return source; @@ -516,7 +520,7 @@ public class QueryMapper { * Creates a new {@link Entry} with the given key and value. * * @param key must not be {@literal null} or empty. - * @param value can be {@literal null} + * @param value can be {@literal null}. * @return */ private Entry createMapEntry(String key, @Nullable Object value) { @@ -777,8 +781,8 @@ public class QueryMapper { private final MongoPersistentEntity entity; private final MappingContext, MongoPersistentProperty> mappingContext; private final MongoPersistentProperty property; - private final PersistentPropertyPath path; - private final Association association; + private final @Nullable PersistentPropertyPath path; + private final @Nullable Association association; /** * Creates a new {@link MetadataBackedField} with the given name, {@link MongoPersistentEntity} and @@ -911,6 +915,7 @@ public class QueryMapper { return path == null ? name : path.toDotPath(isAssociation() ? getAssociationConverter() : getPropertyConverter()); } + @Nullable protected PersistentPropertyPath getPath() { return path; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/UpdateMapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/UpdateMapper.java index d6de3d3c5..f2d6be356 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/UpdateMapper.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/UpdateMapper.java @@ -35,7 +35,7 @@ import org.springframework.lang.Nullable; /** * A subclass of {@link QueryMapper} that retains type information on the mongo types. - * + * * @author Thomas Darimont * @author Oliver Gierke * @author Christoph Strobl @@ -47,7 +47,7 @@ public class UpdateMapper extends QueryMapper { /** * Creates a new {@link UpdateMapper} using the given {@link MongoConverter}. - * + * * @param converter must not be {@literal null}. */ public UpdateMapper(MongoConverter converter) { @@ -102,7 +102,7 @@ public class UpdateMapper extends QueryMapper { /** * Returns {@literal true} if the given {@link Document} is an update object that uses update operators. - * + * * @param updateObj can be {@literal null}. * @return {@literal true} if the given {@link Document} is an update object. */ @@ -124,7 +124,7 @@ public class UpdateMapper extends QueryMapper { /** * Converts the given source object to a mongo type retaining the original type information of the source type on the * mongo type. - * + * * @see org.springframework.data.mongodb.core.convert.QueryMapper#delegateConvertToMongoType(java.lang.Object, * org.springframework.data.mongodb.core.mapping.MongoPersistentEntity) */ @@ -217,7 +217,7 @@ public class UpdateMapper extends QueryMapper { return converter.convertToMongoType(value, typeHint); } - private TypeInformation getTypeHintForEntity(Object source, MongoPersistentEntity entity) { + private TypeInformation getTypeHintForEntity(@Nullable Object source, MongoPersistentEntity entity) { TypeInformation info = entity.getTypeInformation(); Class type = info.getActualType().getType(); @@ -233,7 +233,7 @@ public class UpdateMapper extends QueryMapper { return NESTED_DOCUMENT; } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.convert.QueryMapper#createPropertyField(org.springframework.data.mongodb.core.mapping.MongoPersistentEntity, java.lang.String, org.springframework.data.mapping.context.MappingContext) */ @@ -261,7 +261,7 @@ public class UpdateMapper extends QueryMapper { * containing a {@literal $} before handing it to the super class to make sure property lookups and transformations * continue to work as expected. We provide a custom property converter to re-applied the cleaned up {@literal $}s * when constructing the mapped key. - * + * * @author Thomas Darimont * @author Oliver Gierke */ @@ -273,7 +273,7 @@ public class UpdateMapper extends QueryMapper { * Creates a new {@link MetadataBackedField} with the given {@link MongoPersistentEntity}, key and * {@link MappingContext}. We clean up the key before handing it up to the super class to make sure it continues to * work as expected. - * + * * @param entity must not be {@literal null}. * @param key must not be {@literal null} or empty. * @param mappingContext must not be {@literal null}. @@ -294,7 +294,7 @@ public class UpdateMapper extends QueryMapper { return this.getPath() == null ? key : super.getMappedKey(); } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.core.convert.QueryMapper.MetadataBackedField#getPropertyConverter() */ @@ -314,7 +314,7 @@ public class UpdateMapper extends QueryMapper { /** * {@link Converter} retaining positional parameter {@literal $} for {@link Association}s. - * + * * @author Christoph Strobl */ protected static class UpdateAssociationConverter extends AssociationConverter { @@ -323,7 +323,7 @@ public class UpdateMapper extends QueryMapper { /** * Creates a new {@link AssociationConverter} for the given {@link Association}. - * + * * @param association must not be {@literal null}. */ public UpdateAssociationConverter(Association association, String key) { @@ -332,7 +332,7 @@ public class UpdateMapper extends QueryMapper { this.mapper = new KeyMapper(key); } - /* + /* * (non-Javadoc) * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonModule.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonModule.java index 23955510f..e788b9202 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonModule.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonModule.java @@ -35,9 +35,10 @@ import com.fasterxml.jackson.databind.node.ArrayNode; /** * A Jackson {@link Module} to register custom {@link JsonSerializer} and {@link JsonDeserializer}s for GeoJSON types. - * + * * @author Christoph Strobl * @author Oliver Gierke + * @author Mark Paluch * @since 1.7 */ public class GeoJsonModule extends SimpleModule { @@ -64,6 +65,7 @@ public class GeoJsonModule extends SimpleModule { * (non-Javadoc) * @see com.fasterxml.jackson.databind.JsonDeserializer#deserialize(com.fasterxml.jackson.core.JsonParser, com.fasterxml.jackson.databind.DeserializationContext) */ + @Nullable @Override public T deserialize(@Nullable JsonParser jp, @Nullable DeserializationContext ctxt) throws IOException, JsonProcessingException { @@ -79,20 +81,22 @@ public class GeoJsonModule extends SimpleModule { /** * Perform the actual deserialization given the {@literal coordinates} as {@link ArrayNode}. - * + * * @param coordinates * @return */ + @Nullable protected abstract T doDeserialize(ArrayNode coordinates); /** * Get the {@link GeoJsonPoint} representation of given {@link ArrayNode} assuming {@code node.[0]} represents * {@literal x - coordinate} and {@code node.[1]} is {@literal y}. - * + * * @param node can be {@literal null}. * @return {@literal null} when given a {@code null} value. */ - protected GeoJsonPoint toGeoJsonPoint(ArrayNode node) { + @Nullable + protected GeoJsonPoint toGeoJsonPoint(@Nullable ArrayNode node) { if (node == null) { return null; @@ -104,11 +108,12 @@ public class GeoJsonModule extends SimpleModule { /** * Get the {@link Point} representation of given {@link ArrayNode} assuming {@code node.[0]} represents * {@literal x - coordinate} and {@code node.[1]} is {@literal y}. - * + * * @param node can be {@literal null}. * @return {@literal null} when given a {@code null} value. */ - protected Point toPoint(ArrayNode node) { + @Nullable + protected Point toPoint(@Nullable ArrayNode node) { if (node == null) { return null; @@ -119,11 +124,11 @@ public class GeoJsonModule extends SimpleModule { /** * Get the points nested within given {@link ArrayNode}. - * + * * @param node can be {@literal null}. * @return {@literal empty list} when given a {@code null} value. */ - protected List toPoints(ArrayNode node) { + protected List toPoints(@Nullable ArrayNode node) { if (node == null) { return Collections.emptyList(); @@ -146,13 +151,13 @@ public class GeoJsonModule extends SimpleModule { /** * {@link JsonDeserializer} converting GeoJSON representation of {@literal Point}. - * + * *
 	 * 
 	 * { "type": "Point", "coordinates": [10.0, 20.0] }
 	 * 
 	 * 
- * + * * @author Christoph Strobl * @since 1.7 */ @@ -162,6 +167,7 @@ public class GeoJsonModule extends SimpleModule { * (non-Javadoc) * @see org.springframework.data.mongodb.core.geo.GeoJsonModule.GeoJsonDeserializer#doDeserialize(com.fasterxml.jackson.databind.node.ArrayNode) */ + @Nullable @Override protected GeoJsonPoint doDeserialize(ArrayNode coordinates) { return toGeoJsonPoint(coordinates); @@ -170,18 +176,18 @@ public class GeoJsonModule extends SimpleModule { /** * {@link JsonDeserializer} converting GeoJSON representation of {@literal LineString}. - * + * *
 	 * 
-	 * { 
-	 *   "type": "LineString", 
-	 *   "coordinates": [ 
+	 * {
+	 *   "type": "LineString",
+	 *   "coordinates": [
 	 *     [10.0, 20.0], [30.0, 40.0], [50.0, 60.0]
 	 *   ]
 	 * }
 	 * 
 	 * 
- * + * * @author Christoph Strobl * @since 1.7 */ @@ -199,18 +205,18 @@ public class GeoJsonModule extends SimpleModule { /** * {@link JsonDeserializer} converting GeoJSON representation of {@literal MultiPoint}. - * + * *
 	 * 
-	 * { 
-	 *   "type": "MultiPoint", 
-	 *   "coordinates": [ 
+	 * {
+	 *   "type": "MultiPoint",
+	 *   "coordinates": [
 	 *     [10.0, 20.0], [30.0, 40.0], [50.0, 60.0]
 	 *   ]
 	 * }
 	 * 
 	 * 
- * + * * @author Christoph Strobl * @since 1.7 */ @@ -228,19 +234,19 @@ public class GeoJsonModule extends SimpleModule { /** * {@link JsonDeserializer} converting GeoJSON representation of {@literal MultiLineString}. - * + * *
 	 * 
-	 * { 
-	 *   "type": "MultiLineString", 
+	 * {
+	 *   "type": "MultiLineString",
 	 *   "coordinates": [
-	 *     [ [10.0, 20.0], [30.0, 40.0] ], 
+	 *     [ [10.0, 20.0], [30.0, 40.0] ],
 	 *     [ [50.0, 60.0] , [70.0, 80.0] ]
 	 *   ]
 	 * }
 	 * 
 	 * 
- * + * * @author Christoph Strobl * @since 1.7 */ @@ -267,18 +273,18 @@ public class GeoJsonModule extends SimpleModule { /** * {@link JsonDeserializer} converting GeoJSON representation of {@literal Polygon}. - * + * *
 	 * 
-	 * { 
-	 *   "type": "Polygon", 
-	 *   "coordinates": [ 
-	 *     [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] 
+	 * {
+	 *   "type": "Polygon",
+	 *   "coordinates": [
+	 *     [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ]
 	 *   ]
 	 * }
 	 * 
 	 * 
- * + * * @author Christoph Strobl * @since 1.7 */ @@ -288,6 +294,7 @@ public class GeoJsonModule extends SimpleModule { * (non-Javadoc) * @see org.springframework.data.mongodb.core.geo.GeoJsonModule.GeoJsonDeserializer#doDeserialize(com.fasterxml.jackson.databind.node.ArrayNode) */ + @Nullable @Override protected GeoJsonPolygon doDeserialize(ArrayNode coordinates) { @@ -303,11 +310,11 @@ public class GeoJsonModule extends SimpleModule { /** * {@link JsonDeserializer} converting GeoJSON representation of {@literal MultiPolygon}. - * + * *
 	 * 
-	 * { 
-	 *   "type": "MultiPolygon", 
+	 * {
+	 *   "type": "MultiPolygon",
 	 *   "coordinates": [
 	 *     [[[102.0, 2.0], [103.0, 2.0], [103.0, 3.0], [102.0, 3.0], [102.0, 2.0]]],
 	 *     [[[100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]],
@@ -316,7 +323,7 @@ public class GeoJsonModule extends SimpleModule {
 	 * }
 	 * 
 	 * 
- * + * * @author Christoph Strobl * @since 1.7 */ @@ -332,7 +339,7 @@ public class GeoJsonModule extends SimpleModule { List polygones = new ArrayList(coordinates.size()); for (JsonNode polygon : coordinates) { - for (JsonNode ring : (ArrayNode) polygon) { + for (JsonNode ring : polygon) { polygones.add(new GeoJsonPolygon(toPoints((ArrayNode) ring))); } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonPolygon.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonPolygon.java index 879464b85..c16d0729d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonPolygon.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/GeoJsonPolygon.java @@ -30,6 +30,7 @@ import org.springframework.util.Assert; * closed border. Which means that the first and last {@link Point} have to have same coordinate pairs. * * @author Christoph Strobl + * @author Mark Paluch * @since 1.7 * @see http://geojson.org/geojson-spec.html#polygon */ @@ -47,9 +48,9 @@ public class GeoJsonPolygon extends Polygon implements GeoJson asList(Point first, Point second, Point third, Point fourth, final Point... others) { + private static List asList(Point first, Point second, Point third, Point fourth, Point... others) { ArrayList result = new ArrayList(3 + others.length); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/package-info.java index 1585cec14..6cc77f832 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/geo/package-info.java @@ -1,18 +1,3 @@ -/* - * Copyright 2011-2014 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 - * - * http://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. - */ /** * Support for MongoDB geo-spatial queries. */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java index db4ef3e71..38f73e8b1 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/GeospatialIndex.java @@ -25,11 +25,12 @@ import org.springframework.util.StringUtils; /** * Value object to capture data to create a geo index. - * + * * @author Jon Brisbin * @author Oliver Gierke * @author Laurent Canet * @author Christoph Strobl + * @author Mark Paluch */ public class GeospatialIndex implements IndexDefinition { @@ -46,7 +47,7 @@ public class GeospatialIndex implements IndexDefinition { /** * Creates a new {@link GeospatialIndex} for the given field. - * + * * @param field must not be empty or {@literal null}. */ public GeospatialIndex(String field) { @@ -132,7 +133,7 @@ public class GeospatialIndex implements IndexDefinition { * "https://docs.mongodb.com/manual/core/index-partial/">https://docs.mongodb.com/manual/core/index-partial/ * @since 1.10 */ - public GeospatialIndex partial(IndexFilter filter) { + public GeospatialIndex partial(@Nullable IndexFilter filter) { this.filter = Optional.ofNullable(filter); return this; @@ -148,7 +149,7 @@ public class GeospatialIndex implements IndexDefinition { * @return * @since 2.0 */ - public GeospatialIndex collation(Collation collation) { + public GeospatialIndex collation(@Nullable Collation collation) { this.collation = Optional.ofNullable(collation); return this; @@ -183,12 +184,9 @@ public class GeospatialIndex implements IndexDefinition { return document; } + @Nullable public Document getIndexOptions() { - if (!StringUtils.hasText(name) && min == null && max == null && bucketSize == null) { - return null; - } - Document document = new Document(); if (StringUtils.hasText(name)) { document.put("name", name); @@ -215,9 +213,7 @@ public class GeospatialIndex implements IndexDefinition { case GEO_HAYSTACK: - if (bucketSize != null) { - document.put("bucketSize", bucketSize); - } + document.put("bucketSize", bucketSize); break; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java index 67ee6262d..ce6f152e2 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/Index.java @@ -137,7 +137,7 @@ public class Index implements IndexDefinition { * "https://docs.mongodb.com/manual/core/index-partial/">https://docs.mongodb.com/manual/core/index-partial/ * @since 1.10 */ - public Index partial(IndexFilter filter) { + public Index partial(@Nullable IndexFilter filter) { this.filter = Optional.ofNullable(filter); return this; @@ -153,7 +153,7 @@ public class Index implements IndexDefinition { * @return * @since 2.0 */ - public Index collation(Collation collation) { + public Index collation(@Nullable Collation collation) { this.collation = Optional.ofNullable(collation); return this; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexDefinition.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexDefinition.java index da0acf8ad..8de9d96a7 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexDefinition.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexDefinition.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 by the original author(s). + * Copyright 2011-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.mongodb.core.index; import org.bson.Document; @@ -21,6 +20,7 @@ import org.bson.Document; /** * @author Jon Brisbin * @author Christoph Strobl + * @author Mark Paluch */ public interface IndexDefinition { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexField.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexField.java index dd74cf365..030336beb 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexField.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/IndexField.java @@ -16,12 +16,13 @@ package org.springframework.data.mongodb.core.index; import org.springframework.data.domain.Sort.Direction; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; /** * Value object for an index field. - * + * * @author Oliver Gierke * @author Christoph Strobl */ @@ -33,20 +34,20 @@ public final class IndexField { } private final String key; - private final Direction direction; + private final @Nullable Direction direction; private final Type type; private final Float weight; - private IndexField(String key, Direction direction, Type type) { + private IndexField(String key, @Nullable Direction direction, @Nullable Type type) { this(key, direction, type, Float.NaN); } - private IndexField(String key, Direction direction, Type type, Float weight) { + private IndexField(String key, @Nullable Direction direction, @Nullable Type type, @Nullable Float weight) { Assert.hasText(key, "Key must not be null or empty"); if (Type.GEO.equals(type) || Type.TEXT.equals(type)) { - Assert.isTrue(direction == null, "Geo/Text indexes must not have a direction!"); + Assert.isNull(direction, "Geo/Text indexes must not have a direction!"); } else { Assert.notNull(direction, "Default indexes require a direction"); } @@ -58,7 +59,7 @@ public final class IndexField { } public static IndexField create(String key, Direction order) { - + Assert.notNull(order, "Direction must not be null!"); return new IndexField(key, order, Type.DEFAULT); @@ -66,7 +67,7 @@ public final class IndexField { /** * Creates a geo {@link IndexField} for the given key. - * + * * @param key must not be {@literal null} or empty. * @return */ @@ -76,7 +77,7 @@ public final class IndexField { /** * Creates a text {@link IndexField} for the given key. - * + * * @since 1.6 */ public static IndexField text(String key, Float weight) { @@ -92,16 +93,17 @@ public final class IndexField { /** * Returns the direction of the {@link IndexField} or {@literal null} in case we have a geo index field. - * + * * @return the direction */ + @Nullable public Direction getDirection() { return direction; } /** * Returns whether the {@link IndexField} is a geo index field. - * + * * @return true if type is {@link Type#GEO}. */ public boolean isGeo() { @@ -110,7 +112,7 @@ public final class IndexField { /** * Returns whether the {@link IndexField} is a text index field. - * + * * @return true if type is {@link Type#TEXT} * @since 1.6 */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java index 1056d19cf..cfa290384 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreator.java @@ -33,6 +33,7 @@ import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.MongoMappingContext; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; import org.springframework.data.mongodb.util.MongoDbErrorCodes; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; @@ -175,7 +176,8 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener entity) { + protected IndexDefinitionHolder createCompoundIndexDefinition(String dotPath, String collection, CompoundIndex index, + MongoPersistentEntity entity) { CompoundIndexDefinition indexDefinition = new CompoundIndexDefinition( resolveCompoundIndexKeyFromStringDefinition(dotPath, index.def())); @@ -444,7 +450,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver { return new IndexDefinitionHolder(dotPath, indexDefinition, collection); } - private String pathAwareIndexName(String indexName, String dotPath, MongoPersistentProperty property) { + private String pathAwareIndexName(String indexName, String dotPath, @Nullable MongoPersistentProperty property) { String nameToUse = StringUtils.hasText(indexName) ? indexName : ""; @@ -611,10 +617,10 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver { private static final long serialVersionUID = -3762979307658772277L; private final String propertyName; - private final Class type; + private final @Nullable Class type; private final String dotPath; - public CyclicPropertyReferenceException(String propertyName, Class type, String dotPath) { + public CyclicPropertyReferenceException(String propertyName, @Nullable Class type, String dotPath) { this.propertyName = propertyName; this.type = type; @@ -710,9 +716,9 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver { private final IncludeStrategy strategy; - private final TextIndexedFieldSpec parentFieldSpec; + private final @Nullable TextIndexedFieldSpec parentFieldSpec; - public TextIndexIncludeOptions(IncludeStrategy strategy, TextIndexedFieldSpec parentFieldSpec) { + public TextIndexIncludeOptions(IncludeStrategy strategy, @Nullable TextIndexedFieldSpec parentFieldSpec) { this.strategy = strategy; this.parentFieldSpec = parentFieldSpec; } @@ -725,6 +731,7 @@ public class MongoPersistentEntityIndexResolver implements IndexResolver { return strategy; } + @Nullable public TextIndexedFieldSpec getParentFieldSpec() { return parentFieldSpec; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/TextIndexDefinition.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/TextIndexDefinition.java index b707e3b52..59ec19a48 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/TextIndexDefinition.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/index/TextIndexDefinition.java @@ -28,8 +28,9 @@ import org.springframework.util.StringUtils; /** * {@link IndexDefinition} to span multiple keys for text search. - * + * * @author Christoph Strobl + * @author Mark Paluch * @since 1.6 */ public class TextIndexDefinition implements IndexDefinition { @@ -46,7 +47,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Creates a {@link TextIndexDefinition} for all fields in the document. - * + * * @return */ public static TextIndexDefinition forAllFields() { @@ -55,7 +56,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Get {@link TextIndexDefinitionBuilder} to create {@link TextIndexDefinition}. - * + * * @return */ public static TextIndexDefinitionBuilder builder() { @@ -78,7 +79,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Returns if the {@link TextIndexDefinition} has fields assigned. - * + * * @return */ public boolean hasFieldSpec() { @@ -143,11 +144,11 @@ public class TextIndexDefinition implements IndexDefinition { public static class TextIndexedFieldSpec { private final String fieldname; - private final @Nullable Float weight; + private final Float weight; /** * Create new {@link TextIndexedFieldSpec} for given fieldname without any weight. - * + * * @param fieldname */ public TextIndexedFieldSpec(String fieldname) { @@ -156,7 +157,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Create new {@link TextIndexedFieldSpec} for given fieldname and weight. - * + * * @param fieldname * @param weight */ @@ -169,7 +170,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Get the fieldname associated with the {@link TextIndexedFieldSpec}. - * + * * @return */ public String getFieldname() { @@ -178,10 +179,9 @@ public class TextIndexDefinition implements IndexDefinition { /** * Get the weight associated with the {@link TextIndexedFieldSpec}. - * + * * @return */ - @Nullable public Float getWeight() { return weight; } @@ -190,7 +190,7 @@ public class TextIndexDefinition implements IndexDefinition { * @return true if {@link #weight} has a value that is a valid number. */ public boolean isWeighted() { - return this.weight != null && this.weight.compareTo(1.0F) != 0; + return this.weight.compareTo(1.0F) != 0; } @Override @@ -220,7 +220,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * {@link TextIndexDefinitionBuilder} helps defining options for creating {@link TextIndexDefinition}. - * + * * @author Christoph Strobl * @since 1.6 */ @@ -235,7 +235,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Define the name to be used when creating the index in the store. - * + * * @param name * @return */ @@ -245,9 +245,9 @@ public class TextIndexDefinition implements IndexDefinition { } /** - * Define the index to span all fields using wilcard.
+ * Define the index to span all fields using wildcard.
* NOTE {@link TextIndexDefinition} cannot contain any other fields when defined with wildcard. - * + * * @return */ public TextIndexDefinitionBuilder onAllFields() { @@ -262,7 +262,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Include given fields with default weight. - * + * * @param fieldnames * @return */ @@ -276,7 +276,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Include given field with default weight. - * + * * @param fieldname * @return */ @@ -286,7 +286,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Include given field with weight. - * + * * @param fieldname * @return */ @@ -303,7 +303,7 @@ public class TextIndexDefinition implements IndexDefinition { /** * Define the default language to be used when indexing documents. - * + * * @param language * @return * @see https://docs.mongodb.com/manual/core/index-partial/ * @since 1.10 */ - public TextIndexDefinitionBuilder partial(IndexFilter filter) { + public TextIndexDefinitionBuilder partial(@Nullable IndexFilter filter) { this.instance.filter = filter; return this; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/BasicMongoPersistentEntity.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/BasicMongoPersistentEntity.java index 9d584f8d1..dd9bea9e4 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/BasicMongoPersistentEntity.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/BasicMongoPersistentEntity.java @@ -64,7 +64,7 @@ public class BasicMongoPersistentEntity extends BasicPersistentEntity extends BasicPersistentEntity extends BasicPersistentEntity extends BasicPersistentEntity owner, - SimpleTypeHolder simpleTypeHolder, FieldNamingStrategy fieldNamingStrategy) { + SimpleTypeHolder simpleTypeHolder, @Nullable FieldNamingStrategy fieldNamingStrategy) { super(property, owner, simpleTypeHolder); this.fieldNamingStrategy = fieldNamingStrategy == null ? PropertyNameFieldNamingStrategy.INSTANCE @@ -152,6 +153,7 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope return StringUtils.hasText(getAnnotatedFieldName()); } + @Nullable private String getAnnotatedFieldName() { org.springframework.data.mongodb.core.mapping.Field annotation = findAnnotation( @@ -193,6 +195,7 @@ public class BasicMongoPersistentProperty extends AnnotationBasedPersistentPrope * (non-Javadoc) * @see org.springframework.data.mongodb.core.mapping.MongoPersistentProperty#getDBRef() */ + @Nullable public DBRef getDBRef() { return findAnnotation(DBRef.class); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java index 8a253c192..73abd4147 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/MongoMappingContext.java @@ -32,7 +32,7 @@ import org.springframework.lang.Nullable; /** * Default implementation of a {@link MappingContext} for MongoDB using {@link BasicMongoPersistentEntity} and * {@link BasicMongoPersistentProperty} as primary abstractions. - * + * * @author Jon Brisbin * @author Oliver Gierke */ @@ -54,11 +54,11 @@ public class MongoMappingContext extends AbstractMappingContext extends PersistentEntity extends PersistentEntity * It's marked with {@link TextScore}. - * + * * @return * @since 1.6 */ @@ -88,15 +89,16 @@ public interface MongoPersistentProperty extends PersistentProperty { @@ -115,7 +117,7 @@ public interface MongoPersistentProperty extends PersistentProperty extends MongoMappingEvent { private static final long serialVersionUID = 1L; - private final Class type; + private final @Nullable Class type; /** * Creates a new {@link AbstractDeleteEvent} for the given {@link Document} and type. - * + * * @param document must not be {@literal null}. - * @param type can be {@literal null}. - * @param collectionName can be {@literal null}. + * @param type may be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ - public AbstractDeleteEvent(Document document, Class type, String collectionName) { + public AbstractDeleteEvent(Document document, @Nullable Class type, String collectionName) { super(document, document, collectionName); this.type = type; @@ -44,9 +46,10 @@ public abstract class AbstractDeleteEvent extends MongoMappingEvent /** * Returns the type for which the {@link AbstractDeleteEvent} shall be invoked for. - * + * * @return */ + @Nullable public Class getType() { return type; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterConvertEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterConvertEvent.java index a5f662b5f..7ce42e041 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterConvertEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterConvertEvent.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 by the original author(s). + * Copyright 2011-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -19,9 +19,10 @@ import org.bson.Document; /** * {@link MongoMappingEvent} thrown after convert of a document. - * - * @author Jon Brisbin + * + * @author Jon Brisbin * @author Christoph Strobl + * @author Mark Paluch */ public class AfterConvertEvent extends MongoMappingEvent { @@ -29,10 +30,10 @@ public class AfterConvertEvent extends MongoMappingEvent { /** * Creates new {@link AfterConvertEvent}. - * - * @param document can be {@literal null}. + * + * @param document must not be {@literal null}. * @param source must not be {@literal null}. - * @param collectionName can be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ public AfterConvertEvent(Document document, E source, String collectionName) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterDeleteEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterDeleteEvent.java index 522208aa2..7882fb789 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterDeleteEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterDeleteEvent.java @@ -16,13 +16,15 @@ package org.springframework.data.mongodb.core.mapping.event; import org.bson.Document; +import org.springframework.lang.Nullable; /** * Event being thrown after a single or a set of documents has/have been deleted. The {@link Document} held in the event * will be the query document after it has been mapped onto the domain type handled. - * + * * @author Martin Baumgartner * @author Christoph Strobl + * @author Mark Paluch */ public class AfterDeleteEvent extends AbstractDeleteEvent { @@ -30,13 +32,13 @@ public class AfterDeleteEvent extends AbstractDeleteEvent { /** * Creates a new {@link AfterDeleteEvent} for the given {@link Document}, type and collectionName. - * + * * @param dbo must not be {@literal null}. - * @param type can be {@literal null}. - * @param collectionName can be {@literal null}. + * @param type may be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ - public AfterDeleteEvent(Document document, Class type, String collectionName) { + public AfterDeleteEvent(Document document, @Nullable Class type, String collectionName) { super(document, type, collectionName); } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterLoadEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterLoadEvent.java index 590eac90d..7908d189b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterLoadEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterLoadEvent.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 by the original author(s). + * Copyright 2011-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.mongodb.core.mapping.event; import org.bson.Document; @@ -21,11 +20,12 @@ import org.springframework.util.Assert; /** * Event to be triggered after loading {@link Document}s to be mapped onto a given type. - * + * * @author Oliver Gierke * @author Jon Brisbin * @author Christoph Leiter * @author Christoph Strobl + * @author Mark Paluch */ public class AfterLoadEvent extends MongoMappingEvent { @@ -34,10 +34,10 @@ public class AfterLoadEvent extends MongoMappingEvent { /** * Creates a new {@link AfterLoadEvent} for the given {@link Document}, type and collectionName. - * + * * @param document must not be {@literal null}. * @param type must not be {@literal null}. - * @param collectionName can be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ public AfterLoadEvent(Document document, Class type, String collectionName) { @@ -50,7 +50,7 @@ public class AfterLoadEvent extends MongoMappingEvent { /** * Returns the type for which the {@link AfterLoadEvent} shall be invoked for. - * + * * @return */ public Class getType() { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterSaveEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterSaveEvent.java index e8e490159..3b70f63ec 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterSaveEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/AfterSaveEvent.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 by the original author(s). + * Copyright 2011-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.mongodb.core.mapping.event; import org.bson.Document; /** * {@link MongoMappingEvent} triggered after save of a document. - * - * @author Jon Brisbin + * + * @author Jon Brisbin * @author Christoph Strobl + * @author Mark Paluch */ public class AfterSaveEvent extends MongoMappingEvent { @@ -30,10 +30,10 @@ public class AfterSaveEvent extends MongoMappingEvent { /** * Creates new {@link AfterSaveEvent}. - * + * * @param source must not be {@literal null}. - * @param document can be {@literal null}. - * @param collectionName can be {@literal null}. + * @param document must not be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ public AfterSaveEvent(E source, Document document, String collectionName) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeConvertEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeConvertEvent.java index acb9912f0..1daf6f306 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeConvertEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeConvertEvent.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2015 the original author or authors. + * Copyright 2011-2017 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. @@ -17,10 +17,11 @@ package org.springframework.data.mongodb.core.mapping.event; /** * Event being thrown before a domain object is converted to be persisted. - * + * * @author Jon Brisbin * @author Oliver Gierke * @author Christoph Strobl + * @author Mark Paluch */ public class BeforeConvertEvent extends MongoMappingEvent { @@ -28,9 +29,9 @@ public class BeforeConvertEvent extends MongoMappingEvent { /** * Creates new {@link BeforeConvertEvent}. - * + * * @param source must not be {@literal null}. - * @param collectionName can be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ public BeforeConvertEvent(T source, String collectionName) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeDeleteEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeDeleteEvent.java index 12cec1812..5b6f14da7 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeDeleteEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeDeleteEvent.java @@ -1,11 +1,11 @@ /* - * Copyright 2013-2016 by the original author(s). + * Copyright 2013-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -16,13 +16,15 @@ package org.springframework.data.mongodb.core.mapping.event; import org.bson.Document; +import org.springframework.lang.Nullable; /** * Event being thrown before a document is deleted. The {@link Document} held in the event will represent the query * document before being mapped based on the domain class handled. - * + * * @author Martin Baumgartner * @author Christoph Strobl + * @author Mark Paluch */ public class BeforeDeleteEvent extends AbstractDeleteEvent { @@ -30,13 +32,13 @@ public class BeforeDeleteEvent extends AbstractDeleteEvent { /** * Creates a new {@link BeforeDeleteEvent} for the given {@link Document}, type and collectionName. - * + * * @param document must not be {@literal null}. - * @param type can be {@literal null}. - * @param collectionName can be {@literal null}. + * @param type may be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ - public BeforeDeleteEvent(Document document, Class type, String collectionName) { + public BeforeDeleteEvent(Document document, @Nullable Class type, String collectionName) { super(document, type, collectionName); } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeSaveEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeSaveEvent.java index a25155acd..c2d6add66 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeSaveEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/BeforeSaveEvent.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 by the original author(s). + * Copyright 2011-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.mongodb.core.mapping.event; import org.bson.Document; /** * {@link MongoMappingEvent} triggered before save of a document. - * - * @author Jon Brisbin + * + * @author Jon Brisbin * @author Christoph Strobl + * @author Mark Paluch */ public class BeforeSaveEvent extends MongoMappingEvent { @@ -30,10 +30,10 @@ public class BeforeSaveEvent extends MongoMappingEvent { /** * Creates new {@link BeforeSaveEvent}. - * + * * @param source must not be {@literal null}. - * @param document can be {@literal null}. - * @param collectionName can be {@literal null}. + * @param document must not be {@literal null}. + * @param collectionName must not be {@literal null}. * @since 1.8 */ public BeforeSaveEvent(E source, Document document, String collectionName) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/MongoMappingEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/MongoMappingEvent.java index 37af9b562..40f1b8b72 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/MongoMappingEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapping/event/MongoMappingEvent.java @@ -1,11 +1,11 @@ /* - * Copyright (c) 2011-2016 by the original author(s). + * Copyright 2011-2017 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 * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://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, @@ -13,32 +13,33 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.springframework.data.mongodb.core.mapping.event; import org.bson.Document; import org.springframework.context.ApplicationEvent; +import org.springframework.lang.Nullable; /** * Base {@link ApplicationEvent} triggered by Spring Data MongoDB. - * - * @author Jon Brisbin + * + * @author Jon Brisbin * @author Christoph Strobl + * @author Mark Paluch */ public class MongoMappingEvent extends ApplicationEvent { private static final long serialVersionUID = 1L; - private final Document document; - private final String collectionName; + private final @Nullable Document document; + private final @Nullable String collectionName; /** * Creates new {@link MongoMappingEvent}. - * + * * @param source must not be {@literal null}. * @param document can be {@literal null}. * @param collectionName can be {@literal null}. */ - public MongoMappingEvent(T source, Document document, String collectionName) { + public MongoMappingEvent(T source, @Nullable Document document, @Nullable String collectionName) { super(source); this.document = document; @@ -48,17 +49,17 @@ public class MongoMappingEvent extends ApplicationEvent { /** * @return {@literal null} if not set. */ - public Document getDocument() { + public @Nullable Document getDocument() { return document; } /** * Get the collection the event refers to. - * + * * @return {@literal null} if not set. * @since 1.8 */ - public String getCollectionName() { + public @Nullable String getCollectionName() { return collectionName; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupBy.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupBy.java index 22bff10be..e23b027b9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupBy.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/GroupBy.java @@ -28,6 +28,7 @@ import org.springframework.lang.Nullable; * * @author Mark Pollack * @author Christoph Strobl + * @author Mark Paluch */ public class GroupBy { @@ -52,7 +53,7 @@ public class GroupBy { // NOTE GroupByCommand does not handle keyfunction. - public GroupBy(String key, boolean isKeyFunction) { + public GroupBy(@Nullable String key, boolean isKeyFunction) { Document document = new Document(); if (isKeyFunction) { @@ -89,7 +90,7 @@ public class GroupBy { * @param initialDocument can be {@literal null}. * @return */ - public GroupBy initialDocument(String initialDocument) { + public GroupBy initialDocument(@Nullable String initialDocument) { initial = Optional.ofNullable(initialDocument); return this; @@ -101,7 +102,7 @@ public class GroupBy { * @param initialDocument can be {@literal null}. * @return */ - public GroupBy initialDocument(Document initialDocument) { + public GroupBy initialDocument(@Nullable Document initialDocument) { this.initialDocument = initialDocument; return this; @@ -125,7 +126,7 @@ public class GroupBy { * @param finalizeFunction * @return */ - public GroupBy finalizeFunction(String finalizeFunction) { + public GroupBy finalizeFunction(@Nullable String finalizeFunction) { finalize = Optional.ofNullable(finalizeFunction); return this; @@ -138,7 +139,7 @@ public class GroupBy { * @return * @since 2.0 */ - public GroupBy collation(Collation collation) { + public GroupBy collation(@Nullable Collation collation) { this.collation = Optional.ofNullable(collation); return this; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java index 7a6bfd633..13abcbf36 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceOptions.java @@ -21,14 +21,15 @@ import java.util.Optional; import org.bson.Document; import org.springframework.data.mongodb.core.query.Collation; +import org.springframework.lang.Nullable; import com.mongodb.MapReduceCommand; -import org.springframework.lang.Nullable; /** * @author Mark Pollack * @author Oliver Gierke * @author Christoph Strobl + * @author Mark Paluch */ public class MapReduceOptions { @@ -48,7 +49,7 @@ public class MapReduceOptions { /** * Static factory method to create a MapReduceOptions instance - * + * * @return a new instance */ public static MapReduceOptions options() { @@ -58,7 +59,7 @@ public class MapReduceOptions { /** * Limit the number of objects to return from the collection that is fed into the map reduce operation Often used in * conjunction with a query and sort option so as to reduce the portion of the data that will be processed. - * + * * @param limit Limit the number of objects to process * @return MapReduceOptions so that methods can be chained in a fluent API style */ @@ -71,7 +72,7 @@ public class MapReduceOptions { /** * The collection where the results from the map-reduce operation will be stored. Note, you can set the database name * as well with the outputDatabase option. - * + * * @param collectionName The name of the collection where the results of the map-reduce operation will be stored. * @return MapReduceOptions so that methods can be chained in a fluent API style */ @@ -84,11 +85,11 @@ public class MapReduceOptions { /** * The database where the results from the map-reduce operation will be stored. Note, you ca set the collection name * as well with the outputCollection option. - * + * * @param outputDatabase The name of the database where the results of the map-reduce operation will be stored. * @return MapReduceOptions so that methods can be chained in a fluent API style */ - public MapReduceOptions outputDatabase(String outputDatabase) { + public MapReduceOptions outputDatabase(@Nullable String outputDatabase) { this.outputDatabase = Optional.ofNullable(outputDatabase); return this; @@ -98,7 +99,7 @@ public class MapReduceOptions { * With this option, no collection will be created, and the whole map-reduce operation will happen in RAM. Also, the * results of the map-reduce will be returned within the result object. Note that this option is possible only when * the result set fits within the 16MB limit of a single document. - * + * * @return MapReduceOptions so that methods can be chained in a fluent API style */ public MapReduceOptions outputTypeInline() { @@ -110,7 +111,7 @@ public class MapReduceOptions { /** * This option will merge new data into the old output collection. In other words, if the same key exists in both the * result set and the old collection, the new key will overwrite the old one. - * + * * @return MapReduceOptions so that methods can be chained in a fluent API style */ public MapReduceOptions outputTypeMerge() { @@ -123,7 +124,7 @@ public class MapReduceOptions { * If documents exists for a given key in the result set and in the old collection, then a reduce operation (using the * specified reduce function) will be performed on the two values and the result will be written to the output * collection. If a finalize function was provided, this will be run after the reduce as well. - * + * * @return */ public MapReduceOptions outputTypeReduce() { @@ -134,7 +135,7 @@ public class MapReduceOptions { /** * The output will be inserted into a collection which will atomically replace any existing collection with the same * name. Note, the default is MapReduceCommand.OutputType.REPLACE - * + * * @return MapReduceOptions so that methods can be chained in a fluent API style */ public MapReduceOptions outputTypeReplace() { @@ -146,7 +147,7 @@ public class MapReduceOptions { /** * If true and combined with an output mode that writes to a collection, the output collection will be sharded using * the _id field. For MongoDB 1.9+ - * + * * @param outputShared if true, output will be sharded based on _id key. * @return MapReduceOptions so that methods can be chained in a fluent API style */ @@ -158,11 +159,11 @@ public class MapReduceOptions { /** * Sets the finalize function - * + * * @param finalizeFunction The finalize function. Can be a JSON string or a Spring Resource URL * @return MapReduceOptions so that methods can be chained in a fluent API style */ - public MapReduceOptions finalizeFunction(String finalizeFunction) { + public MapReduceOptions finalizeFunction(@Nullable String finalizeFunction) { this.finalizeFunction = Optional.ofNullable(finalizeFunction); return this; @@ -171,7 +172,7 @@ public class MapReduceOptions { /** * Key-value pairs that are placed into JavaScript global scope and can be accessed from map, reduce, and finalize * scripts. - * + * * @param scopeVariables variables that can be accessed from map, reduce, and finalize scripts * @return MapReduceOptions so that methods can be chained in a fluent API style */ @@ -184,7 +185,7 @@ public class MapReduceOptions { /** * Flag that toggles behavior in the map-reduce operation so as to avoid intermediate conversion to BSON between the * map and reduce steps. For MongoDB 1.9+ - * + * * @param javaScriptMode if true, have the execution of map-reduce stay in JavaScript * @return MapReduceOptions so that methods can be chained in a fluent API style */ @@ -196,7 +197,7 @@ public class MapReduceOptions { /** * Flag to set that will provide statistics on job execution time. - * + * * @return MapReduceOptions so that methods can be chained in a fluent API style */ public MapReduceOptions verbose(boolean verbose) { @@ -209,7 +210,7 @@ public class MapReduceOptions { * Add additional extra options that may not have a method on this class. This method will help if you use a version * of this client library with a server version that has added additional map-reduce options that do not yet have an * method for use in setting them. options - * + * * @param key The key option * @param value The value of the option * @return MapReduceOptions so that methods can be chained in a fluent API style @@ -229,7 +230,7 @@ public class MapReduceOptions { * @return * @since 2.0 */ - public MapReduceOptions collation(Collation collation) { + public MapReduceOptions collation(@Nullable Collation collation) { this.collation = Optional.ofNullable(collation); return this; @@ -248,6 +249,7 @@ public class MapReduceOptions { return this.finalizeFunction; } + @Nullable public Boolean getJavaScriptMode() { return this.jsMode; } @@ -275,7 +277,7 @@ public class MapReduceOptions { /** * Get the maximum number of documents for the input into the map function. - * + * * @return {@literal null} if not set. */ @Nullable diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java index bb7d21bdd..81df949e8 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/mapreduce/MapReduceResults.java @@ -19,13 +19,14 @@ import java.util.Iterator; import java.util.List; import org.bson.Document; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import com.mongodb.MapReduceOutput; /** * Collects the results of performing a MapReduce operations. - * + * * @author Mark Pollack * @author Oliver Gierke * @author Christoph Strobl @@ -35,14 +36,14 @@ import com.mongodb.MapReduceOutput; public class MapReduceResults implements Iterable { private final List mappedResults; - private final Document rawResults; - private final String outputCollection; + private final @Nullable Document rawResults; + private final @Nullable String outputCollection; private final MapReduceTiming mapReduceTiming; private final MapReduceCounts mapReduceCounts; /** * Creates a new {@link MapReduceResults} from the given mapped results and the raw one. - * + * * @param mappedResults must not be {@literal null}. * @param rawResults must not be {@literal null}. * @deprecated since 1.7. Please use {@link #MapReduceResults(List, MapReduceOutput)} @@ -62,7 +63,7 @@ public class MapReduceResults implements Iterable { /** * Creates a new {@link MapReduceResults} from the given mapped results and the {@link MapReduceOutput}. - * + * * @param mappedResults must not be {@literal null}. * @param mapReduceOutput must not be {@literal null}. * @since 1.7 @@ -95,6 +96,7 @@ public class MapReduceResults implements Iterable { return mapReduceCounts; } + @Nullable public String getOutputCollection() { return outputCollection; } @@ -121,7 +123,7 @@ public class MapReduceResults implements Iterable { /** * Returns the value of the source's field with the given key as {@link Long}. - * + * * @param source * @param key * @return @@ -135,7 +137,7 @@ public class MapReduceResults implements Iterable { /** * Parses the raw {@link Document} result into a {@link MapReduceCounts} value object. - * + * * @param rawResults * @return */ @@ -156,10 +158,11 @@ public class MapReduceResults implements Iterable { /** * Parses the output collection from the raw {@link Document} result. - * + * * @param rawResults * @return */ + @Nullable private static String parseOutputCollection(Document rawResults) { Object resultField = rawResults.get("result"); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicQuery.java index 4840dcbf3..fa9a6e702 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicQuery.java @@ -18,6 +18,7 @@ package org.springframework.data.mongodb.core.query; import static org.springframework.util.ObjectUtils.*; import org.bson.Document; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -42,14 +43,14 @@ public class BasicQuery extends Query { * * @param query may be {@literal null}. */ - public BasicQuery(String query) { + public BasicQuery(@Nullable String query) { this(query, null); } /** * Create a new {@link BasicQuery} given a query {@link Document}. * - * @param queryObject may be {@literal null}. + * @param queryObject must not be {@literal null}. */ public BasicQuery(Document queryObject) { this(queryObject, new Document()); @@ -61,7 +62,7 @@ public class BasicQuery extends Query { * @param query may be {@literal null}. * @param fields may be {@literal null}. */ - public BasicQuery(String query, String fields) { + public BasicQuery(@Nullable String query, @Nullable String fields) { this(query != null ? Document.parse(query) : new Document(), fields != null ? Document.parse(fields) : new Document()); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java index eadd87199..d3428b3ed 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/BasicUpdate.java @@ -1,5 +1,5 @@ /* - * Copyright 2010-2016 the original author or authors. + * Copyright 2010-2017 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. @@ -25,10 +25,11 @@ import org.bson.Document; * @author John Brisbin * @author Oliver Gierke * @author Christoph Strobl + * @author Mark Paluch */ public class BasicUpdate extends Update { - private Document updateObject = null; + private Document updateObject; public BasicUpdate(String updateString) { super(); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java index 32cb3d9ac..f8a115477 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Collation.java @@ -15,6 +15,11 @@ */ package org.springframework.data.mongodb.core.query; +import lombok.AccessLevel; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.RequiredArgsConstructor; + import java.util.Locale; import java.util.Optional; @@ -29,11 +34,6 @@ import com.mongodb.client.model.CollationCaseFirst; import com.mongodb.client.model.CollationMaxVariable; import com.mongodb.client.model.CollationStrength; -import lombok.AccessLevel; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.RequiredArgsConstructor; - /** * Central abstraction for MongoDB collation support.
* Allows fluent creation of a collation {@link Document} that can be used for creating collections & indexes as well as @@ -274,7 +274,7 @@ public class Collation { public Collation alternate(Alternate alternate) { Collation newInstance = copy(); - newInstance.alternate = Optional.ofNullable(alternate); + newInstance.alternate = Optional.of(alternate); return newInstance; } @@ -302,10 +302,10 @@ public class Collation { * @param backwards must not be {@literal null}. * @return new {@link Collation}. */ - public Collation backwards(Boolean backwards) { + public Collation backwards(boolean backwards) { Collation newInstance = copy(); - newInstance.backwards = Optional.ofNullable(backwards); + newInstance.backwards = Optional.of(backwards); return newInstance; } @@ -333,10 +333,10 @@ public class Collation { * @param normalization must not be {@literal null}. * @return new {@link Collation}. */ - public Collation normalization(Boolean normalization) { + public Collation normalization(boolean normalization) { Collation newInstance = copy(); - newInstance.normalization = Optional.ofNullable(normalization); + newInstance.normalization = Optional.of(normalization); return newInstance; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Criteria.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Criteria.java index b1a731bbf..4e6d147df 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Criteria.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Criteria.java @@ -63,7 +63,7 @@ public class Criteria implements CriteriaDefinition { private @Nullable String key; private List criteriaChain; private LinkedHashMap criteria = new LinkedHashMap(); - private Object isValue = NOT_SET; + private @Nullable Object isValue = NOT_SET; public Criteria() { this.criteriaChain = new ArrayList(); @@ -130,7 +130,7 @@ public class Criteria implements CriteriaDefinition { * @param o * @return */ - public Criteria is(Object o) { + public Criteria is(@Nullable Object o) { if (!isValue.equals(NOT_SET)) { throw new InvalidMongoDbApiUsageException( @@ -156,7 +156,7 @@ public class Criteria implements CriteriaDefinition { * @return * @see MongoDB Query operator: $ne */ - public Criteria ne(Object o) { + public Criteria ne(@Nullable Object o) { criteria.put("$ne", o); return this; } @@ -352,7 +352,7 @@ public class Criteria implements CriteriaDefinition { * @return * @see MongoDB Query operator: $not */ - private Criteria not(Object value) { + private Criteria not(@Nullable Object value) { criteria.put("$not", value); return this; } @@ -376,7 +376,7 @@ public class Criteria implements CriteriaDefinition { * @return * @see MongoDB Query operator: $regex */ - public Criteria regex(String re, String options) { + public Criteria regex(String re, @Nullable String options) { return regex(toPattern(re, options)); } @@ -408,7 +408,7 @@ public class Criteria implements CriteriaDefinition { return this; } - private Pattern toPattern(String regex, String options) { + private Pattern toPattern(String regex, @Nullable String options) { Assert.notNull(regex, "Regex string must not be null!"); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java index 0543966d3..e27addb56 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Meta.java @@ -1,5 +1,5 @@ /* - * Copyright 2014-2016 the original author or authors. + * Copyright 2014-2017 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. @@ -23,13 +23,14 @@ import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.TimeUnit; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; /** * Meta-data for {@link Query} instances. - * + * * @author Christoph Strobl * @author Oliver Gierke * @author Mark Paluch @@ -53,13 +54,14 @@ public class Meta { /** * @return {@literal null} if not set. */ + @Nullable public Long getMaxTimeMsec() { return getValue(MetaKey.MAX_TIME_MS.key); } /** * Set the maximum time limit in milliseconds for processing operations. - * + * * @param maxTimeMsec */ public void setMaxTimeMsec(long maxTimeMsec) { @@ -68,24 +70,25 @@ public class Meta { /** * Set the maximum time limit for processing operations. - * + * * @param timeout * @param timeUnit */ - public void setMaxTime(long timeout, TimeUnit timeUnit) { + public void setMaxTime(long timeout, @Nullable TimeUnit timeUnit) { setValue(MetaKey.MAX_TIME_MS.key, (timeUnit != null ? timeUnit : TimeUnit.MILLISECONDS).toMillis(timeout)); } /** * @return {@literal null} if not set. */ + @Nullable public Long getMaxScan() { return getValue(MetaKey.MAX_SCAN.key); } /** * Only scan the specified number of documents. - * + * * @param maxScan */ public void setMaxScan(long maxScan) { @@ -94,7 +97,7 @@ public class Meta { /** * Add a comment to the query. - * + * * @param comment */ public void setComment(String comment) { @@ -104,13 +107,14 @@ public class Meta { /** * @return {@literal null} if not set. */ + @Nullable public String getComment() { return getValue(MetaKey.COMMENT.key); } /** * Using snapshot prevents the cursor from returning a document more than once. - * + * * @param useSnapshot */ public void setSnapshot(boolean useSnapshot) { @@ -154,7 +158,7 @@ public class Meta { /** * Get {@link Iterable} of set meta values. - * + * * @return */ public Iterable> values() { @@ -163,11 +167,11 @@ public class Meta { /** * Sets or removes the value in case of {@literal null} or empty {@link String}. - * + * * @param key must not be {@literal null} or empty. * @param value */ - private void setValue(String key, Object value) { + private void setValue(String key, @Nullable Object value) { Assert.hasText(key, "Meta key must not be 'null' or blank."); @@ -177,6 +181,7 @@ public class Meta { this.values.put(key, value); } + @Nullable @SuppressWarnings("unchecked") private T getValue(String key) { return (T) this.values.get(key); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/MongoRegexCreator.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/MongoRegexCreator.java index 2f50fbc29..c287d2f0c 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/MongoRegexCreator.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/MongoRegexCreator.java @@ -17,6 +17,8 @@ package org.springframework.data.mongodb.core.query; import java.util.regex.Pattern; +import org.springframework.lang.Nullable; + /** * @author Christoph Strobl * @author Mark Paluch @@ -77,7 +79,8 @@ public enum MongoRegexCreator { * @param matcherType the type of matching to perform * @return {@literal source} when {@literal source} or {@literal matcherType} is {@literal null}. */ - public String toRegularExpression(String source, MatchMode matcherType) { + @Nullable + public String toRegularExpression(@Nullable String source, @Nullable MatchMode matcherType) { if (matcherType == null || source == null) { return source; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java index f6d6e51f8..300edb605 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/NearQuery.java @@ -30,10 +30,11 @@ import org.springframework.util.ObjectUtils; /** * Builder class to build near-queries. - * + * * @author Oliver Gierke * @author Thomas Darimont * @author Christoph Strobl + * @author Mark Paluch */ public final class NearQuery { @@ -48,7 +49,7 @@ public final class NearQuery { /** * Creates a new {@link NearQuery}. - * + * * @param point must not be {@literal null}. * @param metric must not be {@literal null}. */ @@ -64,7 +65,7 @@ public final class NearQuery { /** * Creates a new {@link NearQuery} starting near the given coordinates. - * + * * @param x * @param y * @return @@ -77,7 +78,7 @@ public final class NearQuery { * Creates a new {@link NearQuery} starting at the given coordinates using the given {@link Metric} to adapt given * values to further configuration. E.g. setting a {@link #maxDistance(double)} will be interpreted as a value of the * initially set {@link Metric}. - * + * * @param x * @param y * @param metric must not be {@literal null}. @@ -89,7 +90,7 @@ public final class NearQuery { /** * Creates a new {@link NearQuery} starting at the given {@link Point}. - * + * * @param point must not be {@literal null}. * @return */ @@ -101,7 +102,7 @@ public final class NearQuery { * Creates a {@link NearQuery} starting near the given {@link Point} using the given {@link Metric} to adapt given * values to further configuration. E.g. setting a {@link #maxDistance(double)} will be interpreted as a value of the * initially set {@link Metric}. - * + * * @param point must not be {@literal null}. * @param metric must not be {@literal null}. * @return @@ -113,7 +114,7 @@ public final class NearQuery { /** * Returns the {@link Metric} underlying the actual query. If no metric was set explicitly {@link Metrics#NEUTRAL} * will be returned. - * + * * @return will never be {@literal null}. */ public Metric getMetric() { @@ -122,7 +123,7 @@ public final class NearQuery { /** * Configures the maximum number of results to return. - * + * * @param num * @return */ @@ -133,7 +134,7 @@ public final class NearQuery { /** * Configures the number of results to skip. - * + * * @param skip * @return */ @@ -144,7 +145,7 @@ public final class NearQuery { /** * Configures the {@link Pageable} to use. - * + * * @param pageable must not be {@literal null} * @return */ @@ -161,13 +162,13 @@ public final class NearQuery { /** * Sets the max distance results shall have from the configured origin. If a {@link Metric} was set before the given * value will be interpreted as being a value in that metric. E.g. - * + * *
 	 * NearQuery query = near(10.0, 20.0, Metrics.KILOMETERS).maxDistance(150);
 	 * 
- * + * * Will set the maximum distance to 150 kilometers. - * + * * @param maxDistance * @return */ @@ -178,7 +179,7 @@ public final class NearQuery { /** * Sets the maximum distance supplied in a given metric. Will normalize the distance but not reconfigure the query's * result {@link Metric} if one was configured before. - * + * * @param maxDistance * @param metric must not be {@literal null}. * @return @@ -193,7 +194,7 @@ public final class NearQuery { /** * Sets the maximum distance to the given {@link Distance}. Will set the returned {@link Metric} to be the one of the * given {@link Distance} if {@link Metric} was {@link Metrics#NEUTRAL} before. - * + * * @param distance must not be {@literal null}. * @return */ @@ -216,13 +217,13 @@ public final class NearQuery { /** * Sets the minimum distance results shall have from the configured origin. If a {@link Metric} was set before the * given value will be interpreted as being a value in that metric. E.g. - * + * *
 	 * NearQuery query = near(10.0, 20.0, Metrics.KILOMETERS).minDistance(150);
 	 * 
- * + * * Will set the minimum distance to 150 kilometers. - * + * * @param minDistance * @return * @since 1.7 @@ -234,7 +235,7 @@ public final class NearQuery { /** * Sets the minimum distance supplied in a given metric. Will normalize the distance but not reconfigure the query's * result {@link Metric} if one was configured before. - * + * * @param minDistance * @param metric must not be {@literal null}. * @return @@ -250,7 +251,7 @@ public final class NearQuery { /** * Sets the minimum distance to the given {@link Distance}. Will set the returned {@link Metric} to be the one of the * given {@link Distance} if no {@link Metric} was set before. - * + * * @param distance must not be {@literal null}. * @return * @since 1.7 @@ -273,7 +274,7 @@ public final class NearQuery { /** * Returns the maximum {@link Distance}. - * + * * @return */ @Nullable @@ -283,7 +284,7 @@ public final class NearQuery { /** * Returns the maximum {@link Distance}. - * + * * @return * @since 1.7 */ @@ -294,7 +295,7 @@ public final class NearQuery { /** * Configures a {@link CustomMetric} with the given multiplier. - * + * * @param distanceMultiplier * @return */ @@ -306,7 +307,7 @@ public final class NearQuery { /** * Configures whether to return spherical values for the actual distance. - * + * * @param spherical * @return */ @@ -317,7 +318,7 @@ public final class NearQuery { /** * Returns whether spharical values will be returned. - * + * * @return */ public boolean isSpherical() { @@ -327,7 +328,7 @@ public final class NearQuery { /** * Will cause the results' distances being returned in kilometers. Sets {@link #distanceMultiplier(double)} and * {@link #spherical(boolean)} accordingly. - * + * * @return */ public NearQuery inKilometers() { @@ -337,7 +338,7 @@ public final class NearQuery { /** * Will cause the results' distances being returned in miles. Sets {@link #distanceMultiplier(double)} and * {@link #spherical(boolean)} accordingly. - * + * * @return */ public NearQuery inMiles() { @@ -347,19 +348,19 @@ public final class NearQuery { /** * Will cause the results' distances being returned in the given metric. Sets {@link #distanceMultiplier(double)} * accordingly as well as {@link #spherical(boolean)} if the given {@link Metric} is not {@link Metrics#NEUTRAL}. - * + * * @param metric the metric the results shall be returned in. Uses {@link Metrics#NEUTRAL} if {@literal null} is * passed. * @return */ - public NearQuery in(Metric metric) { + public NearQuery in(@Nullable Metric metric) { return adaptMetric(metric == null ? Metrics.NEUTRAL : metric); } /** * Configures the given {@link Metric} to be used as base on for this query and recalculate the maximum distance if no * metric was set before. - * + * * @param metric */ private NearQuery adaptMetric(Metric metric) { @@ -374,7 +375,7 @@ public final class NearQuery { /** * Adds an actual query to the {@link NearQuery} to restrict the objects considered for the actual near operation. - * + * * @param query must not be {@literal null}. * @return */ @@ -401,7 +402,7 @@ public final class NearQuery { /** * Returns the {@link Document} built by the {@link NearQuery}. - * + * * @return */ public Document toDocument() { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java index dba1c45c8..ff42c98a9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Query.java @@ -20,7 +20,6 @@ import static org.springframework.util.ObjectUtils.*; import java.util.ArrayList; import java.util.Arrays; -import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; @@ -52,7 +51,7 @@ public class Query { private final Set> restrictedTypes = new HashSet<>(); private final Map criteria = new LinkedHashMap<>(); - private Field fieldSpec = null; + private @Nullable Field fieldSpec = null; private Sort sort = Sort.unsorted(); private long skip; private int limit; @@ -199,7 +198,7 @@ public class Query { * @return the restrictedTypes */ public Set> getRestrictedTypes() { - return restrictedTypes == null ? Collections.emptySet() : restrictedTypes; + return restrictedTypes; } /** @@ -417,7 +416,7 @@ public class Query { * @return * @since 2.0 */ - public Query collation(Collation collation) { + public Query collation(@Nullable Collation collation) { this.collation = Optional.ofNullable(collation); return this; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/SerializationUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/SerializationUtils.java index 507758c6a..5a05ed7b6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/SerializationUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/SerializationUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2012-2016 the original author or authors. + * Copyright 2012-2017 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. @@ -24,14 +24,16 @@ import java.util.Map.Entry; import org.bson.Document; import org.springframework.core.convert.converter.Converter; +import org.springframework.lang.Nullable; import com.mongodb.util.JSON; /** * Utility methods for JSON serialization. - * + * * @author Oliver Gierke * @author Christoph Strobl + * @author Mark Paluch */ public abstract class SerializationUtils { @@ -41,7 +43,7 @@ public abstract class SerializationUtils { /** * Flattens out a given {@link Document}. - * + * *
 	 * 
 	 * {
@@ -49,7 +51,7 @@ public abstract class SerializationUtils {
 	 *   nested : { value : "conflux"}
 	 * }
 	 * 
-	 * will result in 
+	 * will result in
 	 * 
 	 * {
 	 *   _id : 1
@@ -57,12 +59,12 @@ public abstract class SerializationUtils {
 	 * }
 	 * 
 	 * 
- * + * * @param source can be {@literal null}. * @return {@link Collections#emptyMap()} when source is {@literal null} * @since 1.8 */ - public static Map flattenMap(Document source) { + public static Map flattenMap(@Nullable Document source) { if (source == null) { return Collections.emptyMap(); @@ -105,11 +107,12 @@ public abstract class SerializationUtils { * Serializes the given object into pseudo-JSON meaning it's trying to create a JSON representation as far as possible * but falling back to the given object's {@link Object#toString()} method if it's not serializable. Useful for * printing raw {@link Document}s containing complex values before actually converting them into Mongo native types. - * + * * @param value * @return */ - public static String serializeToJsonSafely(Object value) { + @Nullable + public static String serializeToJsonSafely(@Nullable Object value) { if (value == null) { return null; @@ -122,8 +125,6 @@ public abstract class SerializationUtils { return toString((Collection) value); } else if (value instanceof Map) { return toString((Map) value); - } else if (value instanceof Document) { - return toString(((Document) value)); } else { return String.format("{ $java : %s }", value.toString()); } @@ -150,7 +151,7 @@ public abstract class SerializationUtils { * Creates a string representation from the given {@link Iterable} prepending the postfix, applying the given * {@link Converter} to each element before adding it to the result {@link String}, concatenating each element with * {@literal ,} and applying the postfix. - * + * * @param source * @param prefix * @param postfix diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Term.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Term.java index c7a2edffb..2fd0ccd5a 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Term.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Term.java @@ -1,5 +1,5 @@ /* - * Copyright 2014 the original author or authors. + * Copyright 2014-2017 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. @@ -15,11 +15,14 @@ */ package org.springframework.data.mongodb.core.query; +import org.springframework.lang.Nullable; + /** * A {@link Term} defines one or multiple words {@link Type#WORD} or phrases {@link Type#PHRASE} to be used in the * context of full text search. - * + * * @author Christoph Strobl + * @author Mark Paluch * @since 1.6 */ public class Term { @@ -34,7 +37,7 @@ public class Term { /** * Creates a new {@link Term} of {@link Type#WORD}. - * + * * @param raw */ public Term(String raw) { @@ -43,18 +46,18 @@ public class Term { /** * Creates a new {@link Term} of given {@link Type}. - * + * * @param raw * @param type defaulted to {@link Type#WORD} if {@literal null}. */ - public Term(String raw, Type type) { + public Term(String raw, @Nullable Type type) { this.raw = raw; this.type = type == null ? Type.WORD : type; } /** * Negates the term. - * + * * @return */ public Term negate() { @@ -78,7 +81,7 @@ public class Term { /** * Get formatted representation of term. - * + * * @return */ public String getFormatted() { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextCriteria.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextCriteria.java index e14e27966..4c4db1c91 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextCriteria.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextCriteria.java @@ -25,21 +25,22 @@ import org.springframework.util.StringUtils; /** * Implementation of {@link CriteriaDefinition} to be used for full text search. - * + * * @author Christoph Strobl * @author Oliver Gierke + * @author Mark Paluch * @since 1.6 */ public class TextCriteria implements CriteriaDefinition { private final List terms; - private String language; + private @Nullable String language; private @Nullable Boolean caseSensitive; private @Nullable Boolean diacriticSensitive; /** * Creates a new {@link TextCriteria}. - * + * * @see #forDefaultLanguage() * @see #forLanguage(String) */ @@ -47,7 +48,7 @@ public class TextCriteria implements CriteriaDefinition { this(null); } - private TextCriteria(String language) { + private TextCriteria(@Nullable String language) { this.language = language; this.terms = new ArrayList(); @@ -55,7 +56,7 @@ public class TextCriteria implements CriteriaDefinition { /** * Returns a new {@link TextCriteria} for the default language. - * + * * @return */ public static TextCriteria forDefaultLanguage() { @@ -65,7 +66,7 @@ public class TextCriteria implements CriteriaDefinition { /** * For a full list of supported languages see the mongodb reference manual for * Text Search Languages. - * + * * @param language * @return */ @@ -77,7 +78,7 @@ public class TextCriteria implements CriteriaDefinition { /** * Configures the {@link TextCriteria} to match any of the given words. - * + * * @param words the words to match. * @return */ @@ -92,7 +93,7 @@ public class TextCriteria implements CriteriaDefinition { /** * Adds given {@link Term} to criteria. - * + * * @param term must not be {@literal null}. */ public TextCriteria matching(Term term) { @@ -141,7 +142,7 @@ public class TextCriteria implements CriteriaDefinition { /** * Given value will treated as a single phrase. - * + * * @param phrase * @return */ @@ -155,7 +156,7 @@ public class TextCriteria implements CriteriaDefinition { /** * Given value will treated as a single phrase. - * + * * @param phrase * @return */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextQuery.java index ac58dbc54..56841e52f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/TextQuery.java @@ -18,6 +18,7 @@ package org.springframework.data.mongodb.core.query; import java.util.Locale; import org.bson.Document; +import org.springframework.lang.Nullable; /** * {@link Query} implementation to be used to for performing full text searches. @@ -55,7 +56,7 @@ public class TextQuery extends Query { * @see TextCriteria#forLanguage(String) * @see TextCriteria#matching(String) */ - public TextQuery(String wordsAndPhrases, String language) { + public TextQuery(String wordsAndPhrases, @Nullable String language) { super(TextCriteria.forLanguage(language).matching(wordsAndPhrases)); } @@ -67,7 +68,7 @@ public class TextQuery extends Query { * @param wordsAndPhrases * @param locale */ - public TextQuery(String wordsAndPhrases, Locale locale) { + public TextQuery(String wordsAndPhrases, @Nullable Locale locale) { this(wordsAndPhrases, locale != null ? locale.getLanguage() : (String) null); } @@ -158,10 +159,6 @@ public class TextQuery extends Query { Document fields = super.getFieldsObject(); - if (fields == null) { - fields = new Document(); - } - fields.put(getScoreFieldName(), META_TEXT_SCORE); return fields; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java index 37663c454..fdc9075c4 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/query/Update.java @@ -31,6 +31,7 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.domain.Sort.Order; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -848,7 +849,7 @@ public class Update { * @return never {@literal null}. * @since 1.7 */ - public PushOperatorBuilder atPosition(Position position) { + public PushOperatorBuilder atPosition(@Nullable Position position) { if (position == null || Position.LAST.equals(position)) { return this; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionNode.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionNode.java index 9fb3f5b89..fa3496cb1 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionNode.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionNode.java @@ -24,11 +24,12 @@ import org.springframework.expression.spel.ast.Literal; import org.springframework.expression.spel.ast.MethodReference; import org.springframework.expression.spel.ast.Operator; import org.springframework.expression.spel.ast.OperatorNot; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * A value object for nodes in an expression. Allows iterating ove potentially available child {@link ExpressionNode}s. - * + * * @author Oliver Gierke * @author Christoph Strobl * @author Mark Paluch @@ -42,7 +43,7 @@ public class ExpressionNode implements Iterable { /** * Creates a new {@link ExpressionNode} from the given {@link SpelNode} and {@link ExpressionState}. - * + * * @param node must not be {@literal null}. * @param state must not be {@literal null}. */ @@ -58,7 +59,7 @@ public class ExpressionNode implements Iterable { /** * Factory method to create {@link ExpressionNode}'s according to the given {@link SpelNode} and * {@link ExpressionState}. - * + * * @param node * @param state must not be {@literal null}. * @return an {@link ExpressionNode} for the given {@link SpelNode} or {@literal null} if {@literal null} was given @@ -66,10 +67,6 @@ public class ExpressionNode implements Iterable { */ public static ExpressionNode from(SpelNode node, ExpressionState state) { - if (node == null) { - return null; - } - if (node instanceof Operator) { return new OperatorNode((Operator) node, state); } @@ -91,7 +88,7 @@ public class ExpressionNode implements Iterable { /** * Returns the name of the {@link ExpressionNode}. - * + * * @return */ public String getName() { @@ -100,7 +97,7 @@ public class ExpressionNode implements Iterable { /** * Returns whether the current {@link ExpressionNode} is backed by the given type. - * + * * @param type must not be {@literal null}. * @return */ @@ -112,17 +109,17 @@ public class ExpressionNode implements Iterable { /** * Returns whether the given {@link ExpressionNode} is representing the same backing node type as the current one. - * + * * @param node * @return */ - boolean isOfSameTypeAs(ExpressionNode node) { + boolean isOfSameTypeAs(@Nullable ExpressionNode node) { return node == null ? false : this.node.getClass().equals(node.node.getClass()); } /** * Returns whether the {@link ExpressionNode} is a mathematical operation. - * + * * @return */ public boolean isMathematicalOperation() { @@ -141,7 +138,7 @@ public class ExpressionNode implements Iterable { /** * Returns whether the {@link ExpressionNode} is a literal. - * + * * @return */ public boolean isLiteral() { @@ -150,16 +147,17 @@ public class ExpressionNode implements Iterable { /** * Returns the value of the current node. - * + * * @return */ + @Nullable public Object getValue() { return node.getValue(state); } /** * Returns whether the current node has child nodes. - * + * * @return */ public boolean hasChildren() { @@ -168,7 +166,7 @@ public class ExpressionNode implements Iterable { /** * Returns the child {@link ExpressionNode} with the given index. - * + * * @param index must not be negative. * @return */ @@ -180,7 +178,7 @@ public class ExpressionNode implements Iterable { /** * Returns whether the {@link ExpressionNode} has a first child node that is not of the given type. - * + * * @param type must not be {@literal null}. * @return */ @@ -192,7 +190,7 @@ public class ExpressionNode implements Iterable { /** * Creates a new {@link ExpressionNode} from the given {@link SpelNode}. - * + * * @param node * @return */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionTransformationContextSupport.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionTransformationContextSupport.java index 1770d05b5..26258c6b1 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionTransformationContextSupport.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/ExpressionTransformationContextSupport.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 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. @@ -18,31 +18,33 @@ package org.springframework.data.mongodb.core.spel; import java.util.List; import org.bson.Document; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * The context for an {@link ExpressionNode} transformation. - * + * * @author Thomas Darimont * @author Oliver Gierke * @author Christoph Strobl + * @author Mark Paluch */ public class ExpressionTransformationContextSupport { private final T currentNode; - private final ExpressionNode parentNode; - private final Document previousOperationObject; + private final @Nullable ExpressionNode parentNode; + private final @Nullable Document previousOperationObject; /** * Creates a new {@link ExpressionTransformationContextSupport} for the given {@link ExpressionNode}s and an optional * previous operation. - * + * * @param currentNode must not be {@literal null}. - * @param parentNode - * @param previousOperationObject + * @param parentNode may be {@literal null}. + * @param previousOperationObject may be {@literal null}. */ - public ExpressionTransformationContextSupport(T currentNode, ExpressionNode parentNode, - Document previousOperationObject) { + public ExpressionTransformationContextSupport(T currentNode, @Nullable ExpressionNode parentNode, + @Nullable Document previousOperationObject) { Assert.notNull(currentNode, "currentNode must not be null!"); @@ -53,7 +55,7 @@ public class ExpressionTransformationContextSupport { /** * Returns the current {@link ExpressionNode}. - * + * * @return */ public T getCurrentNode() { @@ -62,29 +64,31 @@ public class ExpressionTransformationContextSupport { /** * Returns the parent {@link ExpressionNode} or {@literal null} if none available. - * + * * @return */ + @Nullable public ExpressionNode getParentNode() { return parentNode; } /** - * Returns the previously accumulated operaton object or {@literal null} if none available. Rather than manually + * Returns the previously accumulated operation object or {@literal null} if none available. Rather than manually * adding stuff to the object prefer using {@link #addToPreviousOrReturn(Object)} to transparently do if one is * present. - * + * * @see #hasPreviousOperation() * @see #addToPreviousOrReturn(Object) * @return */ + @Nullable public Document getPreviousOperationObject() { return previousOperationObject; } /** * Returns whether a previous operation is present. - * + * * @return */ public boolean hasPreviousOperation() { @@ -93,27 +97,30 @@ public class ExpressionTransformationContextSupport { /** * Returns whether the parent node is of the same operation as the current node. - * + * * @return */ public boolean parentIsSameOperation() { - return parentNode == null ? false : currentNode.isOfSameTypeAs(parentNode); + return parentNode != null && currentNode.isOfSameTypeAs(parentNode); } /** * Adds the given value to the previous operation and returns it. - * + * * @param value * @return */ public Document addToPreviousOperation(Object value) { + + Assert.state(previousOperationObject != null, "No previous operation available!"); + extractArgumentListFrom(previousOperationObject).add(value); return previousOperationObject; } /** * Adds the given value to the previous operation if one is present or returns the value to add as is. - * + * * @param value * @return */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/LiteralNode.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/LiteralNode.java index 4add40cc7..e22f436ae 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/LiteralNode.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/LiteralNode.java @@ -28,6 +28,7 @@ import org.springframework.expression.spel.ast.LongLiteral; import org.springframework.expression.spel.ast.NullLiteral; import org.springframework.expression.spel.ast.RealLiteral; import org.springframework.expression.spel.ast.StringLiteral; +import org.springframework.lang.Nullable; /** * A node representing a literal in an expression. @@ -72,7 +73,7 @@ public class LiteralNode extends ExpressionNode { * @param parent * @return */ - public boolean isUnaryMinus(ExpressionNode parent) { + public boolean isUnaryMinus(@Nullable ExpressionNode parent) { if (!(parent instanceof OperatorNode)) { return false; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java index fcdd5c15c..e3202b488 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/spel/MethodReferenceNode.java @@ -23,6 +23,7 @@ import java.util.Map; import org.springframework.expression.spel.ExpressionState; import org.springframework.expression.spel.ast.MethodReference; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ObjectUtils; @@ -33,6 +34,7 @@ import org.springframework.util.ObjectUtils; * @author Thomas Darimont * @author Sebastien Gerard * @author Christoph Strobl + * @author Mark Paluch */ public class MethodReferenceNode extends ExpressionNode { @@ -172,6 +174,7 @@ public class MethodReferenceNode extends ExpressionNode { * * @Deprecated since 1.10. Please use {@link #getMethodReference()}. */ + @Nullable @Deprecated public String getMethodName() { @@ -185,6 +188,7 @@ public class MethodReferenceNode extends ExpressionNode { * @return can be {@literal null}. * @since 1.10 */ + @Nullable public AggregationMethodReference getMethodReference() { String name = getName(); @@ -198,9 +202,9 @@ public class MethodReferenceNode extends ExpressionNode { */ public static final class AggregationMethodReference { - private final String mongoOperator; - private final ArgumentType argumentType; - private final String[] argumentMap; + private final @Nullable String mongoOperator; + private final @Nullable ArgumentType argumentType; + private final @Nullable String[] argumentMap; /** * Creates new {@link AggregationMethodReference}. @@ -209,7 +213,8 @@ public class MethodReferenceNode extends ExpressionNode { * @param argumentType can be {@literal null}. * @param argumentMap can be {@literal null}. */ - private AggregationMethodReference(String mongoOperator, ArgumentType argumentType, String[] argumentMap) { + private AggregationMethodReference(@Nullable String mongoOperator, @Nullable ArgumentType argumentType, + @Nullable String[] argumentMap) { this.mongoOperator = mongoOperator; this.argumentType = argumentType; @@ -221,6 +226,7 @@ public class MethodReferenceNode extends ExpressionNode { * * @return can be {@literal null}. */ + @Nullable public String getMongoOperator() { return this.mongoOperator; } @@ -230,6 +236,7 @@ public class MethodReferenceNode extends ExpressionNode { * * @return never {@literal null}. */ + @Nullable public ArgumentType getArgumentType() { return this.argumentType; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryBean.java index a2eba1b3c..462bc0911 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryBean.java @@ -31,7 +31,7 @@ import org.springframework.util.Assert; /** * {@link CdiRepositoryBean} to create Mongo repository instances. - * + * * @author Oliver Gierke * @author Mark Paluch */ @@ -41,13 +41,13 @@ public class MongoRepositoryBean extends CdiRepositoryBean { /** * Creates a new {@link MongoRepositoryBean}. - * + * * @param operations must not be {@literal null}. * @param qualifiers must not be {@literal null}. * @param repositoryType must not be {@literal null}. * @param beanManager must not be {@literal null}. * @param detector detector for the custom {@link org.springframework.data.repository.Repository} implementations - * {@link CustomRepositoryImplementationDetector}, can be {@literal null}. + * {@link CustomRepositoryImplementationDetector}, can be {@link Optional#empty()}. */ public MongoRepositoryBean(Bean operations, Set qualifiers, Class repositoryType, BeanManager beanManager, Optional detector) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryExtension.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryExtension.java index b7ed7fa7a..8976eff9d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryExtension.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/cdi/MongoRepositoryExtension.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2014 the original author or authors. + * Copyright 2011-2017 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. @@ -39,7 +39,7 @@ import org.springframework.data.repository.cdi.CdiRepositoryExtensionSupport; /** * CDI extension to export Mongo repositories. - * + * * @author Oliver Gierke * @author Mark Paluch */ @@ -93,7 +93,7 @@ public class MongoRepositoryExtension extends CdiRepositoryExtensionSupport { /** * Creates a {@link CdiRepositoryBean} for the repository of the given type. - * + * * @param the type of the repository. * @param repositoryType the class representing the repository. * @param qualifiers the qualifiers to be applied to the bean. @@ -113,6 +113,6 @@ public class MongoRepositoryExtension extends CdiRepositoryExtensionSupport { // Construct and return the repository bean. return new MongoRepositoryBean(mongoOperations, qualifiers, repositoryType, beanManager, - Optional.ofNullable(getCustomImplementationDetector())); + Optional.of(getCustomImplementationDetector())); } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ConvertingParameterAccessor.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ConvertingParameterAccessor.java index 3e501cc5f..7508fd1b3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ConvertingParameterAccessor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ConvertingParameterAccessor.java @@ -32,6 +32,7 @@ import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; import org.springframework.data.mongodb.core.query.TextCriteria; import org.springframework.data.repository.query.ParameterAccessor; import org.springframework.data.util.TypeInformation; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; @@ -39,7 +40,7 @@ import com.mongodb.DBRef; /** * Custom {@link ParameterAccessor} that uses a {@link MongoWriter} to serialize parameters into Mongo format. - * + * * @author Oliver Gierke * @author Christoph Strobl * @author Thomas Darimont @@ -52,7 +53,7 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor { /** * Creates a new {@link ConvertingParameterAccessor} with the given {@link MongoWriter} and delegate. - * + * * @param writer must not be {@literal null}. * @param delegate must not be {@literal null}. */ @@ -136,12 +137,13 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor { /** * Converts the given value with the underlying {@link MongoWriter}. - * + * * @param value can be {@literal null}. * @param typeInformation can be {@literal null}. * @return */ - private Object getConvertedValue(Object value, TypeInformation typeInformation) { + @Nullable + private Object getConvertedValue(Object value, @Nullable TypeInformation typeInformation) { return writer.convertToMongoType(value, typeInformation == null ? null : typeInformation.getActualType()); } @@ -155,7 +157,7 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor { /** * Custom {@link Iterator} to convert items before returning them. - * + * * @author Oliver Gierke */ private class ConvertingIterator implements PotentiallyConvertingIterator { @@ -164,7 +166,7 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor { /** * Creates a new {@link ConvertingIterator} for the given delegate. - * + * * @param delegate */ public ConvertingIterator(Iterator delegate) { @@ -229,11 +231,11 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor { * Returns the given object as {@link Collection}. Will do a copy of it if it implements {@link Iterable} or is an * array. Will return an empty {@link Collection} in case {@literal null} is given. Will wrap all other types into a * single-element collection. - * + * * @param source * @return */ - private static Collection asCollection(Object source) { + private static Collection asCollection(@Nullable Object source) { if (source instanceof Iterable) { @@ -263,14 +265,14 @@ public class ConvertingParameterAccessor implements MongoParameterAccessor { /** * Custom {@link Iterator} that adds a method to access elements in a converted manner. - * + * * @author Oliver Gierke */ public interface PotentiallyConvertingIterator extends Iterator { /** * Returns the next element which has already been converted. - * + * * @return */ Object nextConverted(MongoPersistentProperty property); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ExpressionEvaluatingParameterBinder.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ExpressionEvaluatingParameterBinder.java index 82df6f3a3..21aa12cec 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ExpressionEvaluatingParameterBinder.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ExpressionEvaluatingParameterBinder.java @@ -35,6 +35,7 @@ import org.springframework.data.repository.query.EvaluationContextProvider; import org.springframework.expression.EvaluationContext; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; @@ -77,7 +78,7 @@ class ExpressionEvaluatingParameterBinder { * Bind values provided by {@link MongoParameterAccessor} to placeholders in {@literal raw} while considering * potential conversions and parameter types. * - * @param raw can be {@literal null} or empty. + * @param raw can be empty. * @param accessor must not be {@literal null}. * @param bindingContext must not be {@literal null}. * @return {@literal null} if given {@code raw} value is empty. @@ -85,7 +86,7 @@ class ExpressionEvaluatingParameterBinder { public String bind(String raw, MongoParameterAccessor accessor, BindingContext bindingContext) { if (!StringUtils.hasText(raw)) { - return null; + return raw; } return replacePlaceholders(raw, accessor, bindingContext); @@ -147,7 +148,8 @@ class ExpressionEvaluatingParameterBinder { * @param raw the raw binding value * @param isExpression {@literal true} if the binding value results from a SpEL expression. */ - private void postProcessQuotedBinding(StringBuffer buffer, String valueForBinding, Object raw, boolean isExpression) { + private void postProcessQuotedBinding(StringBuffer buffer, String valueForBinding, @Nullable Object raw, + boolean isExpression) { int quotationMarkIndex = buffer.length() - valueForBinding.length() - 1; char quotationMark = buffer.charAt(quotationMarkIndex); @@ -230,6 +232,7 @@ class ExpressionEvaluatingParameterBinder { * @param parameterValues must not be {@literal null}. * @return */ + @Nullable private Object evaluateExpression(String expressionString, MongoParameters parameters, Object[] parameterValues) { EvaluationContext evaluationContext = evaluationContextProvider.getEvaluationContext(parameters, parameterValues); @@ -390,7 +393,7 @@ class ExpressionEvaluatingParameterBinder { private int parameterIndex; private final String parameter; private final boolean quoted; - private final String suffix; + private final @Nullable String suffix; /* * (non-Javadoc) diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameterAccessor.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameterAccessor.java index 6c67778e3..e5689f38e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameterAccessor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameterAccessor.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2015 the original author or authors. + * Copyright 2011-2017 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. @@ -20,19 +20,21 @@ import org.springframework.data.geo.Distance; import org.springframework.data.geo.Point; import org.springframework.data.mongodb.core.query.TextCriteria; import org.springframework.data.repository.query.ParameterAccessor; +import org.springframework.lang.Nullable; /** * Mongo-specific {@link ParameterAccessor} exposing a maximum distance parameter. - * + * * @author Oliver Gierke * @author Christoph Strobl * @author Thomas Darimont + * @author Mark Paluch */ public interface MongoParameterAccessor extends ParameterAccessor { /** * Returns a {@link Distance} to be applied to Mongo geo queries. - * + * * @return the maximum distance to apply to the geo query or {@literal null} if there's no {@link Distance} parameter * at all or the given value for it was {@literal null}. */ @@ -40,22 +42,23 @@ public interface MongoParameterAccessor extends ParameterAccessor { /** * Returns the {@link Point} to use for a geo-near query. - * + * * @return */ Point getGeoNearLocation(); /** * Returns the {@link TextCriteria} to be used for full text query. - * + * * @return null if not set. * @since 1.6 */ + @Nullable TextCriteria getFullText(); /** * Returns the raw parameter values of the underlying query method. - * + * * @return * @since 1.8 */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameters.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameters.java index 323ef0fdb..1a0905bd6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameters.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParameters.java @@ -29,23 +29,22 @@ import org.springframework.data.mongodb.repository.query.MongoParameters.MongoPa import org.springframework.data.repository.query.Parameter; import org.springframework.data.repository.query.Parameters; import org.springframework.data.util.ClassTypeInformation; -import org.springframework.data.util.ReflectionUtils; import org.springframework.data.util.TypeInformation; import org.springframework.lang.Nullable; -import org.springframework.util.ClassUtils; /** * Custom extension of {@link Parameters} discovering additional * * @author Oliver Gierke * @author Christoph Strobl + * @author Mark Paluch */ public class MongoParameters extends Parameters { private final int rangeIndex; private final int maxDistanceIndex; - private final Integer fullTextIndex; - private final Integer nearIndex; + private final @Nullable Integer fullTextIndex; + private final @Nullable Integer nearIndex; /** * Creates a new {@link MongoParameters} instance from the given {@link Method} and {@link MongoQueryMethod}. @@ -74,8 +73,8 @@ public class MongoParameters extends Parameters this.nearIndex = index; } - private MongoParameters(List parameters, int maxDistanceIndex, Integer nearIndex, - Integer fullTextIndex, int rangeIndex) { + private MongoParameters(List parameters, int maxDistanceIndex, @Nullable Integer nearIndex, + @Nullable Integer fullTextIndex, int rangeIndex) { super(parameters); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParametersParameterAccessor.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParametersParameterAccessor.java index 7f8ac79b4..b7c3b40bd 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParametersParameterAccessor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoParametersParameterAccessor.java @@ -24,15 +24,17 @@ import org.springframework.data.geo.Point; import org.springframework.data.mongodb.core.query.Term; import org.springframework.data.mongodb.core.query.TextCriteria; import org.springframework.data.repository.query.ParametersParameterAccessor; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Mongo-specific {@link ParametersParameterAccessor} to allow access to the {@link Distance} parameter. - * + * * @author Oliver Gierke * @author Christoph Strobl * @author Thomas Darimont + * @author Mark Paluch */ public class MongoParametersParameterAccessor extends ParametersParameterAccessor implements MongoParameterAccessor { @@ -41,7 +43,7 @@ public class MongoParametersParameterAccessor extends ParametersParameterAccesso /** * Creates a new {@link MongoParametersParameterAccessor}. - * + * * @param method must not be {@literal null}. * @param values must not be {@literal null}. */ @@ -103,6 +105,7 @@ public class MongoParametersParameterAccessor extends ParametersParameterAccesso * (non-Javadoc) * @see org.springframework.data.mongodb.repository.query.MongoParameterAccessor#getFullText() */ + @Nullable @Override public TextCriteria getFullText() { int index = method.getParameters().getFullTextParameterIndex(); @@ -130,7 +133,7 @@ public class MongoParametersParameterAccessor extends ParametersParameterAccesso ClassUtils.getShortName(fullText.getClass()))); } - /* + /* * (non-Javadoc) * @see org.springframework.data.mongodb.repository.query.MongoParameterAccessor#getValues() */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryExecution.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryExecution.java index 20460b4b5..57fe51ad5 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryExecution.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryExecution.java @@ -164,10 +164,7 @@ interface MongoQueryExecution { distances.getUpperBound().getValue().ifPresent(it -> nearQuery.maxDistance(it).in(it.getMetric())); Pageable pageable = accessor.getPageable(); - - if (pageable != null) { - nearQuery.with(pageable); - } + nearQuery.with(pageable); return (GeoResults) operation.near(nearQuery).all(); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryMethod.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryMethod.java index 76ed6ea81..3bac7bc82 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryMethod.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/MongoQueryMethod.java @@ -103,6 +103,7 @@ public class MongoQueryMethod extends QueryMethod { * * @return */ + @Nullable String getAnnotatedQuery() { return findAnnotatedQuery().orElse(null); } @@ -204,6 +205,7 @@ public class MongoQueryMethod extends QueryMethod { * * @return */ + @Nullable Query getQueryAnnotation() { return AnnotatedElementUtils.findMergedAnnotation(method, Query.class); } @@ -226,6 +228,7 @@ public class MongoQueryMethod extends QueryMethod { * @return * @since 1.6 */ + @Nullable Meta getMetaAnnotation() { return AnnotatedElementUtils.findMergedAnnotation(method, Meta.class); } @@ -236,6 +239,7 @@ public class MongoQueryMethod extends QueryMethod { * @return * @since 2.0 */ + @Nullable Tailable getTailableAnnotation() { return AnnotatedElementUtils.findMergedAnnotation(method, Tailable.class); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecution.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecution.java index 4531927c9..d92f7dc6f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecution.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecution.java @@ -33,6 +33,7 @@ import org.springframework.data.repository.query.ResultProcessor; import org.springframework.data.repository.query.ReturnedType; import org.springframework.data.repository.util.ReactiveWrappers; import org.springframework.data.util.TypeInformation; +import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; import com.mongodb.client.result.DeleteResult; @@ -124,7 +125,7 @@ interface ReactiveMongoQueryExecution { } @SuppressWarnings({ "unchecked", "rawtypes" }) - protected Flux> doExecuteQuery(Query query, Class type, String collection) { + protected Flux> doExecuteQuery(@Nullable Query query, Class type, String collection) { Point nearLocation = accessor.getGeoNearLocation(); NearQuery nearQuery = NearQuery.near(nearLocation); @@ -138,10 +139,7 @@ interface ReactiveMongoQueryExecution { distances.getLowerBound().getValue().ifPresent(it -> nearQuery.minDistance(it).in(it.getMetric())); Pageable pageable = accessor.getPageable(); - - if (pageable != null) { - nearQuery.with(pageable); - } + nearQuery.with(pageable); return (Flux) operations.geoNear(nearQuery, type, collection); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/StringBasedMongoQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/StringBasedMongoQuery.java index 0a1c1f1b8..c8a65d2c7 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/StringBasedMongoQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/query/StringBasedMongoQuery.java @@ -30,6 +30,7 @@ import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.repository.query.ExpressionEvaluatingParameterBinder.BindingContext; import org.springframework.data.repository.query.EvaluationContextProvider; import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.StringUtils; @@ -213,7 +214,7 @@ public class StringBasedMongoQuery extends AbstractMongoQuery { * Returns a list of {@link ParameterBinding}s found in the given {@code input} or an * {@link Collections#emptyList()}. * - * @param input can be {@literal null} or empty. + * @param input can be empty. * @param bindings must not be {@literal null}. * @return */ @@ -372,7 +373,7 @@ public class StringBasedMongoQuery extends AbstractMongoQuery { private final int parameterIndex; private final boolean quoted; - private final String expression; + private final @Nullable String expression; /** * Creates a new {@link ParameterBinding} with the given {@code parameterIndex} and {@code quoted} information. @@ -384,7 +385,7 @@ public class StringBasedMongoQuery extends AbstractMongoQuery { this(parameterIndex, quoted, null); } - public ParameterBinding(int parameterIndex, boolean quoted, String expression) { + public ParameterBinding(int parameterIndex, boolean quoted, @Nullable String expression) { this.parameterIndex = parameterIndex; this.quoted = quoted; @@ -403,6 +404,7 @@ public class StringBasedMongoQuery extends AbstractMongoQuery { return "?" + (isExpression() ? "expr" : "") + parameterIndex; } + @Nullable public String getExpression() { return expression; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/IndexEnsuringQueryCreationListener.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/IndexEnsuringQueryCreationListener.java index 2c018f885..9c3677fe5 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/IndexEnsuringQueryCreationListener.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/IndexEnsuringQueryCreationListener.java @@ -38,7 +38,7 @@ import org.springframework.util.Assert; /** * {@link QueryCreationListener} inspecting {@link PartTreeMongoQuery}s and creating an index for the properties it * refers to. - * + * * @author Oliver Gierke * @author Mark Paluch * @author Christoph Strobl @@ -52,7 +52,7 @@ class IndexEnsuringQueryCreationListener implements QueryCreationListener extends PersistentEntityInform implements MongoEntityInformation { private final MongoPersistentEntity entityMetadata; - private final String customCollectionName; + private final @Nullable String customCollectionName; private final Class fallbackIdType; /** @@ -52,7 +53,7 @@ public class MappingMongoEntityInformation extends PersistentEntityInform * @param entity must not be {@literal null}. * @param fallbackIdType can be {@literal null}. */ - public MappingMongoEntityInformation(MongoPersistentEntity entity, Class fallbackIdType) { + public MappingMongoEntityInformation(MongoPersistentEntity entity, @Nullable Class fallbackIdType) { this(entity, null, fallbackIdType); } @@ -76,8 +77,8 @@ public class MappingMongoEntityInformation extends PersistentEntityInform * @param idType can be {@literal null}. */ @SuppressWarnings("unchecked") - private MappingMongoEntityInformation(MongoPersistentEntity entity, String customCollectionName, - Class idType) { + private MappingMongoEntityInformation(MongoPersistentEntity entity, @Nullable String customCollectionName, + @Nullable Class idType) { super(entity); @@ -112,6 +113,6 @@ public class MappingMongoEntityInformation extends PersistentEntityInform return super.getIdType(); } - return fallbackIdType != null ? fallbackIdType : (Class) ObjectId.class; + return fallbackIdType; } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoEntityInformationSupport.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoEntityInformationSupport.java index f728084ee..f5fe77c24 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoEntityInformationSupport.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoEntityInformationSupport.java @@ -18,6 +18,7 @@ package org.springframework.data.mongodb.repository.support; import org.springframework.data.domain.Persistable; import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; import org.springframework.data.mongodb.repository.query.MongoEntityInformation; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; @@ -26,6 +27,7 @@ import org.springframework.util.ClassUtils; * {@link MongoPersistentEntity}. * * @author Christoph Strobl + * @author Mark Paluch * @since 1.10 */ final class MongoEntityInformationSupport { @@ -40,7 +42,8 @@ final class MongoEntityInformationSupport { * @return never {@literal null}. */ @SuppressWarnings("unchecked") - static MongoEntityInformation entityInformationFor(MongoPersistentEntity entity, Class idType) { + static MongoEntityInformation entityInformationFor(MongoPersistentEntity entity, + @Nullable Class idType) { Assert.notNull(entity, "Entity must not be null!"); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java index a6fa10fcd..e2ea077b7 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/MongoRepositoryFactory.java @@ -144,7 +144,7 @@ public class MongoRepositoryFactory extends RepositoryFactorySupport { } private MongoEntityInformation getEntityInformation(Class domainClass, - RepositoryMetadata metadata) { + @Nullable RepositoryMetadata metadata) { MongoPersistentEntity entity = mappingContext.getRequiredPersistentEntity(domainClass); return MongoEntityInformationSupport. entityInformationFor(entity, diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java index be9c9dc83..d29a297a7 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/ReactiveMongoRepositoryFactory.java @@ -113,7 +113,7 @@ public class ReactiveMongoRepositoryFactory extends ReactiveRepositoryFactorySup @SuppressWarnings("unchecked") private MongoEntityInformation getEntityInformation(Class domainClass, - RepositoryInformation information) { + @Nullable RepositoryInformation information) { MongoPersistentEntity entity = mappingContext.getRequiredPersistentEntity(domainClass); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepository.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepository.java index 081afe1f9..fa8ef6c6b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepository.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleMongoRepository.java @@ -36,6 +36,7 @@ import org.springframework.data.mongodb.repository.query.MongoEntityInformation; import org.springframework.data.repository.support.PageableExecutionUtils; import org.springframework.data.util.StreamUtils; import org.springframework.data.util.Streamable; +import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** @@ -355,7 +356,7 @@ public class SimpleMongoRepository implements MongoRepository { return where(entityInformation.getIdAttribute()).is(id); } - private List findAll(Query query) { + private List findAll(@Nullable Query query) { if (query == null) { return Collections.emptyList(); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleReactiveMongoRepository.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleReactiveMongoRepository.java index fb0330d5a..322d36bf3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleReactiveMongoRepository.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SimpleReactiveMongoRepository.java @@ -380,7 +380,7 @@ public class SimpleReactiveMongoRepository implement Assert.notNull(entityStream, "The given Publisher of entities must not be null!"); return Flux.from(entityStream)// - .map(it -> entityInformation.getRequiredId(it))// + .map(entityInformation::getRequiredId)// .flatMap(this::deleteById)// .then(); } @@ -404,10 +404,6 @@ public class SimpleReactiveMongoRepository implement private Flux findAll(Query query) { - if (query == null) { - return Flux.empty(); - } - return mongoOperations.find(query, entityInformation.getJavaType(), entityInformation.getCollectionName()); } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbQuery.java index 93fd4080f..397dcad4f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/repository/support/SpringDataMongodbQuery.java @@ -27,9 +27,10 @@ import com.mongodb.DBObject; import com.querydsl.mongodb.AbstractMongodbQuery; /** - * Spring Data specific {@link MongodbQuery} implementation. - * + * Spring Data specific {@link AbstractMongodbQuery} implementation. + * * @author Oliver Gierke + * @author Mark Paluch */ public class SpringDataMongodbQuery extends AbstractMongodbQuery> { @@ -37,7 +38,7 @@ public class SpringDataMongodbQuery extends AbstractMongodbQuery extends AbstractMongodbQuery extends AbstractMongodbQuery type) { + protected DBCollection getCollection(Class type) { return ((MongoTemplate) operations).getMongoDbFactory().getLegacyDb() .getCollection(operations.getCollectionName(type)); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java index 059f88755..1a50d3e09 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/BsonUtils.java @@ -1,5 +1,5 @@ /* - * Copyright 2016 the original author or authors. + * Copyright 2016-2017 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. @@ -19,16 +19,20 @@ import java.util.Map; import org.bson.Document; import org.bson.conversions.Bson; +import org.springframework.lang.Nullable; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; /** * @author Christoph Strobl + * @author Mark Paluch * @since 2.0 */ public class BsonUtils { + @SuppressWarnings("unchecked") + @Nullable public static T get(Bson bson, String key) { return (T) asMap(bson).get(key); } @@ -43,7 +47,7 @@ public class BsonUtils { throw new IllegalArgumentException("o_O what's that? Cannot read values from " + bson.getClass()); } - public static void addToMap(Bson bson, String key, Object value) { + public static void addToMap(Bson bson, String key, @Nullable Object value) { if (bson instanceof Document) { ((Document) bson).put(key, value); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoDbErrorCodes.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoDbErrorCodes.java index ff846dd0b..50f61a943 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoDbErrorCodes.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/MongoDbErrorCodes.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 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. @@ -17,10 +17,13 @@ package org.springframework.data.mongodb.util; import java.util.HashMap; +import org.springframework.lang.Nullable; + /** * {@link MongoDbErrorCodes} holds MongoDB specific error codes outlined in {@literal mongo/base/error_codes.err}. - * + * * @author Christoph Strobl + * @author Mark Paluch * @since 1.8 */ public final class MongoDbErrorCodes { @@ -114,27 +117,27 @@ public final class MongoDbErrorCodes { errorCodes.putAll(permissionDeniedCodes); } - public static boolean isDataIntegrityViolationCode(Integer errorCode) { + public static boolean isDataIntegrityViolationCode(@Nullable Integer errorCode) { return errorCode == null ? false : dataIntegrityViolationCodes.containsKey(errorCode); } - public static boolean isDataAccessResourceFailureCode(Integer errorCode) { + public static boolean isDataAccessResourceFailureCode(@Nullable Integer errorCode) { return errorCode == null ? false : dataAccessResourceFailureCodes.containsKey(errorCode); } - public static boolean isDuplicateKeyCode(Integer errorCode) { + public static boolean isDuplicateKeyCode(@Nullable Integer errorCode) { return errorCode == null ? false : duplicateKeyCodes.containsKey(errorCode); } - public static boolean isPermissionDeniedCode(Integer errorCode) { + public static boolean isPermissionDeniedCode(@Nullable Integer errorCode) { return errorCode == null ? false : permissionDeniedCodes.containsKey(errorCode); } - public static boolean isInvalidDataAccessApiUsageCode(Integer errorCode) { + public static boolean isInvalidDataAccessApiUsageCode(@Nullable Integer errorCode) { return errorCode == null ? false : invalidDataAccessApiUsageExeption.containsKey(errorCode); } - public static String getErrorDescription(Integer errorCode) { + public static String getErrorDescription(@Nullable Integer errorCode) { return errorCode == null ? null : errorCodes.get(errorCode); } -} \ No newline at end of file +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/package-info.java index 34b262fd2..7caec410f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/util/package-info.java @@ -1,21 +1,6 @@ -/* - * Copyright 2013 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 - * - * http://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. - */ /** - * @author Thomas Darimont + * MongoDB driver-specific utility classes for {@link org.bson.conversions.Bson} and {@link com.mongodb.DBObject} + * interaction. */ @org.springframework.lang.NonNullApi package org.springframework.data.mongodb.util; - diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecutionUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecutionUnitTests.java index 9723de421..21bdae0b7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecutionUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/query/ReactiveMongoQueryExecutionUnitTests.java @@ -19,6 +19,8 @@ import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.mockito.Mockito.*; +import reactor.core.publisher.Flux; + import java.lang.reflect.Method; import java.util.Arrays; @@ -28,6 +30,7 @@ import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Range; import org.springframework.data.geo.Distance; import org.springframework.data.geo.GeoResult; @@ -40,8 +43,6 @@ import org.springframework.data.mongodb.repository.query.ReactiveMongoQueryExecu import org.springframework.data.util.ClassTypeInformation; import org.springframework.util.ClassUtils; -import reactor.core.publisher.Flux; - /** * Unit tests for {@link ReactiveMongoQueryExecution}. * @@ -80,6 +81,7 @@ public class ReactiveMongoQueryExecutionUnitTests { Method geoNear = ClassUtils.getMethod(GeoRepo.class, "geoNear"); Query query = new Query(); + when(parameterAccessor.getPageable()).thenReturn(Pageable.unpaged()); when(parameterAccessor.getGeoNearLocation()).thenReturn(new Point(1, 2)); when(parameterAccessor.getDistanceRange()).thenReturn(new Range<>(null, null));