From 025691a97a4a591477a44d22dda6f35626210ee6 Mon Sep 17 00:00:00 2001 From: Oliver Gierke Date: Fri, 13 May 2011 18:04:19 +0200 Subject: [PATCH] Change indentation from spaces to tabs. --- .../CannotGetMongoDbConnectionException.java | 60 +- .../document/mongodb/CollectionCallback.java | 2 +- .../document/mongodb/CollectionOptions.java | 76 +- .../data/document/mongodb/CursorPreparer.java | 15 +- .../data/document/mongodb/DbCallback.java | 2 +- .../data/document/mongodb/DbHolder.java | 88 +- .../data/document/mongodb/MongoAdmin.java | 105 +- .../mongodb/MongoAdminOperations.java | 12 +- .../data/document/mongodb/MongoDbUtils.java | 242 ++--- .../mongodb/MongoExceptionTranslator.java | 79 +- .../document/mongodb/MongoFactoryBean.java | 151 ++- .../document/mongodb/MongoOperations.java | 942 +++++++++--------- .../mongodb/MongoOptionsFactoryBean.java | 172 ++-- .../mongodb/MongoPropertyDescriptors.java | 367 ++++--- .../data/document/mongodb/MongoReader.java | 27 +- .../mongodb/MongoSynchronization.java | 7 +- .../data/document/mongodb/MongoTemplate.java | 287 +++--- .../data/document/mongodb/MongoWriter.java | 21 +- .../document/mongodb/WriteResultChecking.java | 2 +- .../config/AbstractMongoConfiguration.java | 112 ++- .../config/MappingMongoConverterParser.java | 23 +- .../mongodb/config/MongoJmxParser.java | 62 +- .../document/mongodb/config/MongoParser.java | 99 +- .../config/MongoRepositoryConfigParser.java | 117 ++- .../MongoRepositoryNamespaceHandler.java | 28 +- .../SimpleMongoRepositoryConfiguration.java | 272 +++-- .../document/mongodb/config/package-info.java | 1 + .../convert/MappingMongoConverter.java | 246 ++--- .../mongodb/convert/MongoBeanWrapper.java | 106 +- .../mongodb/convert/MongoConverter.java | 39 +- .../mongodb/convert/ObjectIdConverters.java | 110 +- .../mongodb/convert/SimpleMongoConverter.java | 49 +- .../data/document/mongodb/geo/Box.java | 90 +- .../data/document/mongodb/geo/Circle.java | 47 +- .../data/document/mongodb/geo/Point.java | 122 ++- .../document/mongodb/index/CompoundIndex.java | 3 +- .../mongodb/index/CompoundIndexes.java | 4 +- .../mongodb/index/GeoSpatialIndexed.java | 12 +- .../mongodb/index/IndexDefinition.java | 4 +- .../mongodb/index/IndexDirection.java | 3 +- .../mongodb/index/IndexPredicate.java | 42 +- .../data/document/mongodb/index/Indexed.java | 15 +- .../mapping/BasicMongoPersistentEntity.java | 88 +- .../mapping/BasicMongoPersistentProperty.java | 125 ++- .../data/document/mongodb/mapping/DBRef.java | 13 +- .../document/mongodb/mapping/Document.java | 7 +- .../mongodb/mapping/MongoMappingContext.java | 49 +- .../mapping/MongoPersistentEntity.java | 4 +- .../MongoPersistentEntityIndexCreator.java | 47 +- .../mapping/MongoPersistentProperty.java | 8 +- .../mapping/SimpleMongoMappingContext.java | 140 +-- .../event/AbstractMappingEventListener.java | 96 +- .../mapping/event/AfterConvertEvent.java | 8 +- .../mongodb/mapping/event/AfterLoadEvent.java | 8 +- .../mongodb/mapping/event/AfterSaveEvent.java | 8 +- .../mapping/event/BeforeConvertEvent.java | 9 +- .../mapping/event/BeforeSaveEvent.java | 8 +- .../mapping/event/MongoMappingEvent.java | 28 +- .../mongodb/monitor/AbstractMonitor.java | 67 +- .../mongodb/monitor/AssertMetrics.java | 58 +- .../monitor/BackgroundFlushingMetrics.java | 71 +- .../mongodb/monitor/BtreeIndexCounters.java | 72 +- .../mongodb/monitor/ConnectionMetrics.java | 36 +- .../mongodb/monitor/GlobalLockMetrics.java | 78 +- .../mongodb/monitor/MemoryMetrics.java | 64 +- .../mongodb/monitor/OperationCounters.java | 65 +- .../document/mongodb/monitor/ServerInfo.java | 50 +- .../mongodb/monitor/package-info.java | 1 + .../data/document/mongodb/package-info.java | 1 + .../document/mongodb/query/BasicQuery.java | 100 +- .../data/document/mongodb/query/Criteria.java | 735 +++++++------- .../mongodb/query/CriteriaDefinition.java | 2 +- .../data/document/mongodb/query/Field.java | 57 +- .../mongodb/query/GeospatialIndex.java | 115 ++- .../data/document/mongodb/query/Index.java | 138 ++- .../data/document/mongodb/query/Order.java | 4 +- .../data/document/mongodb/query/Query.java | 2 +- .../document/mongodb/query/QueryMapper.java | 6 +- .../data/document/mongodb/query/Sort.java | 35 +- .../data/document/mongodb/query/Update.java | 32 +- .../document/mongodb/query/package-info.java | 1 + .../repository/AbstractMongoQuery.java | 250 ++--- .../ConvertingParameterAccessor.java | 264 ++--- .../MappingMongoEntityInformation.java | 90 +- .../repository/MongoAnnotationProcessor.java | 24 +- .../repository/MongoEntityInformation.java | 26 +- .../mongodb/repository/MongoQueryCreator.java | 273 +++-- .../mongodb/repository/MongoQueryMethod.java | 108 +- .../mongodb/repository/MongoRepository.java | 28 +- .../MongoRepositoryFactoryBean.java | 447 +++++---- .../repository/PartTreeMongoQuery.java | 60 +- .../document/mongodb/repository/Query.java | 28 +- .../repository/QueryDslMongoRepository.java | 379 ++++--- .../repository/QueryDslPredicateExecutor.java | 3 +- .../mongodb/repository/QueryUtils.java | 85 +- .../repository/SimpleMongoRepository.java | 353 +++---- .../repository/StringBasedMongoQuery.java | 114 +-- .../mongodb/repository/package-info.java | 1 + .../document/mongodb/GeoSpatialAppConfig.java | 34 +- .../document/mongodb/GeoSpatialTests.java | 231 +++-- .../data/document/mongodb/JmxServer.java | 14 +- .../data/document/mongodb/Message.java | 77 +- .../mongodb/MongoAdminIntegrationTests.java | 35 +- .../mongodb/MongoOperationsUnitTests.java | 12 +- .../mongodb/MongoTemplateMappingTests.java | 91 +- .../document/mongodb/MongoTemplateTests.java | 774 +++++++------- .../mongodb/MongoTemplateUnitTests.java | 112 +-- .../data/document/mongodb/Person.java | 125 ++- .../data/document/mongodb/PersonExample.java | 140 ++- .../mongodb/PersonExampleAppConfig.java | 27 +- .../document/mongodb/PersonReadConverter.java | 2 +- .../document/mongodb/PersonWithAList.java | 3 +- .../PersonWithIdPropertyOfTypeObjectId.java | 42 +- .../PersonWithIdPropertyOfTypeString.java | 54 +- .../PersonWith_idPropertyOfTypeObjectId.java | 42 +- .../PersonWith_idPropertyOfTypeString.java | 43 +- .../data/document/mongodb/Portfolio.java | 76 +- .../mongodb/SimpleMongoConverterTests.java | 772 +++++++------- .../data/document/mongodb/SomeEnumTest.java | 82 +- .../data/document/mongodb/Trade.java | 57 +- .../data/document/mongodb/TradeBatch.java | 43 +- .../data/document/mongodb/User.java | 89 +- .../data/document/mongodb/Venue.java | 59 +- .../mongodb/analytics/MvcAnalyticsTests.java | 72 +- .../mongodb/config/MongoNamespaceTests.java | 70 +- .../convert/CustomConvertersUnitTests.java | 162 +-- .../document/mongodb/mapping/Account.java | 31 +- .../document/mongodb/mapping/AccountPojo.java | 36 +- .../document/mongodb/mapping/Address.java | 72 +- .../document/mongodb/mapping/BasePerson.java | 56 +- .../mongodb/mapping/GenericMappingTests.java | 82 +- .../mongodb/mapping/GeoIndexedAppConfig.java | 30 +- .../mongodb/mapping/GeoIndexedTests.java | 8 +- .../document/mongodb/mapping/GeoLocation.java | 4 +- .../document/mongodb/mapping/Location.java | 60 +- .../MappingMongoConverterUnitTests.java | 299 +++--- .../mongodb/mapping/MappingTests.java | 92 +- .../data/document/mongodb/mapping/Person.java | 9 +- .../mapping/PersonCustomCollection1.java | 10 +- .../mapping/PersonCustomCollection2.java | 6 +- .../mongodb/mapping/PersonCustomIdName.java | 1 - .../mongodb/mapping/PersonMapProperty.java | 34 +- .../mongodb/mapping/PersonMultiDimArrays.java | 4 +- .../document/mongodb/mapping/PersonPojo.java | 20 +- .../mongodb/mapping/PersonSimpleList.java | 20 +- .../SimpleMappingContextUnitTests.java | 30 +- .../monitor/MongoMonitorIntegrationTests.java | 29 +- .../document/mongodb/query/CriteriaTests.java | 48 +- .../document/mongodb/query/IndexTests.java | 76 +- .../mongodb/query/QueryMapperUnitTests.java | 70 +- .../document/mongodb/query/QueryTests.java | 49 +- .../document/mongodb/query/SortTests.java | 20 +- .../document/mongodb/query/UpdateTests.java | 183 ++-- ...tractPersonRepositoryIntegrationTests.java | 332 +++--- .../document/mongodb/repository/Address.java | 105 +- .../document/mongodb/repository/Contact.java | 20 +- .../mongodb/repository/ContactRepository.java | 2 +- .../ContactRepositoryIntegrationTests.java | 22 +- .../MongoQueryCreatorUnitTests.java | 85 +- .../MongoRepositoryFactoryUnitTests.java | 59 +- .../document/mongodb/repository/Person.java | 280 +++--- .../mongodb/repository/PersonRepository.java | 156 ++- .../PersonRepositoryIntegrationTests.java | 6 +- .../StringBasedMongoQueryUnitTests.java | 95 +- .../repository/StubParameterAccessor.java | 93 +- .../MongoNamespaceIntegrationTests.java | 27 +- 166 files changed, 7570 insertions(+), 7663 deletions(-) diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CannotGetMongoDbConnectionException.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CannotGetMongoDbConnectionException.java index cafcd7541..a2455f520 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CannotGetMongoDbConnectionException.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CannotGetMongoDbConnectionException.java @@ -19,39 +19,39 @@ import org.springframework.dao.DataAccessResourceFailureException; public class CannotGetMongoDbConnectionException extends DataAccessResourceFailureException { - private String username; - - private char[] password; - - private String database; - - private static final long serialVersionUID = 1172099106475265589L; + private String username; - public CannotGetMongoDbConnectionException(String msg, Throwable cause) { - super(msg, cause); - } - - public CannotGetMongoDbConnectionException(String msg) { - super(msg); - } + private char[] password; - public CannotGetMongoDbConnectionException(String msg, String database, String username, char[] password2) { - super(msg); - this.username = username; - this.password = password2; - this.database = database; - } + private String database; - public String getUsername() { - return username; - } + private static final long serialVersionUID = 1172099106475265589L; - public char[] getPassword() { - return password; - } + public CannotGetMongoDbConnectionException(String msg, Throwable cause) { + super(msg, cause); + } + + public CannotGetMongoDbConnectionException(String msg) { + super(msg); + } + + public CannotGetMongoDbConnectionException(String msg, String database, String username, char[] password2) { + super(msg); + this.username = username; + this.password = password2; + this.database = database; + } + + public String getUsername() { + return username; + } + + public char[] getPassword() { + return password; + } + + public String getDatabase() { + return database; + } - public String getDatabase() { - return database; - } - } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionCallback.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionCallback.java index 8c29a6178..513e6b9d8 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionCallback.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionCallback.java @@ -21,6 +21,6 @@ import org.springframework.dao.DataAccessException; public interface CollectionCallback { - T doInCollection(DBCollection collection) throws MongoException, DataAccessException; + T doInCollection(DBCollection collection) throws MongoException, DataAccessException; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionOptions.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionOptions.java index 52f4769f0..96394bf60 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionOptions.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CollectionOptions.java @@ -17,55 +17,57 @@ package org.springframework.data.document.mongodb; /** * Provides a simple wrapper to encapsulate the variety of settings you can use when creating a collection. - * + * * @author Thomas Risberg */ public class CollectionOptions { - private Integer maxDocuments; + private Integer maxDocuments; - private Integer size; + private Integer size; - private Boolean capped; + private Boolean capped; - /** - * Constructs a new CollectionOptions instance. - * - * @param size the collection size in bytes, this data space is preallocated - * @param maxDocuments the maximum number of documents in the collection. - * @param capped true to created a "capped" collection (fixed size with auto-FIFO behavior - * based on insertion order), false otherwise. - */ - public CollectionOptions(Integer size, Integer maxDocuments, Boolean capped) { - super(); - this.maxDocuments = maxDocuments; - this.size = size; - this.capped = capped; - } + /** + * Constructs a new CollectionOptions instance. + * + * @param size + * the collection size in bytes, this data space is preallocated + * @param maxDocuments + * the maximum number of documents in the collection. + * @param capped + * true to created a "capped" collection (fixed size with auto-FIFO behavior based on insertion order), false + * otherwise. + */ + public CollectionOptions(Integer size, Integer maxDocuments, Boolean capped) { + super(); + this.maxDocuments = maxDocuments; + this.size = size; + this.capped = capped; + } - public Integer getMaxDocuments() { - return maxDocuments; - } + public Integer getMaxDocuments() { + return maxDocuments; + } - public void setMaxDocuments(Integer maxDocuments) { - this.maxDocuments = maxDocuments; - } + public void setMaxDocuments(Integer maxDocuments) { + this.maxDocuments = maxDocuments; + } - public Integer getSize() { - return size; - } + public Integer getSize() { + return size; + } - public void setSize(Integer size) { - this.size = size; - } + public void setSize(Integer size) { + this.size = size; + } - public Boolean getCapped() { - return capped; - } - - public void setCapped(Boolean capped) { - this.capped = capped; - } + public Boolean getCapped() { + return capped; + } + public void setCapped(Boolean capped) { + this.capped = capped; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CursorPreparer.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CursorPreparer.java index 9d07c0684..13659923e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CursorPreparer.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/CursorPreparer.java @@ -17,18 +17,17 @@ package org.springframework.data.document.mongodb; import com.mongodb.DBCursor; - /** * Simple callback interface to allow customization of a {@link DBCursor}. - * + * * @author Oliver Gierke */ public interface CursorPreparer { - /** - * Prepare the given cursor (apply limits, skips and so on). Returns th eprepared cursor. - * - * @param cursor - */ - DBCursor prepare(DBCursor cursor); + /** + * Prepare the given cursor (apply limits, skips and so on). Returns th eprepared cursor. + * + * @param cursor + */ + DBCursor prepare(DBCursor cursor); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbCallback.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbCallback.java index 4ea233359..9bd6943c6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbCallback.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbCallback.java @@ -21,5 +21,5 @@ import org.springframework.dao.DataAccessException; public interface DbCallback { - T doInDB(DB db) throws MongoException, DataAccessException; + T doInDB(DB db) throws MongoException, DataAccessException; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbHolder.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbHolder.java index d6f713aa1..375a9d704 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbHolder.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/DbHolder.java @@ -8,63 +8,59 @@ import org.springframework.transaction.support.ResourceHolderSupport; import org.springframework.util.Assert; class DbHolder extends ResourceHolderSupport { - private static final Object DEFAULT_KEY = new Object(); + private static final Object DEFAULT_KEY = new Object(); - private final Map dbMap = new ConcurrentHashMap(); + private final Map dbMap = new ConcurrentHashMap(); + public DbHolder(DB db) { + addDB(db); + } - public DbHolder(DB db) { - addDB(db); - } + public DbHolder(Object key, DB db) { + addDB(key, db); + } - public DbHolder(Object key, DB db) { - addDB(key, db); - } + public DB getDB() { + return getDB(DEFAULT_KEY); + } + public DB getDB(Object key) { + return this.dbMap.get(key); + } - public DB getDB() { - return getDB(DEFAULT_KEY); - } + public DB getAnyDB() { + if (!this.dbMap.isEmpty()) { + return this.dbMap.values().iterator().next(); + } + return null; + } - public DB getDB(Object key) { - return this.dbMap.get(key); - } + public void addDB(DB session) { + addDB(DEFAULT_KEY, session); + } + public void addDB(Object key, DB session) { + Assert.notNull(key, "Key must not be null"); + Assert.notNull(session, "DB must not be null"); + this.dbMap.put(key, session); + } - public DB getAnyDB() { - if (!this.dbMap.isEmpty()) { - return this.dbMap.values().iterator().next(); - } - return null; - } + public DB removeDB(Object key) { + return this.dbMap.remove(key); + } - public void addDB(DB session) { - addDB(DEFAULT_KEY, session); - } + public boolean containsDB(DB session) { + return this.dbMap.containsValue(session); + } - public void addDB(Object key, DB session) { - Assert.notNull(key, "Key must not be null"); - Assert.notNull(session, "DB must not be null"); - this.dbMap.put(key, session); - } + public boolean isEmpty() { + return this.dbMap.isEmpty(); + } - public DB removeDB(Object key) { - return this.dbMap.remove(key); - } - - public boolean containsDB(DB session) { - return this.dbMap.containsValue(session); - } - - public boolean isEmpty() { - return this.dbMap.isEmpty(); - } - - public boolean doesNotHoldNonDefaultDB() { - synchronized (this.dbMap) { - return this.dbMap.isEmpty() || - (this.dbMap.size() == 1 && this.dbMap.containsKey(DEFAULT_KEY)); - } - } + public boolean doesNotHoldNonDefaultDB() { + synchronized (this.dbMap) { + return this.dbMap.isEmpty() || (this.dbMap.size() == 1 && this.dbMap.containsKey(DEFAULT_KEY)); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdmin.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdmin.java index e516eee87..ec6f9d835 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdmin.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdmin.java @@ -24,71 +24,72 @@ import org.springframework.jmx.export.annotation.ManagedResource; /** * Mongo server administration exposed via JMX annotations - * + * * @author Mark Pollack */ @ManagedResource(description = "Mongo Admin Operations") public class MongoAdmin implements MongoAdminOperations { - /** - * Logger available to subclasses - */ - protected final Log logger = LogFactory.getLog(getClass()); + /** + * Logger available to subclasses + */ + protected final Log logger = LogFactory.getLog(getClass()); - private Mongo mongo; - private String username; - private String password; + private Mongo mongo; + private String username; + private String password; - public MongoAdmin(Mongo mongo) { - this.mongo = mongo; - } + public MongoAdmin(Mongo mongo) { + this.mongo = mongo; + } - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.MongoAdminOperations#dropDatabase(java.lang.String) - */ - @ManagedOperation - public void dropDatabase(String databaseName) { - getDB(databaseName).dropDatabase(); - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.MongoAdminOperations#dropDatabase(java.lang.String) + */ + @ManagedOperation + public void dropDatabase(String databaseName) { + getDB(databaseName).dropDatabase(); + } - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.MongoAdminOperations#createDatabase(java.lang.String) - */ - @ManagedOperation - public void createDatabase(String databaseName) { - getDB(databaseName); - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.MongoAdminOperations#createDatabase(java.lang.String) + */ + @ManagedOperation + public void createDatabase(String databaseName) { + getDB(databaseName); + } - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.MongoAdminOperations#getDatabaseStats(java.lang.String) - */ - @ManagedOperation - public String getDatabaseStats(String databaseName) { - return getDB(databaseName).getStats().toString(); - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.MongoAdminOperations#getDatabaseStats(java.lang.String) + */ + @ManagedOperation + public String getDatabaseStats(String databaseName) { + return getDB(databaseName).getStats().toString(); + } - /** - * Sets the username to use to connect to the Mongo database - * - * @param username The username to use - */ - public void setUsername(String username) { - this.username = username; - } + /** + * Sets the username to use to connect to the Mongo database + * + * @param username + * The username to use + */ + public void setUsername(String username) { + this.username = username; + } - /** - * Sets the password to use to authenticate with the Mongo database. - * - * @param password The password to use - */ - public void setPassword(String password) { + /** + * Sets the password to use to authenticate with the Mongo database. + * + * @param password + * The password to use + */ + public void setPassword(String password) { - this.password = password; - } + this.password = password; + } - - DB getDB(String databaseName) { - return MongoDbUtils.getDB(mongo, databaseName, username, password == null ? null : password.toCharArray()); - } + DB getDB(String databaseName) { + return MongoDbUtils.getDB(mongo, databaseName, username, password == null ? null : password.toCharArray()); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdminOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdminOperations.java index 4d1b799c0..40113cbd6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdminOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoAdminOperations.java @@ -4,13 +4,13 @@ import org.springframework.jmx.export.annotation.ManagedOperation; public interface MongoAdminOperations { - @ManagedOperation - public abstract void dropDatabase(String databaseName); + @ManagedOperation + public abstract void dropDatabase(String databaseName); - @ManagedOperation - public abstract void createDatabase(String databaseName); + @ManagedOperation + public abstract void createDatabase(String databaseName); - @ManagedOperation - public abstract String getDatabaseStats(String databaseName); + @ManagedOperation + public abstract String getDatabaseStats(String databaseName); } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoDbUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoDbUtils.java index b0decf66a..3d589bd2e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoDbUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoDbUtils.java @@ -27,8 +27,9 @@ import org.springframework.util.Assert; /** * Helper class featuring helper methods for internal MongoDb classes. *

- *

Mainly intended for internal use within the framework. - * + *

+ * Mainly intended for internal use within the framework. + * * @author Thomas Risberg * @author Graeme Rocher * @author Oliver Gierke @@ -36,133 +37,138 @@ import org.springframework.util.Assert; */ public abstract class MongoDbUtils { - private static final Log LOGGER = LogFactory.getLog(MongoDbUtils.class); + private static final Log LOGGER = LogFactory.getLog(MongoDbUtils.class); - /** - * Private constructor to prevent instantiation. - */ - private MongoDbUtils() { + /** + * Private constructor to prevent instantiation. + */ + private MongoDbUtils() { - } + } - /** - * Obtains a {@link DB} connection for the given {@link Mongo} instance and database name - * - * @param mongo The {@link Mongo} instance - * @param databaseName The database name - * @return The {@link DB} connection - */ - public static DB getDB(Mongo mongo, String databaseName) { - return doGetDB(mongo, databaseName, null, null, true); - } + /** + * Obtains a {@link DB} connection for the given {@link Mongo} instance and database name + * + * @param mongo + * The {@link Mongo} instance + * @param databaseName + * The database name + * @return The {@link DB} connection + */ + public static DB getDB(Mongo mongo, String databaseName) { + return doGetDB(mongo, databaseName, null, null, true); + } - /** - * Obtains a {@link DB} connection for the given {@link Mongo} instance and database name - * - * @param mongo The {@link Mongo} instance - * @param databaseName The database name - * @param username The username to authenticate with - * @param password The password to authenticate with - * @return The {@link DB} connection - */ - public static DB getDB(Mongo mongo, String databaseName, String username, char[] password) { - return doGetDB(mongo, databaseName, username, password, true); - } + /** + * Obtains a {@link DB} connection for the given {@link Mongo} instance and database name + * + * @param mongo + * The {@link Mongo} instance + * @param databaseName + * The database name + * @param username + * The username to authenticate with + * @param password + * The password to authenticate with + * @return The {@link DB} connection + */ + public static DB getDB(Mongo mongo, String databaseName, String username, char[] password) { + return doGetDB(mongo, databaseName, username, password, true); + } - public static DB doGetDB(Mongo mongo, String databaseName, String username, char[] password, boolean allowCreate) { - Assert.notNull(mongo, "No Mongo instance specified"); + public static DB doGetDB(Mongo mongo, String databaseName, String username, char[] password, boolean allowCreate) { + Assert.notNull(mongo, "No Mongo instance specified"); - DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo); - if (dbHolder != null && !dbHolder.isEmpty()) { - // pre-bound Mongo DB - DB db = null; - if (TransactionSynchronizationManager.isSynchronizationActive() && - dbHolder.doesNotHoldNonDefaultDB()) { - // Spring transaction management is active -> - db = dbHolder.getDB(); - if (db != null && !dbHolder.isSynchronizedWithTransaction()) { - LOGGER.debug("Registering Spring transaction synchronization for existing Mongo DB"); - TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo)); - dbHolder.setSynchronizedWithTransaction(true); - } - } - if (db != null) { - return db; - } - } + DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo); + if (dbHolder != null && !dbHolder.isEmpty()) { + // pre-bound Mongo DB + DB db = null; + if (TransactionSynchronizationManager.isSynchronizationActive() && dbHolder.doesNotHoldNonDefaultDB()) { + // Spring transaction management is active -> + db = dbHolder.getDB(); + if (db != null && !dbHolder.isSynchronizedWithTransaction()) { + LOGGER.debug("Registering Spring transaction synchronization for existing Mongo DB"); + TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo)); + dbHolder.setSynchronizedWithTransaction(true); + } + } + if (db != null) { + return db; + } + } - LOGGER.trace("Getting Mongo Database name=["+databaseName+"]"); - DB db = mongo.getDB(databaseName); - - boolean credentialsGiven = username != null && password != null; - if (credentialsGiven && !db.isAuthenticated()) { - //Note, can only authenticate once against the same com.mongodb.DB object. - if (!db.authenticate(username, password)) { - throw new CannotGetMongoDbConnectionException("Failed to authenticate to database [" + databaseName + - "], username = [" + username + "], password = [" + new String(password) + "]", databaseName, username, password ); - } - } + LOGGER.trace("Getting Mongo Database name=[" + databaseName + "]"); + DB db = mongo.getDB(databaseName); - // Use same Session for further Mongo actions within the transaction. - // Thread object will get removed by synchronization at transaction completion. - if (TransactionSynchronizationManager.isSynchronizationActive()) { - // We're within a Spring-managed transaction, possibly from JtaTransactionManager. - LOGGER.debug("Registering Spring transaction synchronization for new Hibernate Session"); - DbHolder holderToUse = dbHolder; - if (holderToUse == null) { - holderToUse = new DbHolder(db); - } else { - holderToUse.addDB(db); - } - TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo)); - holderToUse.setSynchronizedWithTransaction(true); - if (holderToUse != dbHolder) { - TransactionSynchronizationManager.bindResource(mongo, holderToUse); - } - } + boolean credentialsGiven = username != null && password != null; + if (credentialsGiven && !db.isAuthenticated()) { + // Note, can only authenticate once against the same com.mongodb.DB object. + if (!db.authenticate(username, password)) { + throw new CannotGetMongoDbConnectionException("Failed to authenticate to database [" + databaseName + + "], username = [" + username + "], password = [" + new String(password) + "]", databaseName, username, + password); + } + } - // Check whether we are allowed to return the DB. - if (!allowCreate && !isDBTransactional(db, mongo)) { - throw new IllegalStateException("No Mongo DB bound to thread, " + - "and configuration does not allow creation of non-transactional one here"); - } + // Use same Session for further Mongo actions within the transaction. + // Thread object will get removed by synchronization at transaction completion. + if (TransactionSynchronizationManager.isSynchronizationActive()) { + // We're within a Spring-managed transaction, possibly from JtaTransactionManager. + LOGGER.debug("Registering Spring transaction synchronization for new Hibernate Session"); + DbHolder holderToUse = dbHolder; + if (holderToUse == null) { + holderToUse = new DbHolder(db); + } else { + holderToUse.addDB(db); + } + TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo)); + holderToUse.setSynchronizedWithTransaction(true); + if (holderToUse != dbHolder) { + TransactionSynchronizationManager.bindResource(mongo, holderToUse); + } + } - return db; - } + // Check whether we are allowed to return the DB. + if (!allowCreate && !isDBTransactional(db, mongo)) { + throw new IllegalStateException("No Mongo DB bound to thread, " + + "and configuration does not allow creation of non-transactional one here"); + } + return db; + } - /** - * Return whether the given DB instance is transactional, that is, - * bound to the current thread by Spring's transaction facilities. - * - * @param db the DB to check - * @param mongo the Mongo instance that the DB was created with - * (may be null) - * @return whether the DB is transactional - */ - public static boolean isDBTransactional(DB db, Mongo mongo) { - if (mongo == null) { - return false; - } - DbHolder dbHolder = - (DbHolder) TransactionSynchronizationManager.getResource(mongo); - return (dbHolder != null && dbHolder.containsDB(db)); - } + /** + * Return whether the given DB instance is transactional, that is, bound to the current thread by Spring's transaction + * facilities. + * + * @param db + * the DB to check + * @param mongo + * the Mongo instance that the DB was created with (may be null) + * @return whether the DB is transactional + */ + public static boolean isDBTransactional(DB db, Mongo mongo) { + if (mongo == null) { + return false; + } + DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo); + return (dbHolder != null && dbHolder.containsDB(db)); + } - /** - * Perform actual closing of the Mongo DB object, - * catching and logging any cleanup exceptions thrown. - * - * @param db the DB to close (may be null) - */ - public static void closeDB(DB db) { - if (db != null) { - LOGGER.debug("Closing Mongo DB object"); - try { - db.requestDone(); - } catch (Throwable ex) { - LOGGER.debug("Unexpected exception on closing Mongo DB object", ex); - } - } - } + /** + * Perform actual closing of the Mongo DB object, catching and logging any cleanup exceptions thrown. + * + * @param db + * the DB to close (may be null) + */ + public static void closeDB(DB db) { + if (db != null) { + LOGGER.debug("Closing Mongo DB object"); + try { + db.requestDone(); + } catch (Throwable ex) { + LOGGER.debug("Unexpected exception on closing Mongo DB object", ex); + } + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoExceptionTranslator.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoExceptionTranslator.java index 2880b1069..92611e38f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoExceptionTranslator.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoExceptionTranslator.java @@ -34,51 +34,52 @@ import org.springframework.data.document.UncategorizedDocumentStoreException; * Simple {@link PersistenceExceptionTranslator} for Mongo. Convert the given runtime exception to an appropriate * exception from the {@code org.springframework.dao} hierarchy. Return {@literal null} if no translation is * appropriate: any other exception may have resulted from user code, and should not be translated. - * - * @param ex runtime exception that occurred + * + * @param ex + * runtime exception that occurred * @author Oliver Gierke * @return the corresponding DataAccessException instance, or {@literal null} if the exception should not be translated */ public class MongoExceptionTranslator implements PersistenceExceptionTranslator { - /* - * (non-Javadoc) - * - * @see org.springframework.dao.support.PersistenceExceptionTranslator# - * translateExceptionIfPossible(java.lang.RuntimeException) - */ - public DataAccessException translateExceptionIfPossible(RuntimeException ex) { + /* + * (non-Javadoc) + * + * @see org.springframework.dao.support.PersistenceExceptionTranslator# + * translateExceptionIfPossible(java.lang.RuntimeException) + */ + public DataAccessException translateExceptionIfPossible(RuntimeException ex) { - // Check for well-known MongoException subclasses. + // Check for well-known MongoException subclasses. - // All other MongoExceptions - if (ex instanceof DuplicateKey) { - return new DuplicateKeyException(ex.getMessage(), ex); - } - if (ex instanceof Network) { - return new DataAccessResourceFailureException(ex.getMessage(), ex); - } - if (ex instanceof CursorNotFound) { - return new DataAccessResourceFailureException(ex.getMessage(), ex); - } - if (ex instanceof MongoException) { - int code = ((MongoException)ex).getCode(); - if (code == 11000 || code == 11001) { - throw new DuplicateKeyException(ex.getMessage(), ex); - } else if (code == 12000 || code == 13440) { - throw new DataAccessResourceFailureException(ex.getMessage(), ex); - } else if (code == 10003 || code == 12001 || code == 12010 || code == 12011 || code == 12012 ) { - throw new InvalidDataAccessApiUsageException(ex.getMessage(), ex); - } - return new UncategorizedDocumentStoreException(ex.getMessage(), ex); - } - if (ex instanceof MongoInternalException) { - return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex); - } + // All other MongoExceptions + if (ex instanceof DuplicateKey) { + return new DuplicateKeyException(ex.getMessage(), ex); + } + if (ex instanceof Network) { + return new DataAccessResourceFailureException(ex.getMessage(), ex); + } + if (ex instanceof CursorNotFound) { + return new DataAccessResourceFailureException(ex.getMessage(), ex); + } + if (ex instanceof MongoException) { + int code = ((MongoException) ex).getCode(); + if (code == 11000 || code == 11001) { + throw new DuplicateKeyException(ex.getMessage(), ex); + } else if (code == 12000 || code == 13440) { + throw new DataAccessResourceFailureException(ex.getMessage(), ex); + } else if (code == 10003 || code == 12001 || code == 12010 || code == 12011 || code == 12012) { + throw new InvalidDataAccessApiUsageException(ex.getMessage(), ex); + } + return new UncategorizedDocumentStoreException(ex.getMessage(), ex); + } + if (ex instanceof MongoInternalException) { + return new InvalidDataAccessResourceUsageException(ex.getMessage(), ex); + } - // If we get here, we have an exception that resulted from user code, - // rather than the persistence provider, so we return null to indicate - // that translation should not occur. - return null; - } + // If we get here, we have an exception that resulted from user code, + // rather than the persistence provider, so we return null to indicate + // that translation should not occur. + return null; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoFactoryBean.java index 36ccfe9fc..54990351c 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoFactoryBean.java @@ -31,101 +31,100 @@ import org.springframework.util.Assert; /** * Convenient factory for configuring MongoDB. - * + * * @author Thomas Risberg * @author Graeme Rocher * @since 1.0 */ public class MongoFactoryBean implements FactoryBean, InitializingBean, PersistenceExceptionTranslator { + /** + * Logger, available to subclasses. + */ + protected final Log logger = LogFactory.getLog(getClass()); - /** - * Logger, available to subclasses. - */ - protected final Log logger = LogFactory.getLog(getClass()); + private Mongo mongo; + private MongoOptions mongoOptions; + private String host; + private Integer port; + private List replicaSetSeeds; + private List replicaPair; - private Mongo mongo; - private MongoOptions mongoOptions; - private String host; - private Integer port; - private List replicaSetSeeds; - private List replicaPair; + private PersistenceExceptionTranslator exceptionTranslator = new MongoExceptionTranslator(); - private PersistenceExceptionTranslator exceptionTranslator = new MongoExceptionTranslator(); + public void setMongoOptions(MongoOptions mongoOptions) { + this.mongoOptions = mongoOptions; + } - public void setMongoOptions(MongoOptions mongoOptions) { - this.mongoOptions = mongoOptions; - } + public void setReplicaSetSeeds(List replicaSetSeeds) { + this.replicaSetSeeds = replicaSetSeeds; + } - public void setReplicaSetSeeds(List replicaSetSeeds) { - this.replicaSetSeeds = replicaSetSeeds; - } + public void setReplicaPair(List replicaPair) { + this.replicaPair = replicaPair; + } - public void setReplicaPair(List replicaPair) { - this.replicaPair = replicaPair; - } + public void setHost(String host) { + this.host = host; + } - public void setHost(String host) { - this.host = host; - } + public void setPort(int port) { + this.port = port; + } - public void setPort(int port) { - this.port = port; - } + public PersistenceExceptionTranslator getExceptionTranslator() { + return exceptionTranslator; + } - public PersistenceExceptionTranslator getExceptionTranslator() { - return exceptionTranslator; - } + public void setExceptionTranslator(PersistenceExceptionTranslator exceptionTranslator) { + this.exceptionTranslator = exceptionTranslator; + } - public void setExceptionTranslator( - PersistenceExceptionTranslator exceptionTranslator) { - this.exceptionTranslator = exceptionTranslator; - } + public Mongo getObject() throws Exception { + Assert.notNull(mongo, "Mongo must not be null"); + return mongo; + } - public Mongo getObject() throws Exception { - Assert.notNull(mongo, "Mongo must not be null"); - return mongo; - } + public Class getObjectType() { + return Mongo.class; + } - public Class getObjectType() { - return Mongo.class; - } + public boolean isSingleton() { + return false; + } - public boolean isSingleton() { - return false; - } + public void afterPropertiesSet() throws Exception { + // apply defaults - convenient when used to configure for tests + // in an application context + if (mongo == null) { - public void afterPropertiesSet() throws Exception { - // apply defaults - convenient when used to configure for tests - // in an application context - if (mongo == null) { + if (host == null) { + logger.warn("Property host not specified. Using default configuration"); + mongo = new Mongo(); + } else { + ServerAddress defaultOptions = new ServerAddress(); + if (mongoOptions == null) + mongoOptions = new MongoOptions(); + if (replicaPair != null) { + if (replicaPair.size() < 2) { + throw new CannotGetMongoDbConnectionException("A replica pair must have two server entries"); + } + mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions); + } else if (replicaSetSeeds != null) { + mongo = new Mongo(replicaSetSeeds, mongoOptions); + } else { + String mongoHost = host != null ? host : defaultOptions.getHost(); + if (port != null) { + mongo = new Mongo(new ServerAddress(mongoHost, port), mongoOptions); + } else { + mongo = new Mongo(mongoHost, mongoOptions); + } + } + } + } + } - if (host == null) { - logger.warn("Property host not specified. Using default configuration"); - mongo = new Mongo(); - } else { - ServerAddress defaultOptions = new ServerAddress(); - if (mongoOptions == null) mongoOptions = new MongoOptions(); - if (replicaPair != null) { - if (replicaPair.size() < 2) { - throw new CannotGetMongoDbConnectionException("A replica pair must have two server entries"); - } - mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions); - } else if (replicaSetSeeds != null) { - mongo = new Mongo(replicaSetSeeds, mongoOptions); - } else { - String mongoHost = host != null ? host : defaultOptions.getHost(); - if (port != null) { - mongo = new Mongo(new ServerAddress(mongoHost, port), mongoOptions); - } else { - mongo = new Mongo(mongoHost, mongoOptions); - } - } - } - } - } - - public DataAccessException translateExceptionIfPossible(RuntimeException ex) { - return exceptionTranslator.translateExceptionIfPossible(ex); - } + public DataAccessException translateExceptionIfPossible(RuntimeException ex) { + return exceptionTranslator.translateExceptionIfPossible(ex); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java index e3d8a7a41..cf8b9f1ed 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOperations.java @@ -28,495 +28,537 @@ import org.springframework.data.document.mongodb.query.Query; import org.springframework.data.document.mongodb.query.Update; /** - * Interface that specifies a basic set of MongoDB operations. Implemented by {@link MongoTemplate}. - * Not often used but a useful option for extensibility and testability (as it can be easily mocked, stubbed, or be - * the target of a JDK proxy). - * + * Interface that specifies a basic set of MongoDB operations. Implemented by {@link MongoTemplate}. Not often used but + * a useful option for extensibility and testability (as it can be easily mocked, stubbed, or be the target of a JDK + * proxy). + * * @author Thomas Risberg * @author Mark Pollack * @author Oliver Gierke */ public interface MongoOperations { - /** - * The collection name used for the specified class by this template. - * - * @return - */ - String getCollectionName(Class clazz); + /** + * The collection name used for the specified class by this template. + * + * @return + */ + String getCollectionName(Class clazz); - /** - * Execute the a MongoDB command expressed as a JSON string. This will call the method - * JSON.parse that is part of the MongoDB driver to convert the JSON string to a DBObject. - * Any errors that result from executing this command will be converted into Spring's DAO - * exception hierarchy. - * - * @param jsonCommand a MongoDB command expressed as a JSON string. - */ - CommandResult executeCommand(String jsonCommand); + /** + * Execute the a MongoDB command expressed as a JSON string. This will call the method JSON.parse that is part of the + * MongoDB driver to convert the JSON string to a DBObject. Any errors that result from executing this command will be + * converted into Spring's DAO exception hierarchy. + * + * @param jsonCommand + * a MongoDB command expressed as a JSON string. + */ + CommandResult executeCommand(String jsonCommand); - /** - * Execute a MongoDB command. Any errors that result from executing this command will be converted - * into Spring's DAO exception hierarchy. - * - * @param command a MongoDB command - */ - CommandResult executeCommand(DBObject command); + /** + * Execute a MongoDB command. Any errors that result from executing this command will be converted into Spring's DAO + * exception hierarchy. + * + * @param command + * a MongoDB command + */ + CommandResult executeCommand(DBObject command); - /** - * Executes a {@link DbCallback} translating any exceptions as necessary. - *

- * Allows for returning a result object, that is a domain object or a collection of domain objects. - * - * @param return type - * @param action callback object that specifies the MongoDB actions to perform on the passed in DB instance. - * @return a result object returned by the action or null - */ - T execute(DbCallback action); + /** + * Executes a {@link DbCallback} translating any exceptions as necessary. + *

+ * Allows for returning a result object, that is a domain object or a collection of domain objects. + * + * @param + * return type + * @param action + * callback object that specifies the MongoDB actions to perform on the passed in DB instance. + * @return a result object returned by the action or null + */ + T execute(DbCallback action); - /** - * Executes the given {@link CollectionCallback} on the entity collection of the specified class. - *

- * Allows for returning a result object, that is a domain object or a collection of domain objects. - * - * @param entityClass class that determines the collection to use - * @param return type - * @param action callback object that specifies the MongoDB action - * @return a result object returned by the action or null - */ - T execute(Class entityClass, CollectionCallback action); + /** + * Executes the given {@link CollectionCallback} on the entity collection of the specified class. + *

+ * Allows for returning a result object, that is a domain object or a collection of domain objects. + * + * @param entityClass + * class that determines the collection to use + * @param + * return type + * @param action + * callback object that specifies the MongoDB action + * @return a result object returned by the action or null + */ + T execute(Class entityClass, CollectionCallback action); - /** - * Executes the given {@link CollectionCallback} on the collection of the given name. - *

- * Allows for returning a result object, that is a domain object or a collection of domain objects. - * - * @param return type - * @param collectionName the name of the collection that specifies which DBCollection instance will be passed into - * @param action callback object that specifies the MongoDB action - * the callback action. - * @return a result object returned by the action or null - */ - T execute(String collectionName, CollectionCallback action); + /** + * Executes the given {@link CollectionCallback} on the collection of the given name. + *

+ * Allows for returning a result object, that is a domain object or a collection of domain objects. + * + * @param + * return type + * @param collectionName + * the name of the collection that specifies which DBCollection instance will be passed into + * @param action + * callback object that specifies the MongoDB action the callback action. + * @return a result object returned by the action or null + */ + T execute(String collectionName, CollectionCallback action); - /** - * Executes the given {@link DbCallback} within the same connection to the database so as to ensure - * consistency in a write heavy environment where you may read the data that you wrote. See the - * comments on {@see Java Driver Concurrency} - *

- * Allows for returning a result object, that is a domain object or a collection of domain objects. - * - * @param return type - * @param action callback that specified the MongoDB actions to perform on the DB instance - * @return a result object returned by the action or null - */ - T executeInSession(DbCallback action); + /** + * Executes the given {@link DbCallback} within the same connection to the database so as to ensure consistency in a + * write heavy environment where you may read the data that you wrote. See the comments on {@see Java Driver Concurrency} + *

+ * Allows for returning a result object, that is a domain object or a collection of domain objects. + * + * @param + * return type + * @param action + * callback that specified the MongoDB actions to perform on the DB instance + * @return a result object returned by the action or null + */ + T executeInSession(DbCallback action); - /** - * Create an uncapped collection with the provided name. - * - * @param collectionName name of the collection - * @return the created collection - */ - DBCollection createCollection(String collectionName); + /** + * Create an uncapped collection with the provided name. + * + * @param collectionName + * name of the collection + * @return the created collection + */ + DBCollection createCollection(String collectionName); - /** - * Create a collect with the provided name and options. - * - * @param collectionName name of the collection - * @param collectionOptions options to use when creating the collection. - * @return the created collection - */ - DBCollection createCollection(String collectionName, CollectionOptions collectionOptions); + /** + * Create a collect with the provided name and options. + * + * @param collectionName + * name of the collection + * @param collectionOptions + * options to use when creating the collection. + * @return the created collection + */ + DBCollection createCollection(String collectionName, CollectionOptions collectionOptions); - /** - * A set of collection names. - * - * @return list of collection names - */ - Set getCollectionNames(); + /** + * A set of collection names. + * + * @return list of collection names + */ + Set getCollectionNames(); - /** - * Get a collection by name, creating it if it doesn't exist. - *

- * Translate any exceptions as necessary. - * - * @param collectionName name of the collection - * @return an existing collection or a newly created one. - */ - DBCollection getCollection(String collectionName); + /** + * Get a collection by name, creating it if it doesn't exist. + *

+ * Translate any exceptions as necessary. + * + * @param collectionName + * name of the collection + * @return an existing collection or a newly created one. + */ + DBCollection getCollection(String collectionName); - /** - * Check to see if a collection with a given name exists. - *

- * Translate any exceptions as necessary. - * - * @param collectionName name of the collection - * @return true if a collection with the given name is found, false otherwise. - */ - boolean collectionExists(String collectionName); + /** + * Check to see if a collection with a given name exists. + *

+ * Translate any exceptions as necessary. + * + * @param collectionName + * name of the collection + * @return true if a collection with the given name is found, false otherwise. + */ + boolean collectionExists(String collectionName); - /** - * Drop the collection with the given name. - *

- * Translate any exceptions as necessary. - * - * @param collectionName name of the collection to drop/delete. - */ - void dropCollection(String collectionName); + /** + * Drop the collection with the given name. + *

+ * Translate any exceptions as necessary. + * + * @param collectionName + * name of the collection to drop/delete. + */ + void dropCollection(String collectionName); - /** - * Query for a list of objects of type T from the default collection. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * If your collection does not contain a homogeneous collection of types, this operation will not be an efficient - * way to map objects since the test for class type is done in the client and not on the server. - * - * @param targetClass the parameterized type of the returned list - * @return the converted collection - */ - List getCollection(Class targetClass); + /** + * Query for a list of objects of type T from the default collection. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way + * to map objects since the test for class type is done in the client and not on the server. + * + * @param targetClass + * the parameterized type of the returned list + * @return the converted collection + */ + List getCollection(Class targetClass); - /** - * Query for a list of objects of type T from the specified collection. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * If your collection does not contain a homogeneous collection of types, this operation will not be an efficient - * way to map objects since the test for class type is done in the client and not on the server. - * - * @param collectionName name of the collection to retrieve the objects from - * @param targetClass the parameterized type of the returned list. - * @return the converted collection - */ - List getCollection(String collectionName, Class targetClass); + /** + * Query for a list of objects of type T from the specified collection. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * If your collection does not contain a homogeneous collection of types, this operation will not be an efficient way + * to map objects since the test for class type is done in the client and not on the server. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param targetClass + * the parameterized type of the returned list. + * @return the converted collection + */ + List getCollection(String collectionName, Class targetClass); - /** - * Ensure that an index for the provided {@link IndexDefinition} exists for the default collection. - * If not it will be created. - * - * @param entityClass class that determines the collection to use - * @param indexDefinition - */ - void ensureIndex(Class entityClass, IndexDefinition indexDefinition); + /** + * Ensure that an index for the provided {@link IndexDefinition} exists for the default collection. If not it will be + * created. + * + * @param entityClass + * class that determines the collection to use + * @param indexDefinition + */ + void ensureIndex(Class entityClass, IndexDefinition indexDefinition); - /** - * Ensure that an index for the provided {@link IndexDefinition} exists. If not it will be - * created. - * - * @param collectionName - * @param index - */ - void ensureIndex(String collectionName, IndexDefinition indexDefinition); + /** + * Ensure that an index for the provided {@link IndexDefinition} exists. If not it will be created. + * + * @param collectionName + * @param index + */ + void ensureIndex(String collectionName, IndexDefinition indexDefinition); - /** - * Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object - * of the specified type. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more - * feature rich {@link Query}. - * - * @param query the query class that specifies the criteria used to find a record and also an optional fields specification - * @param targetClass the parameterized type of the returned list. - * @return the converted object - */ - T findOne(Query query, Class targetClass); + /** + * Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object of the + * specified type. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more + * feature rich {@link Query}. + * + * @param query + * the query class that specifies the criteria used to find a record and also an optional fields + * specification + * @param targetClass + * the parameterized type of the returned list. + * @return the converted object + */ + T findOne(Query query, Class targetClass); - /** - * Map the results of an ad-hoc query on the specified collection to a single instance of an object - * of the specified type. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more - * feature rich {@link Query}. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query class that specifies the criteria used to find a record and also an optional fields specification - * @param targetClass the parameterized type of the returned list. - * @return the converted object - */ - T findOne(String collectionName, Query query, - Class targetClass); + /** + * Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified + * type. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more + * feature rich {@link Query}. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query class that specifies the criteria used to find a record and also an optional fields + * specification + * @param targetClass + * the parameterized type of the returned list. + * @return the converted object + */ + T findOne(String collectionName, Query query, Class targetClass); - /** - * Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more - * feature rich {@link Query}. - * - * @param query the query class that specifies the criteria used to find a record and also an optional fields specification - * @param targetClass the parameterized type of the returned list. - * @return the List of converted objects - */ - List find(Query query, Class targetClass); + /** + * Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more + * feature rich {@link Query}. + * + * @param query + * the query class that specifies the criteria used to find a record and also an optional fields + * specification + * @param targetClass + * the parameterized type of the returned list. + * @return the List of converted objects + */ + List find(Query query, Class targetClass); - /** - * Map the results of an ad-hoc query on the specified collection to a List of the specified type. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more - * feature rich {@link Query}. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query class that specifies the criteria used to find a record and also an optional fields specification - * @param targetClass the parameterized type of the returned list. - * @return the List of converted objects - */ - List find(String collectionName, Query query, - Class targetClass); + /** + * Map the results of an ad-hoc query on the specified collection to a List of the specified type. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more + * feature rich {@link Query}. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query class that specifies the criteria used to find a record and also an optional fields + * specification + * @param targetClass + * the parameterized type of the returned list. + * @return the List of converted objects + */ + List find(String collectionName, Query query, Class targetClass); - /** - * Map the results of an ad-hoc query on the specified collection to a List of the specified type. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more - * feature rich {@link Query}. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query class that specifies the criteria used to find a record and also an optional fields specification - * @param targetClass the parameterized type of the returned list. - * @param preparer allows for customization of the DBCursor used when iterating over the result set, - * (apply limits, skips and so on). - * @return the List of converted objects. - */ - List find(String collectionName, Query query, Class targetClass, CursorPreparer preparer); + /** + * Map the results of an ad-hoc query on the specified collection to a List of the specified type. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more + * feature rich {@link Query}. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query class that specifies the criteria used to find a record and also an optional fields + * specification + * @param targetClass + * the parameterized type of the returned list. + * @param preparer + * allows for customization of the DBCursor used when iterating over the result set, (apply limits, skips and + * so on). + * @return the List of converted objects. + */ + List find(String collectionName, Query query, Class targetClass, CursorPreparer preparer); - /** - * Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object - * of the specified type. The first document that matches the query is returned and also removed from the - * collection in the database. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more - * feature rich {@link Query}. - * - * @param query the query class that specifies the criteria used to find a record and also an optional fields specification - * @param targetClass the parameterized type of the returned list. - * @return the converted object - */ - T findAndRemove(Query query, Class targetClass); + /** + * Map the results of an ad-hoc query on the default MongoDB collection to a single instance of an object of the + * specified type. The first document that matches the query is returned and also removed from the collection in the + * database. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more + * feature rich {@link Query}. + * + * @param query + * the query class that specifies the criteria used to find a record and also an optional fields + * specification + * @param targetClass + * the parameterized type of the returned list. + * @return the converted object + */ + T findAndRemove(Query query, Class targetClass); - /** - * Map the results of an ad-hoc query on the specified collection to a single instance of an object - * of the specified type. The first document that matches the query is returned and also removed from the - * collection in the database. - *

- * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more - * feature rich {@link Query}. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query class that specifies the criteria used to find a record and also an optional fields specification - * @param targetClass the parameterized type of the returned list. - * @return the converted object - */ - T findAndRemove(String collectionName, Query query, - Class targetClass); + /** + * Map the results of an ad-hoc query on the specified collection to a single instance of an object of the specified + * type. The first document that matches the query is returned and also removed from the collection in the database. + *

+ * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * The query is specified as a {@link Query} which can be created either using the {@link BasicQuery} or the more + * feature rich {@link Query}. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query class that specifies the criteria used to find a record and also an optional fields + * specification + * @param targetClass + * the parameterized type of the returned list. + * @return the converted object + */ + T findAndRemove(String collectionName, Query query, Class targetClass); - /** - * Insert the object into the default collection. - *

- * The object is converted to the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property - * is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from - * ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's - * new Type Conversion API. - * See Spring 3 Type Conversion" - * for more details. - *

- *

- * Insert is used to initially store the object into the database. - * To update an existing object use the save method. - * - * @param objectToSave the object to store in the collection. - */ - void insert(Object objectToSave); + /** + * Insert the object into the default collection. + *

+ * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a + * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your + * property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Conversion API. + * See Spring 3 Type + * Conversion" for more details. + *

+ *

+ * Insert is used to initially store the object into the database. To update an existing object use the save method. + * + * @param objectToSave + * the object to store in the collection. + */ + void insert(Object objectToSave); - /** - * Insert the object into the specified collection. - *

- * The object is converted to the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * Insert is used to initially store the object into the - * database. To update an existing object use the save method. - * - * @param collectionName name of the collection to store the object in - * @param objectToSave the object to store in the collection - */ - void insert(String collectionName, Object objectToSave); + /** + * Insert the object into the specified collection. + *

+ * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * Insert is used to initially store the object into the database. To update an existing object use the save method. + * + * @param collectionName + * name of the collection to store the object in + * @param objectToSave + * the object to store in the collection + */ + void insert(String collectionName, Object objectToSave); - /** - * Insert a list of objects into the default collection in a single batch write to the database. - * - * @param listToSave the list of objects to save. - */ - void insertList(List listToSave); + /** + * Insert a list of objects into the default collection in a single batch write to the database. + * + * @param listToSave + * the list of objects to save. + */ + void insertList(List listToSave); - /** - * Insert a list of objects into the specified collection in a single batch write to the database. - * - * @param collectionName name of the collection to store the object in - * @param listToSave the list of objects to save. - */ - void insertList(String collectionName, List listToSave); + /** + * Insert a list of objects into the specified collection in a single batch write to the database. + * + * @param collectionName + * name of the collection to store the object in + * @param listToSave + * the list of objects to save. + */ + void insertList(String collectionName, List listToSave); - /** - * Save the object to the default collection. This will perform an insert if the object is not already - * present, that is an 'upsert'. - *

- * The object is converted to the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property - * is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from - * ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's - * new Type Conversion API. - * See Spring 3 Type Conversion" - * for more details. - * - * @param objectToSave the object to store in the collection - */ - void save(Object objectToSave); + /** + * Save the object to the default collection. This will perform an insert if the object is not already present, that + * is an 'upsert'. + *

+ * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a + * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your + * property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Conversion API. + * See Spring 3 Type + * Conversion" for more details. + * + * @param objectToSave + * the object to store in the collection + */ + void save(Object objectToSave); - /** - * Save the object to the specified collection. This will perform an insert if the object is not already - * present, that is an 'upsert'. - *

- * The object is converted to the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. - *

- * If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property - * is a String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from - * ObjectId to your property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's - * new Type Cobnversion API. - * See Spring 3 Type Conversion" - * for more details. - * - * @param collectionName name of the collection to store the object in - * @param objectToSave the object to store in the collection - */ - void save(String collectionName, Object objectToSave); + /** + * Save the object to the specified collection. This will perform an insert if the object is not already present, that + * is an 'upsert'. + *

+ * The object is converted to the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. + *

+ * If you object has an "Id' property, it will be set with the generated Id from MongoDB. If your Id property is a + * String then MongoDB ObjectId will be used to populate that string. Otherwise, the conversion from ObjectId to your + * property type will be handled by Spring's BeanWrapper class that leverages Spring 3.0's new Type Cobnversion API. + * See Spring 3 Type + * Conversion" for more details. + * + * @param collectionName + * name of the collection to store the object in + * @param objectToSave + * the object to store in the collection + */ + void save(String collectionName, Object objectToSave); - /** - * Updates the first object that is found in the default collection that matches the query document - * with the provided updated document. - * - * @param entityClass class that determines the collection to use - * @param queryDoc the query document that specifies the criteria used to select a record to be updated - * @param updateDoc the update document that contains the updated object or $ operators to manipulate the - * existing object. - */ - WriteResult updateFirst(Class entityClass, Query query, Update update); + /** + * Updates the first object that is found in the default collection that matches the query document with the provided + * updated document. + * + * @param entityClass + * class that determines the collection to use + * @param queryDoc + * the query document that specifies the criteria used to select a record to be updated + * @param updateDoc + * the update document that contains the updated object or $ operators to manipulate the existing object. + */ + WriteResult updateFirst(Class entityClass, Query query, Update update); - /** - * Updates the first object that is found in the specified collection that matches the query document criteria - * with the provided updated document. - * - * @param collectionName name of the collection to update the object in - * @param queryDoc the query document that specifies the criteria used to select a record to be updated - * @param updateDoc the update document that contains the updated object or $ operators to manipulate the - * existing object. - */ - WriteResult updateFirst(String collectionName, Query query, - Update update); + /** + * Updates the first object that is found in the specified collection that matches the query document criteria with + * the provided updated document. + * + * @param collectionName + * name of the collection to update the object in + * @param queryDoc + * the query document that specifies the criteria used to select a record to be updated + * @param updateDoc + * the update document that contains the updated object or $ operators to manipulate the existing object. + */ + WriteResult updateFirst(String collectionName, Query query, Update update); - /** - * Updates all objects that are found in the default collection that matches the query document criteria - * with the provided updated document. - * - * @param entityClass class that determines the collection to use - * @param queryDoc the query document that specifies the criteria used to select a record to be updated - * @param updateDoc the update document that contains the updated object or $ operators to manipulate the - * existing object. - */ - WriteResult updateMulti(Class entityClass, Query query, Update update); + /** + * Updates all objects that are found in the default collection that matches the query document criteria with the + * provided updated document. + * + * @param entityClass + * class that determines the collection to use + * @param queryDoc + * the query document that specifies the criteria used to select a record to be updated + * @param updateDoc + * the update document that contains the updated object or $ operators to manipulate the existing object. + */ + WriteResult updateMulti(Class entityClass, Query query, Update update); - /** - * Updates all objects that are found in the specified collection that matches the query document criteria - * with the provided updated document. - * - * @param collectionName name of the collection to update the object in - * @param queryDoc the query document that specifies the criteria used to select a record to be updated - * @param updateDoc the update document that contains the updated object or $ operators to manipulate the - * existing object. - */ - WriteResult updateMulti(String collectionName, Query query, - Update update); + /** + * Updates all objects that are found in the specified collection that matches the query document criteria with the + * provided updated document. + * + * @param collectionName + * name of the collection to update the object in + * @param queryDoc + * the query document that specifies the criteria used to select a record to be updated + * @param updateDoc + * the update document that contains the updated object or $ operators to manipulate the existing object. + */ + WriteResult updateMulti(String collectionName, Query query, Update update); - /** - * Remove the given object from the collection by Id - * @param object - */ - void remove(Object object); - - - - /** - * Remove all documents from the default collection that match the provided query document criteria. - * - * @param queryDoc the query document that specifies the criteria used to remove a record - */ - void remove(Query query); - - /** - * Remove all documents from the default collection that match the provided query document criteria. The - * Class parameter is used to help convert the Id of the object if it is present in the query. - * @param - * @param query - * @param targetClass - */ - void remove(Query query, Class targetClass); - - /** - * Remove all documents from the specified collection that match the provided query document criteria. - * - * @param collectionName name of the collection where the objects will removed - * @param queryDoc the query document that specifies the criteria used to remove a record - */ - void remove(String collectionName, Query query); - - /** - * Remove all documents from the specified collection that match the provided query document criteria. - * The Class parameter is used to help convert the Id of the object if it is present in the query. - * @param collectionName - * @param query - * @param targetClass - */ - void remove(String collectionName, Query query, Class targetClass); + /** + * Remove the given object from the collection by Id + * + * @param object + */ + void remove(Object object); + + /** + * Remove all documents from the default collection that match the provided query document criteria. + * + * @param queryDoc + * the query document that specifies the criteria used to remove a record + */ + void remove(Query query); + + /** + * Remove all documents from the default collection that match the provided query document criteria. The Class + * parameter is used to help convert the Id of the object if it is present in the query. + * + * @param + * @param query + * @param targetClass + */ + void remove(Query query, Class targetClass); + + /** + * Remove all documents from the specified collection that match the provided query document criteria. + * + * @param collectionName + * name of the collection where the objects will removed + * @param queryDoc + * the query document that specifies the criteria used to remove a record + */ + void remove(String collectionName, Query query); + + /** + * Remove all documents from the specified collection that match the provided query document criteria. The Class + * parameter is used to help convert the Id of the object if it is present in the query. + * + * @param collectionName + * @param query + * @param targetClass + */ + void remove(String collectionName, Query query, Class targetClass); } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOptionsFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOptionsFactoryBean.java index e9baffd9d..74b86554f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOptionsFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoOptionsFactoryBean.java @@ -21,114 +21,108 @@ import org.springframework.beans.factory.InitializingBean; /** * A factory bean for consruction a MongoOptions instance - * + * * @author Graeme Rocher */ public class MongoOptionsFactoryBean implements FactoryBean, InitializingBean { - private static final MongoOptions MONGO_OPTIONS = new MongoOptions(); - /** - * number of connections allowed per host - * will block if run out - */ - private int connectionsPerHost = MONGO_OPTIONS.connectionsPerHost; + private static final MongoOptions MONGO_OPTIONS = new MongoOptions(); + /** + * number of connections allowed per host will block if run out + */ + private int connectionsPerHost = MONGO_OPTIONS.connectionsPerHost; - /** - * multiplier for connectionsPerHost for # of threads that can block - * if connectionsPerHost is 10, and threadsAllowedToBlockForConnectionMultiplier is 5, - * then 50 threads can block - * more than that and an exception will be throw - */ - private int threadsAllowedToBlockForConnectionMultiplier = MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier; + /** + * multiplier for connectionsPerHost for # of threads that can block if connectionsPerHost is 10, and + * threadsAllowedToBlockForConnectionMultiplier is 5, then 50 threads can block more than that and an exception will + * be throw + */ + private int threadsAllowedToBlockForConnectionMultiplier = MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier; - /** - * max wait time of a blocking thread for a connection - */ - private int maxWaitTime = MONGO_OPTIONS.maxWaitTime; + /** + * max wait time of a blocking thread for a connection + */ + private int maxWaitTime = MONGO_OPTIONS.maxWaitTime; - /** - * connect timeout in milliseconds. 0 is default and infinite - */ - private int connectTimeout = MONGO_OPTIONS.connectTimeout; + /** + * connect timeout in milliseconds. 0 is default and infinite + */ + private int connectTimeout = MONGO_OPTIONS.connectTimeout; - /** - * socket timeout. 0 is default and infinite - */ - private int socketTimeout = MONGO_OPTIONS.socketTimeout; + /** + * socket timeout. 0 is default and infinite + */ + private int socketTimeout = MONGO_OPTIONS.socketTimeout; - /** - * this controls whether or not on a connect, the system retries automatically - */ - private boolean autoConnectRetry = MONGO_OPTIONS.autoConnectRetry; + /** + * this controls whether or not on a connect, the system retries automatically + */ + private boolean autoConnectRetry = MONGO_OPTIONS.autoConnectRetry; + /** + * number of connections allowed per host will block if run out + */ + public void setConnectionsPerHost(int connectionsPerHost) { + this.connectionsPerHost = connectionsPerHost; + } - /** - * number of connections allowed per host - * will block if run out - */ - public void setConnectionsPerHost(int connectionsPerHost) { - this.connectionsPerHost = connectionsPerHost; - } + /** + * multiplier for connectionsPerHost for # of threads that can block if connectionsPerHost is 10, and + * threadsAllowedToBlockForConnectionMultiplier is 5, then 50 threads can block more than that and an exception will + * be throw + */ + public void setThreadsAllowedToBlockForConnectionMultiplier(int threadsAllowedToBlockForConnectionMultiplier) { + this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; + } - /** - * multiplier for connectionsPerHost for # of threads that can block - * if connectionsPerHost is 10, and threadsAllowedToBlockForConnectionMultiplier is 5, - * then 50 threads can block - * more than that and an exception will be throw - */ - public void setThreadsAllowedToBlockForConnectionMultiplier( - int threadsAllowedToBlockForConnectionMultiplier) { - this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; - } + /** + * max wait time of a blocking thread for a connection + */ + public void setMaxWaitTime(int maxWaitTime) { + this.maxWaitTime = maxWaitTime; + } - /** - * max wait time of a blocking thread for a connection - */ - public void setMaxWaitTime(int maxWaitTime) { - this.maxWaitTime = maxWaitTime; - } + /** + * connect timeout in milliseconds. 0 is default and infinite + */ + public void setConnectTimeout(int connectTimeout) { + this.connectTimeout = connectTimeout; + } - /** - * connect timeout in milliseconds. 0 is default and infinite - */ - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } + /** + * socket timeout. 0 is default and infinite + */ + public void setSocketTimeout(int socketTimeout) { + this.socketTimeout = socketTimeout; + } - /** - * socket timeout. 0 is default and infinite - */ - public void setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } + /** + * this controls whether or not on a connect, the system retries automatically + */ + public void setAutoConnectRetry(boolean autoConnectRetry) { + this.autoConnectRetry = autoConnectRetry; + } - /** - * this controls whether or not on a connect, the system retries automatically - */ - public void setAutoConnectRetry(boolean autoConnectRetry) { - this.autoConnectRetry = autoConnectRetry; - } + public void afterPropertiesSet() { + MONGO_OPTIONS.connectionsPerHost = connectionsPerHost; + MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; + MONGO_OPTIONS.maxWaitTime = maxWaitTime; + MONGO_OPTIONS.connectTimeout = connectTimeout; + MONGO_OPTIONS.socketTimeout = socketTimeout; + MONGO_OPTIONS.autoConnectRetry = autoConnectRetry; - public void afterPropertiesSet() { - MONGO_OPTIONS.connectionsPerHost = connectionsPerHost; - MONGO_OPTIONS.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; - MONGO_OPTIONS.maxWaitTime = maxWaitTime; - MONGO_OPTIONS.connectTimeout = connectTimeout; - MONGO_OPTIONS.socketTimeout = socketTimeout; - MONGO_OPTIONS.autoConnectRetry = autoConnectRetry; + } - } + public MongoOptions getObject() { + return MONGO_OPTIONS; + } - public MongoOptions getObject() { - return MONGO_OPTIONS; - } + public Class getObjectType() { + return MongoOptions.class; + } - public Class getObjectType() { - return MongoOptions.class; - } - - public boolean isSingleton() { - return true; - } + public boolean isSingleton() { + return true; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoPropertyDescriptors.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoPropertyDescriptors.java index 9f82ddd0d..029c99155 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoPropertyDescriptors.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoPropertyDescriptors.java @@ -29,217 +29,216 @@ import org.springframework.util.ReflectionUtils; /** * An iterable of {@link MongoPropertyDescriptor}s that allows dedicated access to the {@link MongoPropertyDescriptor} * that captures the id-property. - * + * * @author Oliver Gierke */ public class MongoPropertyDescriptors implements Iterable { - private final Collection descriptors; - private final MongoPropertyDescriptors.MongoPropertyDescriptor idDescriptor; + private final Collection descriptors; + private final MongoPropertyDescriptors.MongoPropertyDescriptor idDescriptor; - /** - * Creates the {@link MongoPropertyDescriptors} for the given type. - * - * @param type - */ - public MongoPropertyDescriptors(Class type) { + /** + * Creates the {@link MongoPropertyDescriptors} for the given type. + * + * @param type + */ + public MongoPropertyDescriptors(Class type) { - Assert.notNull(type); - Set descriptors = new HashSet(); - MongoPropertyDescriptors.MongoPropertyDescriptor idDesciptor = null; + Assert.notNull(type); + Set descriptors = new HashSet(); + MongoPropertyDescriptors.MongoPropertyDescriptor idDesciptor = null; - for (PropertyDescriptor candidates : BeanUtils.getPropertyDescriptors(type)) { - MongoPropertyDescriptor descriptor = new MongoPropertyDescriptors.MongoPropertyDescriptor(candidates, type); - descriptors.add(descriptor); - if (descriptor.isIdProperty()) { - idDesciptor = descriptor; - } - } + for (PropertyDescriptor candidates : BeanUtils.getPropertyDescriptors(type)) { + MongoPropertyDescriptor descriptor = new MongoPropertyDescriptors.MongoPropertyDescriptor(candidates, type); + descriptors.add(descriptor); + if (descriptor.isIdProperty()) { + idDesciptor = descriptor; + } + } - this.descriptors = Collections.unmodifiableSet(descriptors); - this.idDescriptor = idDesciptor; - } + this.descriptors = Collections.unmodifiableSet(descriptors); + this.idDescriptor = idDesciptor; + } - /** - * Returns the {@link MongoPropertyDescriptor} for the id property. - * - * @return the idDescriptor - */ - public MongoPropertyDescriptors.MongoPropertyDescriptor getIdDescriptor() { - return idDescriptor; - } + /** + * Returns the {@link MongoPropertyDescriptor} for the id property. + * + * @return the idDescriptor + */ + public MongoPropertyDescriptors.MongoPropertyDescriptor getIdDescriptor() { + return idDescriptor; + } - /* - * (non-Javadoc) - * - * @see java.lang.Iterable#iterator() - */ - public Iterator iterator() { - return descriptors.iterator(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Iterable#iterator() + */ + public Iterator iterator() { + return descriptors.iterator(); + } - /** - * Simple value object to have a more suitable abstraction for MongoDB specific property handling. - * - * @author Oliver Gierke - */ - public static class MongoPropertyDescriptor { + /** + * Simple value object to have a more suitable abstraction for MongoDB specific property handling. + * + * @author Oliver Gierke + */ + public static class MongoPropertyDescriptor { - public static Collection> SUPPORTED_ID_CLASSES; + public static Collection> SUPPORTED_ID_CLASSES; - static { - Set> classes = new HashSet>(); - classes.add(ObjectId.class); - classes.add(String.class); - classes.add(BigInteger.class); - SUPPORTED_ID_CLASSES = Collections.unmodifiableCollection(classes); - } + static { + Set> classes = new HashSet>(); + classes.add(ObjectId.class); + classes.add(String.class); + classes.add(BigInteger.class); + SUPPORTED_ID_CLASSES = Collections.unmodifiableCollection(classes); + } - private static final String ID_PROPERTY = "id"; - static final String ID_KEY = "_id"; + private static final String ID_PROPERTY = "id"; + static final String ID_KEY = "_id"; - private final PropertyDescriptor delegate; - private final Class owningType; + private final PropertyDescriptor delegate; + private final Class owningType; - /** - * Creates a new {@link MongoPropertyDescriptor} for the given {@link PropertyDescriptor}. - * - * @param descriptor - * @param owningType - */ - public MongoPropertyDescriptor(PropertyDescriptor descriptor, Class owningType) { - Assert.notNull(descriptor); - this.delegate = descriptor; - this.owningType = owningType; - } + /** + * Creates a new {@link MongoPropertyDescriptor} for the given {@link PropertyDescriptor}. + * + * @param descriptor + * @param owningType + */ + public MongoPropertyDescriptor(PropertyDescriptor descriptor, Class owningType) { + Assert.notNull(descriptor); + this.delegate = descriptor; + this.owningType = owningType; + } - /** - * Returns whether the property is the id-property. Will be identified by name for now ({@value #ID_PROPERTY}). - * - * @return - */ - public boolean isIdProperty() { - return ID_PROPERTY.equals(delegate.getName()) || ID_KEY.equals(delegate.getName()); - } + /** + * Returns whether the property is the id-property. Will be identified by name for now ({@value #ID_PROPERTY}). + * + * @return + */ + public boolean isIdProperty() { + return ID_PROPERTY.equals(delegate.getName()) || ID_KEY.equals(delegate.getName()); + } - /** - * Returns whether the property is of one of the supported id types. Currently we support {@link String}, - * {@link ObjectId} and {@link BigInteger}. - * - * @return - */ - public boolean isOfIdType() { - return SUPPORTED_ID_CLASSES.contains(delegate.getPropertyType()); - } + /** + * Returns whether the property is of one of the supported id types. Currently we support {@link String}, + * {@link ObjectId} and {@link BigInteger}. + * + * @return + */ + public boolean isOfIdType() { + return SUPPORTED_ID_CLASSES.contains(delegate.getPropertyType()); + } - /** - * Returns the key that shall be used for mapping. Will return {@value #ID_KEY} for the id property and the - * plain name for all other ones. - * - * @return - */ - public String getKeyToMap() { - return isIdProperty() ? ID_KEY : delegate.getName(); - } + /** + * Returns the key that shall be used for mapping. Will return {@value #ID_KEY} for the id property and the plain + * name for all other ones. + * + * @return + */ + public String getKeyToMap() { + return isIdProperty() ? ID_KEY : delegate.getName(); + } - /** - * Returns the name of the property. - * - * @return - */ - public String getName() { - return delegate.getName(); - } + /** + * Returns the name of the property. + * + * @return + */ + public String getName() { + return delegate.getName(); + } - /** - * Returns whether the underlying property is actually mappable. By default this will exclude the - * {@literal class} property and only include properties with a getter. - * - * @return - */ - public boolean isMappable() { - - boolean isNotClassAttribute = !delegate.getName().equals("class"); - boolean hasGetter = delegate.getReadMethod() != null; - boolean hasField = ReflectionUtils.findField(owningType, delegate.getName()) != null; - - return isNotClassAttribute && hasGetter && hasField; - } + /** + * Returns whether the underlying property is actually mappable. By default this will exclude the {@literal class} + * property and only include properties with a getter. + * + * @return + */ + public boolean isMappable() { - /** - * Returns the plain property type. - * - * @return - */ - public Class getPropertyType() { - return delegate.getPropertyType(); - } + boolean isNotClassAttribute = !delegate.getName().equals("class"); + boolean hasGetter = delegate.getReadMethod() != null; + boolean hasField = ReflectionUtils.findField(owningType, delegate.getName()) != null; - /** - * Returns the type type to be set. Will return the setter method's type and fall back to the getter method's - * return type in case no setter is available. Useful for further (generics) inspection. - * - * @return - */ - public Type getTypeToSet() { + return isNotClassAttribute && hasGetter && hasField; + } - Method method = delegate.getWriteMethod(); - return method == null ? delegate.getReadMethod().getGenericReturnType() - : method.getGenericParameterTypes()[0]; - } + /** + * Returns the plain property type. + * + * @return + */ + public Class getPropertyType() { + return delegate.getPropertyType(); + } - /** - * Returns whther we describe a {@link Map}. - * - * @return - */ - public boolean isMap() { - return Map.class.isAssignableFrom(getPropertyType()); - } + /** + * Returns the type type to be set. Will return the setter method's type and fall back to the getter method's return + * type in case no setter is available. Useful for further (generics) inspection. + * + * @return + */ + public Type getTypeToSet() { - /** - * Returns whether the descriptor is for a collection. - * - * @return - */ - public boolean isCollection() { - return Collection.class.isAssignableFrom(getPropertyType()); - } + Method method = delegate.getWriteMethod(); + return method == null ? delegate.getReadMethod().getGenericReturnType() : method.getGenericParameterTypes()[0]; + } - /** - * Returns whether the descriptor is for an {@link Enum}. - * - * @return - */ - public boolean isEnum() { - return Enum.class.isAssignableFrom(getPropertyType()); - } + /** + * Returns whther we describe a {@link Map}. + * + * @return + */ + public boolean isMap() { + return Map.class.isAssignableFrom(getPropertyType()); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } - if (obj == null || !getClass().equals(obj.getClass())) { - return false; - } - MongoPropertyDescriptor that = (MongoPropertyDescriptor) obj; - return that.delegate.equals(this.delegate); - } + /** + * Returns whether the descriptor is for a collection. + * + * @return + */ + public boolean isCollection() { + return Collection.class.isAssignableFrom(getPropertyType()); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return delegate.hashCode(); - } - } + /** + * Returns whether the descriptor is for an {@link Enum}. + * + * @return + */ + public boolean isEnum() { + return Enum.class.isAssignableFrom(getPropertyType()); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + if (obj == null || !getClass().equals(obj.getClass())) { + return false; + } + MongoPropertyDescriptor that = (MongoPropertyDescriptor) obj; + return that.delegate.equals(this.delegate); + } + + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return delegate.hashCode(); + } + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoReader.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoReader.java index 5af012be5..1e5c61fb2 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoReader.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoReader.java @@ -19,22 +19,25 @@ import com.mongodb.DBObject; /** * A MongoWriter is responsible for converting a native MongoDB DBObject to an object of type T. - * - * @param the type of the object to convert from a DBObject + * + * @param + * the type of the object to convert from a DBObject * @author Mark Pollack * @author Thomas Risberg * @author Oliver Gierke */ public interface MongoReader { - /** - * Ready from the native MongoDB DBObject representation to an instance of the class T. The given type has to be the - * starting point for marshalling the {@link DBObject} into it. So in case there's no real valid data inside - * {@link DBObject} for the given type, just return an empty instance of the given type. - * - * @param clazz the type of the return value - * @param dbo theDBObject - * @return the converted object - */ - S read(Class clazz, DBObject dbo); + /** + * Ready from the native MongoDB DBObject representation to an instance of the class T. The given type has to be the + * starting point for marshalling the {@link DBObject} into it. So in case there's no real valid data inside + * {@link DBObject} for the given type, just return an empty instance of the given type. + * + * @param clazz + * the type of the return value + * @param dbo + * theDBObject + * @return the converted object + */ + S read(Class clazz, DBObject dbo); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoSynchronization.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoSynchronization.java index 5111b2729..2fe6373e2 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoSynchronization.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoSynchronization.java @@ -5,8 +5,7 @@ import org.springframework.transaction.support.ResourceHolderSynchronization; class MongoSynchronization extends ResourceHolderSynchronization { - public MongoSynchronization(ResourceHolder resourceHolder, - Object resourceKey) { - super(resourceHolder, resourceKey); - } + public MongoSynchronization(ResourceHolder resourceHolder, Object resourceKey) { + super(resourceHolder, resourceKey); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java index 579c96a59..f2b79d2aa 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoTemplate.java @@ -73,7 +73,7 @@ import org.springframework.util.Assert; /** * Primary implementation of {@link MongoOperations}. - * + * * @author Thomas Risberg * @author Graeme Rocher * @author Mark Pollack @@ -110,7 +110,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Constructor used for a basic template configuration - * + * * @param mongo * @param databaseName */ @@ -119,8 +119,9 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher } /** - * Constructor used for a template configuration with a custom {@link org.springframework.data.document.mongodb.convert.MongoConverter} - * + * Constructor used for a template configuration with a custom + * {@link org.springframework.data.document.mongodb.convert.MongoConverter} + * * @param mongo * @param databaseName * @param mongoConverter @@ -130,16 +131,17 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher } /** - * Constructor used for a template configuration with a custom {@link MongoConverter} - * and with a specific {@link com.mongodb.WriteConcern} to be used for all database write operations - * + * Constructor used for a template configuration with a custom {@link MongoConverter} and with a specific + * {@link com.mongodb.WriteConcern} to be used for all database write operations + * * @param mongo * @param databaseName * @param mongoConverter * @param writeConcern * @param writeResultChecking */ - MongoTemplate(Mongo mongo, String databaseName, MongoConverter mongoConverter, WriteConcern writeConcern, WriteResultChecking writeResultChecking) { + MongoTemplate(Mongo mongo, String databaseName, MongoConverter mongoConverter, WriteConcern writeConcern, + WriteResultChecking writeResultChecking) { Assert.notNull(mongo); Assert.notNull(databaseName); @@ -174,8 +176,9 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Sets the username to use to connect to the Mongo database - * - * @param username The username to use + * + * @param username + * The username to use */ public void setUsername(String username) { this.username = username; @@ -183,8 +186,9 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Sets the password to use to authenticate with the Mongo database. - * - * @param password The password to use + * + * @param password + * The password to use */ public void setPassword(String password) { @@ -193,7 +197,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Sets the database name to be used. - * + * * @param databaseName */ public void setDatabaseName(String databaseName) { @@ -203,7 +207,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Returns the default {@link org.springframework.data.document.mongodb.convert.MongoConverter}. - * + * * @return */ public MongoConverter getConverter() { @@ -238,10 +242,9 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher String error = result.getErrorMessage(); if (error != null) { // TODO: allow configuration of logging level / throw - // throw new InvalidDataAccessApiUsageException("Command execution of " + - // command.toString() + " failed: " + error); - LOGGER.warn("Command execution of " + - command.toString() + " failed: " + error); + // throw new InvalidDataAccessApiUsageException("Command execution of " + + // command.toString() + " failed: " + error); + LOGGER.warn("Command execution of " + command.toString() + " failed: " + error); } return result; } @@ -285,18 +288,23 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Central callback executing method to do queries against the datastore that requires reading a single object from a - * collection of objects. It will take the following steps

  1. Execute the given {@link ConnectionCallback} for a - * {@link DBObject}.
  2. Apply the given - * {@link DbObjectCallback} to each of the {@link DBObject}s to obtain the result.
    1. - * + * collection of objects. It will take the following steps + *
        + *
      1. Execute the given {@link ConnectionCallback} for a {@link DBObject}.
      2. + *
      3. Apply the given {@link DbObjectCallback} to each of the {@link DBObject}s to obtain the result.
      4. + *
          + * * @param - * @param collectionCallback the callback to retrieve the {@link DBObject} with - * @param objectCallback the {@link DbObjectCallback} to transform {@link DBObject}s into the actual domain type - * @param collectionName the collection to be queried + * @param collectionCallback + * the callback to retrieve the {@link DBObject} with + * @param objectCallback + * the {@link DbObjectCallback} to transform {@link DBObject}s into the actual domain type + * @param collectionName + * the collection to be queried * @return */ - private T execute(CollectionCallback collectionCallback, - DbObjectCallback objectCallback, String collectionName) { + private T execute(CollectionCallback collectionCallback, DbObjectCallback objectCallback, + String collectionName) { try { T result = objectCallback.doWith(collectionCallback.doInCollection(getCollection(collectionName))); @@ -308,20 +316,28 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Central callback executing method to do queries against the datastore that requires reading a collection of - * objects. It will take the following steps
          1. Execute the given {@link ConnectionCallback} for a - * {@link DBCursor}.
          2. Prepare that {@link DBCursor} with the given {@link CursorPreparer} (will be skipped - * if {@link CursorPreparer} is {@literal null}
          3. Iterate over the {@link DBCursor} and applies the given - * {@link DbObjectCallback} to each of the {@link DBObject}s collecting the actual result {@link List}.
            1. - * + * objects. It will take the following steps + *
                + *
              1. Execute the given {@link ConnectionCallback} for a {@link DBCursor}.
              2. + *
              3. Prepare that {@link DBCursor} with the given {@link CursorPreparer} (will be skipped if {@link CursorPreparer} + * is {@literal null}
              4. + *
              5. Iterate over the {@link DBCursor} and applies the given {@link DbObjectCallback} to each of the + * {@link DBObject}s collecting the actual result {@link List}.
              6. + *
                  + * * @param - * @param collectionCallback the callback to retrieve the {@link DBCursor} with - * @param preparer the {@link CursorPreparer} to potentially modify the {@link DBCursor} before ireating over it - * @param objectCallback the {@link DbObjectCallback} to transform {@link DBObject}s into the actual domain type - * @param collectionName the collection to be queried + * @param collectionCallback + * the callback to retrieve the {@link DBCursor} with + * @param preparer + * the {@link CursorPreparer} to potentially modify the {@link DBCursor} before ireating over it + * @param objectCallback + * the {@link DbObjectCallback} to transform {@link DBObject}s into the actual domain type + * @param collectionName + * the collection to be queried * @return */ private List executeEach(CollectionCallback collectionCallback, CursorPreparer preparer, - DbObjectCallback objectCallback, String collectionName) { + DbObjectCallback objectCallback, String collectionName) { try { DBCursor cursor = collectionCallback.doInCollection(getCollection(collectionName)); @@ -384,7 +400,6 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher }); } - /* (non-Javadoc) * @see org.springframework.data.document.mongodb.MongoOperations#collectionExists(java.lang.String) */ @@ -435,8 +450,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher return findOne(determineCollectionName(targetClass), query, targetClass); } - public T findOne(String collectionName, Query query, - Class targetClass) { + public T findOne(String collectionName, Query query, Class targetClass) { return doFindOne(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass); } @@ -473,8 +487,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, cursorPreparer); } - public List find(String collectionName, Query query, - Class targetClass, CursorPreparer preparer) { + public List find(String collectionName, Query query, Class targetClass, CursorPreparer preparer) { return doFind(collectionName, query.getQueryObject(), query.getFieldsObject(), targetClass, preparer); } @@ -485,9 +498,9 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher return findAndRemove(determineCollectionName(targetClass), query, targetClass); } - public T findAndRemove(String collectionName, Query query, - Class targetClass) { - return doFindAndRemove(collectionName, query.getQueryObject(), query.getFieldsObject(), query.getSortObject(), targetClass); + public T findAndRemove(String collectionName, Query query, Class targetClass) { + return doFindAndRemove(collectionName, query.getQueryObject(), query.getFieldsObject(), query.getSortObject(), + targetClass); } /* (non-Javadoc) @@ -538,8 +551,8 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher MongoPersistentEntity entity = mappingContext.getPersistentEntity(o.getClass()); if (entity == null) { - throw new InvalidDataAccessApiUsageException("No Persitent Entity information found for the class " + - o.getClass().getName()); + throw new InvalidDataAccessApiUsageException("No Persitent Entity information found for the class " + + o.getClass().getName()); } String collection = entity.getCollection(); @@ -608,15 +621,14 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher maybeEmitEvent(new AfterSaveEvent(objectToSave, dbDoc)); } - protected Object insertDBObject(String collectionName, final DBObject dbDoc) { // DATADOC-95: This will prevent null objects from being saved. - //if (dbDoc.keySet().isEmpty()) { - //return null; - //} + // if (dbDoc.keySet().isEmpty()) { + // return null; + // } - //TODO: Need to move this to more central place + // TODO: Need to move this to more central place if (dbDoc.containsField("_id")) { if (dbDoc.get("_id") instanceof String) { ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id")); @@ -646,7 +658,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher return Collections.emptyList(); } - //TODO: Need to move this to more central place + // TODO: Need to move this to more central place for (DBObject dbDoc : dbDocList) { if (dbDoc.containsField("_id")) { if (dbDoc.get("_id") instanceof String) { @@ -690,7 +702,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher return null; } - //TODO: Need to move this to more central place + // TODO: Need to move this to more central place if (dbDoc.containsField("_id")) { if (dbDoc.get("_id") instanceof String) { ObjectId oid = convertIdValue(this.mongoConverter, dbDoc.get("_id")); @@ -742,12 +754,8 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher return doUpdate(collectionName, query, update, null, false, true); } - protected WriteResult doUpdate(final String collectionName, - final Query query, - final Update update, - final Class entityClass, - final boolean upsert, - final boolean multi) { + protected WriteResult doUpdate(final String collectionName, final Query query, final Update update, + final Class entityClass, final boolean upsert, final boolean multi) { return execute(collectionName, new CollectionCallback() { public WriteResult doInCollection(DBCollection collection) throws MongoException, DataAccessException { @@ -773,7 +781,8 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher } if (LOGGER.isDebugEnabled()) { - LOGGER.debug("calling update using query: " + queryObj + " and update: " + updateObj + " in collection: " + collectionName); + LOGGER.debug("calling update using query: " + queryObj + " and update: " + updateObj + " in collection: " + + collectionName); } WriteResult wr; @@ -841,7 +850,6 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher remove(collectionName, query, null); } - /* (non-Javadoc) * @see org.springframework.data.document.mongodb.MongoOperations#getCollection(java.lang.Class) */ @@ -875,7 +883,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Create the specified collection using the provided options - * + * * @param collectionName * @param collectionOptions * @return the collection that was created @@ -894,11 +902,15 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher * Map the results of an ad-hoc query on the default MongoDB collection to an object using the template's converter *

                  * The query document is specified as a standard DBObject and so is the fields specification. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query document that specifies the criteria used to find a record - * @param fields the document that specifies the fields to be returned - * @param targetClass the parameterized type of the returned list. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query document that specifies the criteria used to find a record + * @param fields + * the document that specifies the fields to be returned + * @param targetClass + * the parameterized type of the returned list. * @return the List of converted objects. */ protected T doFindOne(String collectionName, DBObject query, DBObject fields, Class targetClass) { @@ -906,63 +918,70 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher MongoPersistentEntity entity = mappingContext.getPersistentEntity(targetClass); DBObject mappedQuery = mapper.getMappedObject(query, entity); - return execute(new FindOneCallback(mappedQuery, fields), - new ReadDbObjectCallback(readerToUse, targetClass), + return execute(new FindOneCallback(mappedQuery, fields), new ReadDbObjectCallback(readerToUse, targetClass), collectionName); } /** * Map the results of an ad-hoc query on the default MongoDB collection to a List of the specified type. *

                  - * The object is converted from the MongoDB native representation using an instance of - * {@see MongoConverter}. Unless configured otherwise, an - * instance of SimpleMongoConverter will be used. + * The object is converted from the MongoDB native representation using an instance of {@see MongoConverter}. Unless + * configured otherwise, an instance of SimpleMongoConverter will be used. *

                  * The query document is specified as a standard DBObject and so is the fields specification. *

                  * Can be overridden by subclasses. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query document that specifies the criteria used to find a record - * @param fields the document that specifies the fields to be returned - * @param targetClass the parameterized type of the returned list. - * @param preparer allows for customization of the DBCursor used when iterating over the result set, - * (apply limits, skips and so on). + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query document that specifies the criteria used to find a record + * @param fields + * the document that specifies the fields to be returned + * @param targetClass + * the parameterized type of the returned list. + * @param preparer + * allows for customization of the DBCursor used when iterating over the result set, (apply limits, skips and + * so on). * @return the List of converted objects. */ - protected List doFind(String collectionName, DBObject query, DBObject fields, Class targetClass, CursorPreparer preparer) { + protected List doFind(String collectionName, DBObject query, DBObject fields, Class targetClass, + CursorPreparer preparer) { MongoPersistentEntity entity = mappingContext.getPersistentEntity(targetClass); if (LOGGER.isDebugEnabled()) { - LOGGER.debug("find using query: " + query + " fields: " + fields + " for class: " + targetClass + " in collection: " + collectionName); + LOGGER.debug("find using query: " + query + " fields: " + fields + " for class: " + targetClass + + " in collection: " + collectionName); } - return executeEach(new FindCallback(mapper.getMappedObject(query, entity), fields), - preparer, - new ReadDbObjectCallback(mongoConverter, targetClass), - collectionName); + return executeEach(new FindCallback(mapper.getMappedObject(query, entity), fields), preparer, + new ReadDbObjectCallback(mongoConverter, targetClass), collectionName); } /** * Map the results of an ad-hoc query on the default MongoDB collection to a List using the template's converter. *

                  * The query document is specified as a standard DBObject and so is the fields specification. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query document that specifies the criteria used to find a record - * @param fields the document that specifies the fields to be returned - * @param targetClass the parameterized type of the returned list. - * @param reader the MongoReader to convert from DBObject to an object. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query document that specifies the criteria used to find a record + * @param fields + * the document that specifies the fields to be returned + * @param targetClass + * the parameterized type of the returned list. + * @param reader + * the MongoReader to convert from DBObject to an object. * @return the List of converted objects. */ protected List doFind(String collectionName, DBObject query, DBObject fields, Class targetClass) { if (LOGGER.isDebugEnabled()) { - LOGGER.debug("find using query: " + query + " fields: " + fields + " for class: " + targetClass + " in collection: " + collectionName); + LOGGER.debug("find using query: " + query + " fields: " + fields + " for class: " + targetClass + + " in collection: " + collectionName); } MongoReader readerToUse = this.mongoConverter; MongoPersistentEntity entity = mappingContext.getPersistentEntity(targetClass); - return executeEach(new FindCallback(mapper.getMappedObject(query, entity), fields), - null, - new ReadDbObjectCallback(readerToUse, targetClass), - collectionName); + return executeEach(new FindCallback(mapper.getMappedObject(query, entity), fields), null, + new ReadDbObjectCallback(readerToUse, targetClass), collectionName); } protected DBObject convertToDbObject(CollectionOptions collectionOptions) { @@ -986,22 +1005,27 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher * The first document that matches the query is returned and also removed from the collection in the database. *

                  * The query document is specified as a standard DBObject and so is the fields specification. - * - * @param collectionName name of the collection to retrieve the objects from - * @param query the query document that specifies the criteria used to find a record - * @param targetClass the parameterized type of the returned list. - * @param reader the MongoReader to convert from DBObject to an object. + * + * @param collectionName + * name of the collection to retrieve the objects from + * @param query + * the query document that specifies the criteria used to find a record + * @param targetClass + * the parameterized type of the returned list. + * @param reader + * the MongoReader to convert from DBObject to an object. * @return the List of converted objects. */ - protected T doFindAndRemove(String collectionName, DBObject query, DBObject fields, DBObject sort, Class targetClass) { + protected T doFindAndRemove(String collectionName, DBObject query, DBObject fields, DBObject sort, + Class targetClass) { MongoReader readerToUse = this.mongoConverter; if (LOGGER.isDebugEnabled()) { - LOGGER.debug("findAndRemove using query: " + query + " fields: " + fields + " sort: " + sort + " for class: " + targetClass + " in collection: " + collectionName); + LOGGER.debug("findAndRemove using query: " + query + " fields: " + fields + " sort: " + sort + " for class: " + + targetClass + " in collection: " + collectionName); } MongoPersistentEntity entity = mappingContext.getPersistentEntity(targetClass); return execute(new FindAndRemoveCallback(mapper.getMappedObject(query, entity), fields, sort), - new ReadDbObjectCallback(readerToUse, targetClass), - collectionName); + new ReadDbObjectCallback(readerToUse, targetClass), collectionName); } protected Object getIdValue(Object object) { @@ -1024,7 +1048,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Populates the id property of the saved object, if it's not set already. - * + * * @param savedObject * @param id */ @@ -1051,10 +1075,10 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher } /** - * Substitutes the id key if it is found in he query. Any 'id' keys will be replaced with '_id' and the value converted - * to an ObjectId if possible. This conversion should match the way that the id fields are converted during read - * operations. - * + * Substitutes the id key if it is found in he query. Any 'id' keys will be replaced with '_id' and the value + * converted to an ObjectId if possible. This conversion should match the way that the id fields are converted during + * read operations. + * * @param query * @param targetClass * @param reader @@ -1087,7 +1111,8 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher // no property descriptor for this key - try the other try { String theOtherIdKey = "id".equals(idKey) ? "_id" : "id"; - MongoPropertyDescriptor mpd2 = new MongoPropertyDescriptor(new PropertyDescriptor(theOtherIdKey, targetClass), targetClass); + MongoPropertyDescriptor mpd2 = new MongoPropertyDescriptor(new PropertyDescriptor(theOtherIdKey, targetClass), + targetClass); descriptor = mpd2; } catch (IntrospectionException e2) { // no property descriptor for this key either - bail @@ -1109,8 +1134,8 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher } } if (ids.size() > 0 && ids.size() != count) { - throw new InvalidDataAccessApiUsageException("Inconsistent set of id values provided " + - Arrays.asList((Object[]) dbo.get("$in"))); + throw new InvalidDataAccessApiUsageException("Inconsistent set of id values provided " + + Arrays.asList((Object[]) dbo.get("$in"))); } if (ids.size() > 0) { dbo.removeField("$in"); @@ -1162,12 +1187,14 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher private String determineCollectionName(Class clazz) { if (clazz == null) { - throw new InvalidDataAccessApiUsageException("No class parameter provided, entity collection can't be determined for " + clazz); + throw new InvalidDataAccessApiUsageException( + "No class parameter provided, entity collection can't be determined for " + clazz); } MongoPersistentEntity entity = mappingContext.getPersistentEntity(clazz); if (entity == null) { - throw new InvalidDataAccessApiUsageException("No Persitent Entity information found for the class " + clazz.getName()); + throw new InvalidDataAccessApiUsageException("No Persitent Entity information found for the class " + + clazz.getName()); } return entity.getCollection(); } @@ -1175,8 +1202,8 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Checks and handles any errors. *

                  - * TODO: current implementation logs errors - will be configurable to log warning, errors or - * throw exception in later versions + * TODO: current implementation logs errors - will be configurable to log warning, errors or throw exception in later + * versions */ private void handleAnyWriteResultErrors(WriteResult wr, DBObject query, String operation) { if (WriteResultChecking.NONE == this.writeResultChecking) { @@ -1185,16 +1212,16 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher String error = wr.getError(); int n = wr.getN(); if (error != null) { - String message = "Execution of '" + operation + - (query == null ? "" : "' using '" + query.toString() + "' query") + " failed: " + error; + String message = "Execution of '" + operation + (query == null ? "" : "' using '" + query.toString() + "' query") + + " failed: " + error; if (WriteResultChecking.EXCEPTION == this.writeResultChecking) { throw new DataIntegrityViolationException(message); } else { LOGGER.error(message); } } else if (n == 0) { - String message = "Execution of '" + operation + - (query == null ? "" : "' using '" + query.toString() + "' query") + " did not succeed: 0 documents updated"; + String message = "Execution of '" + operation + (query == null ? "" : "' using '" + query.toString() + "' query") + + " did not succeed: 0 documents updated"; if (WriteResultChecking.EXCEPTION == this.writeResultChecking) { throw new DataIntegrityViolationException(message); } else { @@ -1207,7 +1234,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Tries to convert the given {@link RuntimeException} into a {@link DataAccessException} but returns the original * exception if the conversation failed. Thus allows safe rethrowing of the return value. - * + * * @param ex * @return */ @@ -1221,11 +1248,10 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher converter.setDefaultDatabase(databaseName); } - /** * Simple {@link CollectionCallback} that takes a query {@link DBObject} plus an optional fields specification * {@link DBObject} and executes that against the {@link DBCollection}. - * + * * @author Oliver Gierke * @author Thomas Risberg */ @@ -1248,7 +1274,8 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher return collection.findOne(query); } else { if (LOGGER.isDebugEnabled()) { - LOGGER.debug("findOne using query: " + query + " fields: " + fields + " in db.collection: " + collection.getFullName()); + LOGGER.debug("findOne using query: " + query + " fields: " + fields + " in db.collection: " + + collection.getFullName()); } return collection.findOne(query, fields); } @@ -1258,7 +1285,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Simple {@link CollectionCallback} that takes a query {@link DBObject} plus an optional fields specification * {@link DBObject} and executes that against the {@link DBCollection}. - * + * * @author Oliver Gierke * @author Thomas Risberg */ @@ -1289,7 +1316,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Simple {@link CollectionCallback} that takes a query {@link DBObject} plus an optional fields specification * {@link DBObject} and executes that against the {@link DBCollection}. - * + * * @author Thomas Risberg */ private static class FindAndRemoveCallback implements CollectionCallback { @@ -1313,7 +1340,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Simple internal callback to allow operations on a {@link DBObject}. - * + * * @author Oliver Gierke */ @@ -1325,7 +1352,7 @@ public class MongoTemplate implements MongoOperations, ApplicationEventPublisher /** * Simple {@link DbObjectCallback} that will transform {@link DBObject} into the given target type using the given * {@link MongoReader}. - * + * * @author Oliver Gierke */ private class ReadDbObjectCallback implements DbObjectCallback { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoWriter.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoWriter.java index 2949ffa39..90def42f3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoWriter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/MongoWriter.java @@ -19,19 +19,22 @@ import com.mongodb.DBObject; /** * A MongoWriter is responsible for converting an object of type T to the native MongoDB representation DBObject. - * - * @param the type of the object to convert to a DBObject + * + * @param + * the type of the object to convert to a DBObject * @author Mark Pollack * @author Thomas Risberg */ public interface MongoWriter { - /** - * Write the given object of type T to the native MongoDB object representation DBObject. - * - * @param t The object to convert to a DBObject - * @param dbo The DBObject to use for writing. - */ - void write(T t, DBObject dbo); + /** + * Write the given object of type T to the native MongoDB object representation DBObject. + * + * @param t + * The object to convert to a DBObject + * @param dbo + * The DBObject to use for writing. + */ + void write(T t, DBObject dbo); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/WriteResultChecking.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/WriteResultChecking.java index 2a577d174..d2bb144f7 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/WriteResultChecking.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/WriteResultChecking.java @@ -1,5 +1,5 @@ package org.springframework.data.document.mongodb; public enum WriteResultChecking { - NONE, LOG, EXCEPTION + NONE, LOG, EXCEPTION } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/AbstractMongoConfiguration.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/AbstractMongoConfiguration.java index 4307c6f6b..60c1255dc 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/AbstractMongoConfiguration.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/AbstractMongoConfiguration.java @@ -38,61 +38,63 @@ import com.mongodb.Mongo; @Configuration public abstract class AbstractMongoConfiguration { + @Bean + public abstract Mongo mongo() throws Exception; - @Bean - public abstract Mongo mongo() throws Exception; - - @Bean - public abstract MongoTemplate mongoTemplate() throws Exception; - - public String getMappingBasePackage() { - return ""; - } - - - @Bean - public MongoMappingContext mongoMappingContext() throws ClassNotFoundException, LinkageError { - MongoMappingContext mappingContext = new MongoMappingContext(); - String basePackage = getMappingBasePackage(); - if (StringUtils.hasText(basePackage)) { - ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(false); - componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class)); - componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class)); - - Set> initialEntitySet = new HashSet>(); - for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) { - initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(), mappingContext.getClass().getClassLoader())); - } - mappingContext.setInitialEntitySet(initialEntitySet); - } - return mappingContext; - } - - @Bean - public MappingMongoConverter mappingMongoConverter() throws Exception { - MappingMongoConverter converter = new MappingMongoConverter(mongoMappingContext()); - converter.setMongo(mongo()); - afterMappingMongoConverterCreation(converter); - return converter; - } - - /** - * Hook that allows post-processing after the MappingMongoConverter has been - * successfully created. - * @param converter - */ - protected void afterMappingMongoConverterCreation(MappingMongoConverter converter) { - } + @Bean + public abstract MongoTemplate mongoTemplate() throws Exception; - @Bean - public MappingContextAwareBeanPostProcessor mappingContextAwareBeanPostProcessor() { - MappingContextAwareBeanPostProcessor bpp = new MappingContextAwareBeanPostProcessor(); - bpp.setMappingContextBeanName("mongoMappingContext"); - return bpp; - } - - @Bean MongoPersistentEntityIndexCreator mongoPersistentEntityIndexCreator() throws Exception { - MongoPersistentEntityIndexCreator indexCreator = new MongoPersistentEntityIndexCreator(mongoMappingContext(), mongoTemplate() ); - return indexCreator; - } + public String getMappingBasePackage() { + return ""; + } + + @Bean + public MongoMappingContext mongoMappingContext() throws ClassNotFoundException, LinkageError { + MongoMappingContext mappingContext = new MongoMappingContext(); + String basePackage = getMappingBasePackage(); + if (StringUtils.hasText(basePackage)) { + ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( + false); + componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class)); + componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class)); + + Set> initialEntitySet = new HashSet>(); + for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) { + initialEntitySet.add(ClassUtils.forName(candidate.getBeanClassName(), mappingContext.getClass() + .getClassLoader())); + } + mappingContext.setInitialEntitySet(initialEntitySet); + } + return mappingContext; + } + + @Bean + public MappingMongoConverter mappingMongoConverter() throws Exception { + MappingMongoConverter converter = new MappingMongoConverter(mongoMappingContext()); + converter.setMongo(mongo()); + afterMappingMongoConverterCreation(converter); + return converter; + } + + /** + * Hook that allows post-processing after the MappingMongoConverter has been successfully created. + * + * @param converter + */ + protected void afterMappingMongoConverterCreation(MappingMongoConverter converter) { + } + + @Bean + public MappingContextAwareBeanPostProcessor mappingContextAwareBeanPostProcessor() { + MappingContextAwareBeanPostProcessor bpp = new MappingContextAwareBeanPostProcessor(); + bpp.setMappingContextBeanName("mongoMappingContext"); + return bpp; + } + + @Bean + MongoPersistentEntityIndexCreator mongoPersistentEntityIndexCreator() throws Exception { + MongoPersistentEntityIndexCreator indexCreator = new MongoPersistentEntityIndexCreator(mongoMappingContext(), + mongoTemplate()); + return indexCreator; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MappingMongoConverterParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MappingMongoConverterParser.java index 527ac5927..69c9a46eb 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MappingMongoConverterParser.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MappingMongoConverterParser.java @@ -63,7 +63,8 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser { private static final String BASE_PACKAGE = "base-package"; @Override - protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) + throws BeanDefinitionStoreException { String id = super.resolveId(element, definition, parserContext); return StringUtils.hasText(id) ? id : "mappingConverter"; } @@ -74,7 +75,8 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser { String ctxRef = element.getAttribute("mapping-context-ref"); if (!StringUtils.hasText(ctxRef)) { - BeanDefinitionBuilder mappingContextBuilder = BeanDefinitionBuilder.genericBeanDefinition(MongoMappingContext.class); + BeanDefinitionBuilder mappingContextBuilder = BeanDefinitionBuilder + .genericBeanDefinition(MongoMappingContext.class); Set classesToAdd = getInititalEntityClasses(element, mappingContextBuilder); if (classesToAdd != null) { @@ -88,7 +90,8 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser { try { registry.getBeanDefinition(POST_PROCESSOR); } catch (NoSuchBeanDefinitionException ignored) { - BeanDefinitionBuilder postProcBuilder = BeanDefinitionBuilder.genericBeanDefinition(MappingContextAwareBeanPostProcessor.class); + BeanDefinitionBuilder postProcBuilder = BeanDefinitionBuilder + .genericBeanDefinition(MappingContextAwareBeanPostProcessor.class); postProcBuilder.addPropertyValue("mappingContextBeanName", ctxRef); registry.registerBeanDefinition(POST_PROCESSOR, postProcBuilder.getBeanDefinition()); } @@ -104,9 +107,11 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser { registry.getBeanDefinition(INDEX_HELPER); } catch (NoSuchBeanDefinitionException ignored) { String templateRef = element.getAttribute("mongo-template-ref"); - BeanDefinitionBuilder indexHelperBuilder = BeanDefinitionBuilder.genericBeanDefinition(MongoPersistentEntityIndexCreator.class); + BeanDefinitionBuilder indexHelperBuilder = BeanDefinitionBuilder + .genericBeanDefinition(MongoPersistentEntityIndexCreator.class); indexHelperBuilder.addConstructorArgValue(new RuntimeBeanReference(ctxRef)); - indexHelperBuilder.addConstructorArgValue(new RuntimeBeanReference(StringUtils.hasText(templateRef) ? templateRef : TEMPLATE)); + indexHelperBuilder.addConstructorArgValue(new RuntimeBeanReference(StringUtils.hasText(templateRef) ? templateRef + : TEMPLATE)); registry.registerBeanDefinition(INDEX_HELPER, indexHelperBuilder.getBeanDefinition()); } @@ -126,7 +131,6 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser { return converterBuilder.getBeanDefinition(); } - public Set getInititalEntityClasses(Element element, BeanDefinitionBuilder builder) { String basePackage = element.getAttribute(BASE_PACKAGE); @@ -135,7 +139,8 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser { return null; } - ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(false); + ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( + false); componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class)); componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class)); @@ -148,8 +153,8 @@ public class MappingMongoConverterParser extends AbstractBeanDefinitionParser { } public BeanMetadataElement parseConverter(Element element, ParserContext parserContext) { - - String converterRef= element.getAttribute("ref"); + + String converterRef = element.getAttribute("ref"); if (StringUtils.hasText(converterRef)) { return new RuntimeBeanReference(converterRef); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoJmxParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoJmxParser.java index 5ffa9bbf9..c3bf6fbd6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoJmxParser.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoJmxParser.java @@ -28,42 +28,42 @@ import org.w3c.dom.Element; public class MongoJmxParser implements BeanDefinitionParser { - public BeanDefinition parse(Element element, ParserContext parserContext) { - String name = element.getAttribute("mongo-ref"); - if (!StringUtils.hasText(name)) { - name = "mongo"; - } - registerJmxComponents(name, element, parserContext); - return null; - } + public BeanDefinition parse(Element element, ParserContext parserContext) { + String name = element.getAttribute("mongo-ref"); + if (!StringUtils.hasText(name)) { + name = "mongo"; + } + registerJmxComponents(name, element, parserContext); + return null; + } - protected void registerJmxComponents(String mongoRefName, Element element, ParserContext parserContext) { - Object eleSource = parserContext.extractSource(element); + protected void registerJmxComponents(String mongoRefName, Element element, ParserContext parserContext) { + Object eleSource = parserContext.extractSource(element); - CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource); + CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), eleSource); - createBeanDefEntry(AssertMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(BackgroundFlushingMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(BtreeIndexCounters.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(ConnectionMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(GlobalLockMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(MemoryMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(OperationCounters.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(ServerInfo.class, compositeDef, mongoRefName, eleSource, parserContext); - createBeanDefEntry(MongoAdmin.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(AssertMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(BackgroundFlushingMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(BtreeIndexCounters.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(ConnectionMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(GlobalLockMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(MemoryMetrics.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(OperationCounters.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(ServerInfo.class, compositeDef, mongoRefName, eleSource, parserContext); + createBeanDefEntry(MongoAdmin.class, compositeDef, mongoRefName, eleSource, parserContext); + parserContext.registerComponent(compositeDef); - parserContext.registerComponent(compositeDef); + } - } - - protected void createBeanDefEntry(Class clazz, CompositeComponentDefinition compositeDef, String mongoRefName, Object eleSource, ParserContext parserContext) { - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz); - builder.getRawBeanDefinition().setSource(eleSource); - builder.addConstructorArgReference(mongoRefName); - BeanDefinition assertDef = builder.getBeanDefinition(); - String assertName = parserContext.getReaderContext().registerWithGeneratedName(assertDef); - compositeDef.addNestedComponent(new BeanComponentDefinition(assertDef, assertName)); - } + protected void createBeanDefEntry(Class clazz, CompositeComponentDefinition compositeDef, String mongoRefName, + Object eleSource, ParserContext parserContext) { + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(clazz); + builder.getRawBeanDefinition().setSource(eleSource); + builder.addConstructorArgReference(mongoRefName); + BeanDefinition assertDef = builder.getBeanDefinition(); + String assertName = parserContext.getReaderContext().registerWithGeneratedName(assertDef); + compositeDef.addNestedComponent(new BeanComponentDefinition(assertDef, assertName)); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoParser.java index 547731007..4d029d6e1 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoParser.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoParser.java @@ -28,67 +28,68 @@ import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; /** - * Parser for <mongo;gt; definitions. If no name - * + * Parser for <mongo;gt; definitions. If no name + * * @author Mark Pollack */ public class MongoParser extends AbstractSingleBeanDefinitionParser { - protected Class getBeanClass(Element element) { - return MongoFactoryBean.class; - } + protected Class getBeanClass(Element element) { + return MongoFactoryBean.class; + } - @Override - protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { - super.doParse(element, builder); + @Override + protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { + super.doParse(element, builder); - setPropertyValue(element, builder, "port", "port"); - setPropertyValue(element, builder, "host", "host"); + setPropertyValue(element, builder, "port", "port"); + setPropertyValue(element, builder, "host", "host"); - parseOptions(parserContext, element, builder); + parseOptions(parserContext, element, builder); - } + } - /** - * Parses the options sub-element. Populates the given attribute factory with the proper attributes. - * - * @param element - * @param attrBuilder - * @return true if parsing actually occured, false otherwise - */ - private boolean parseOptions(ParserContext parserContext, Element element, - BeanDefinitionBuilder mongoBuilder) { - Element optionsElement = DomUtils.getChildElementByTagName(element, "options"); - if (optionsElement == null) - return false; + /** + * Parses the options sub-element. Populates the given attribute factory with the proper attributes. + * + * @param element + * @param attrBuilder + * @return true if parsing actually occured, false otherwise + */ + private boolean parseOptions(ParserContext parserContext, Element element, BeanDefinitionBuilder mongoBuilder) { + Element optionsElement = DomUtils.getChildElementByTagName(element, "options"); + if (optionsElement == null) + return false; - BeanDefinitionBuilder optionsDefBuilder = BeanDefinitionBuilder.genericBeanDefinition(MongoOptionsFactoryBean.class); + BeanDefinitionBuilder optionsDefBuilder = BeanDefinitionBuilder + .genericBeanDefinition(MongoOptionsFactoryBean.class); - setPropertyValue(optionsElement, optionsDefBuilder, "connectionsPerHost", "connectionsPerHost"); - setPropertyValue(optionsElement, optionsDefBuilder, "threadsAllowedToBlockForConnectionMultiplier", "threadsAllowedToBlockForConnectionMultiplier"); - setPropertyValue(optionsElement, optionsDefBuilder, "maxWaitTime", "maxWaitTime"); - setPropertyValue(optionsElement, optionsDefBuilder, "connectTimeout", "connectTimeout"); - setPropertyValue(optionsElement, optionsDefBuilder, "socketTimeout", "socketTimeout"); - setPropertyValue(optionsElement, optionsDefBuilder, "autoConnectRetry", "autoConnectRetry"); + setPropertyValue(optionsElement, optionsDefBuilder, "connectionsPerHost", "connectionsPerHost"); + setPropertyValue(optionsElement, optionsDefBuilder, "threadsAllowedToBlockForConnectionMultiplier", + "threadsAllowedToBlockForConnectionMultiplier"); + setPropertyValue(optionsElement, optionsDefBuilder, "maxWaitTime", "maxWaitTime"); + setPropertyValue(optionsElement, optionsDefBuilder, "connectTimeout", "connectTimeout"); + setPropertyValue(optionsElement, optionsDefBuilder, "socketTimeout", "socketTimeout"); + setPropertyValue(optionsElement, optionsDefBuilder, "autoConnectRetry", "autoConnectRetry"); - mongoBuilder.addPropertyValue("mongoOptions", optionsDefBuilder.getBeanDefinition()); - return true; - } + mongoBuilder.addPropertyValue("mongoOptions", optionsDefBuilder.getBeanDefinition()); + return true; + } - @Override - protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) - throws BeanDefinitionStoreException { - String name = super.resolveId(element, definition, parserContext); - if (!StringUtils.hasText(name)) { - name = "mongo"; - } - return name; - } + @Override + protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) + throws BeanDefinitionStoreException { + String name = super.resolveId(element, definition, parserContext); + if (!StringUtils.hasText(name)) { + name = "mongo"; + } + return name; + } - private void setPropertyValue(Element element, BeanDefinitionBuilder builder, String attrName, String propertyName) { - String attr = element.getAttribute(attrName); - if (StringUtils.hasText(attr)) { - builder.addPropertyValue(propertyName, attr); - } - } + private void setPropertyValue(Element element, BeanDefinitionBuilder builder, String attrName, String propertyName) { + String attr = element.getAttribute(attrName); + if (StringUtils.hasText(attr)) { + builder.addPropertyValue(propertyName, attr); + } + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryConfigParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryConfigParser.java index a102093f2..94f39a1f2 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryConfigParser.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryConfigParser.java @@ -23,73 +23,68 @@ import org.springframework.data.mapping.model.MappingContext; import org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser; import org.w3c.dom.Element; - /** - * {@link org.springframework.beans.factory.xml.BeanDefinitionParser} to create - * Mongo DB repositories from classpath scanning or manual definition. - * + * {@link org.springframework.beans.factory.xml.BeanDefinitionParser} to create Mongo DB repositories from classpath + * scanning or manual definition. + * * @author Oliver Gierke */ -public class MongoRepositoryConfigParser - extends - AbstractRepositoryConfigDefinitionParser { - - private static final String MAPPING_CONTEXT_DEFAULT = MappingMongoConverterParser.MAPPING_CONTEXT; - - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.config. - * AbstractRepositoryConfigDefinitionParser - * #getGlobalRepositoryConfigInformation(org.w3c.dom.Element) - */ - @Override - protected SimpleMongoRepositoryConfiguration getGlobalRepositoryConfigInformation( - Element element) { +public class MongoRepositoryConfigParser extends + AbstractRepositoryConfigDefinitionParser { - return new SimpleMongoRepositoryConfiguration(element); - } + private static final String MAPPING_CONTEXT_DEFAULT = MappingMongoConverterParser.MAPPING_CONTEXT; + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.config. + * AbstractRepositoryConfigDefinitionParser + * #getGlobalRepositoryConfigInformation(org.w3c.dom.Element) + */ + @Override + protected SimpleMongoRepositoryConfiguration getGlobalRepositoryConfigInformation(Element element) { - /* - * (non-Javadoc) - * @see org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser#postProcessBeanDefinition(org.springframework.data.repository.config.SingleRepositoryConfigInformation, org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object) - */ - @Override - protected void postProcessBeanDefinition( - MongoRepositoryConfiguration context, - BeanDefinitionBuilder builder, BeanDefinitionRegistry registry, Object beanSource) { + return new SimpleMongoRepositoryConfiguration(element); + } - builder.addPropertyReference("template", context.getMongoTemplateRef()); - - String mappingContextRef = getMappingContextReference(context, registry); - if (mappingContextRef != null) { - builder.addPropertyReference("mappingContext", mappingContextRef); - } - } + /* + * (non-Javadoc) + * @see org.springframework.data.repository.config.AbstractRepositoryConfigDefinitionParser#postProcessBeanDefinition(org.springframework.data.repository.config.SingleRepositoryConfigInformation, org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.beans.factory.support.BeanDefinitionRegistry, java.lang.Object) + */ + @Override + protected void postProcessBeanDefinition(MongoRepositoryConfiguration context, BeanDefinitionBuilder builder, + BeanDefinitionRegistry registry, Object beanSource) { - /** - * Returns the bean name of a {@link MappingContext} to be wired. Will inspect the namespace attribute first and if no - * config is found in that place it will try to lookup the default one. Will return {@literal null} if neither one is - * available. - * - * @param config - * @param registry - * @return - */ - private String getMappingContextReference(MongoRepositoryConfiguration config, BeanDefinitionRegistry registry) { - - String contextRef = config.getMappingContextRef(); - - if (contextRef != null) { - return contextRef; - } - - try { - registry.getBeanDefinition(MAPPING_CONTEXT_DEFAULT); - return MAPPING_CONTEXT_DEFAULT; - } catch(NoSuchBeanDefinitionException e) { - return null; - } - } + builder.addPropertyReference("template", context.getMongoTemplateRef()); + + String mappingContextRef = getMappingContextReference(context, registry); + if (mappingContextRef != null) { + builder.addPropertyReference("mappingContext", mappingContextRef); + } + } + + /** + * Returns the bean name of a {@link MappingContext} to be wired. Will inspect the namespace attribute first and if no + * config is found in that place it will try to lookup the default one. Will return {@literal null} if neither one is + * available. + * + * @param config + * @param registry + * @return + */ + private String getMappingContextReference(MongoRepositoryConfiguration config, BeanDefinitionRegistry registry) { + + String contextRef = config.getMappingContextRef(); + + if (contextRef != null) { + return contextRef; + } + + try { + registry.getBeanDefinition(MAPPING_CONTEXT_DEFAULT); + return MAPPING_CONTEXT_DEFAULT; + } catch (NoSuchBeanDefinitionException e) { + return null; + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryNamespaceHandler.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryNamespaceHandler.java index 67c42d644..0dc275879 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryNamespaceHandler.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/MongoRepositoryNamespaceHandler.java @@ -17,25 +17,23 @@ package org.springframework.data.document.mongodb.config; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; - /** - * {@link org.springframework.beans.factory.xml.NamespaceHandler} for Mongo DB - * based repositories. - * + * {@link org.springframework.beans.factory.xml.NamespaceHandler} for Mongo DB based repositories. + * * @author Oliver Gierke */ public class MongoRepositoryNamespaceHandler extends NamespaceHandlerSupport { - /* - * (non-Javadoc) - * - * @see org.springframework.beans.factory.xml.NamespaceHandler#init() - */ - public void init() { + /* + * (non-Javadoc) + * + * @see org.springframework.beans.factory.xml.NamespaceHandler#init() + */ + public void init() { - registerBeanDefinitionParser("repositories", new MongoRepositoryConfigParser()); - registerBeanDefinitionParser("mapping-converter", new MappingMongoConverterParser()); - registerBeanDefinitionParser("mongo", new MongoParser()); - registerBeanDefinitionParser("jmx", new MongoJmxParser()); - } + registerBeanDefinitionParser("repositories", new MongoRepositoryConfigParser()); + registerBeanDefinitionParser("mapping-converter", new MappingMongoConverterParser()); + registerBeanDefinitionParser("mongo", new MongoParser()); + registerBeanDefinitionParser("jmx", new MongoJmxParser()); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/SimpleMongoRepositoryConfiguration.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/SimpleMongoRepositoryConfiguration.java index 89180dda1..f8428ce02 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/SimpleMongoRepositoryConfiguration.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/SimpleMongoRepositoryConfiguration.java @@ -23,180 +23,160 @@ import org.springframework.data.repository.config.SingleRepositoryConfigInformat import org.springframework.util.StringUtils; import org.w3c.dom.Element; - /** - * {@link RepositoryConfig} implementation to create - * {@link MongoRepositoryConfiguration} instances for both automatic and manual - * configuration. - * + * {@link RepositoryConfig} implementation to create {@link MongoRepositoryConfiguration} instances for both automatic + * and manual configuration. + * * @author Oliver Gierke */ -public class SimpleMongoRepositoryConfiguration extends RepositoryConfig { +public class SimpleMongoRepositoryConfiguration + extends + RepositoryConfig { - private static final String MONGO_TEMPLATE_REF = "mongo-template-ref"; - private static final String DEFAULT_MONGO_TEMPLATE_REF = "mongoTemplate"; - - private static final String MAPPING_CONTEXT_REF = "mongo-mapping-context-ref"; + private static final String MONGO_TEMPLATE_REF = "mongo-template-ref"; + private static final String DEFAULT_MONGO_TEMPLATE_REF = "mongoTemplate"; + private static final String MAPPING_CONTEXT_REF = "mongo-mapping-context-ref"; - /** - * Creates a new {@link SimpleMongoRepositoryConfiguration} for the given - * {@link Element}. - * - * @param repositoriesElement - */ - protected SimpleMongoRepositoryConfiguration(Element repositoriesElement) { + /** + * Creates a new {@link SimpleMongoRepositoryConfiguration} for the given {@link Element}. + * + * @param repositoriesElement + */ + protected SimpleMongoRepositoryConfiguration(Element repositoriesElement) { - super(repositoriesElement, MongoRepositoryFactoryBean.class.getName()); - } + super(repositoriesElement, MongoRepositoryFactoryBean.class.getName()); + } + /** + * Returns the bean name of the {@link org.springframework.data.document.mongodb.MongoTemplate} to be referenced. + * + * @return + */ + public String getMongoTemplateRef() { - /** - * Returns the bean name of the {@link org.springframework.data.document.mongodb.MongoTemplate} to be referenced. - * - * @return - */ - public String getMongoTemplateRef() { + String templateRef = getSource().getAttribute(MONGO_TEMPLATE_REF); + return StringUtils.hasText(templateRef) ? templateRef : DEFAULT_MONGO_TEMPLATE_REF; + } - String templateRef = getSource().getAttribute(MONGO_TEMPLATE_REF); - return StringUtils.hasText(templateRef) ? templateRef - : DEFAULT_MONGO_TEMPLATE_REF; - } - - public String getMappingContextRef() { - - String attribute = getSource().getAttribute(MAPPING_CONTEXT_REF); - return StringUtils.hasText(attribute) ? attribute : null; - } + public String getMappingContextRef() { + String attribute = getSource().getAttribute(MAPPING_CONTEXT_REF); + return StringUtils.hasText(attribute) ? attribute : null; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.config.GlobalRepositoryConfigInformation - * #getAutoconfigRepositoryInformation(java.lang.String) - */ - public MongoRepositoryConfiguration getAutoconfigRepositoryInformation( - String interfaceName) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.config.GlobalRepositoryConfigInformation + * #getAutoconfigRepositoryInformation(java.lang.String) + */ + public MongoRepositoryConfiguration getAutoconfigRepositoryInformation(String interfaceName) { - return new AutomaticMongoRepositoryConfiguration(interfaceName, this); - } + return new AutomaticMongoRepositoryConfiguration(interfaceName, this); + } + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.config.RepositoryConfig# + * createSingleRepositoryConfigInformationFor(org.w3c.dom.Element) + */ + @Override + protected MongoRepositoryConfiguration createSingleRepositoryConfigInformationFor(Element element) { - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.config.RepositoryConfig# - * createSingleRepositoryConfigInformationFor(org.w3c.dom.Element) - */ - @Override - protected MongoRepositoryConfiguration createSingleRepositoryConfigInformationFor( - Element element) { + return new ManualMongoRepositoryConfiguration(element, this); + } - return new ManualMongoRepositoryConfiguration(element, this); - } + /** + * Simple interface for configuration values specific to Mongo repositories. + * + * @author Oliver Gierke + */ + public interface MongoRepositoryConfiguration extends + SingleRepositoryConfigInformation { - /** - * Simple interface for configuration values specific to Mongo repositories. - * - * @author Oliver Gierke - */ - public interface MongoRepositoryConfiguration - extends - SingleRepositoryConfigInformation { + String getMongoTemplateRef(); - String getMongoTemplateRef(); - - String getMappingContextRef(); - } + String getMappingContextRef(); + } - /** - * Implements manual lookup of the additional attributes. - * - * @author Oliver Gierke - */ - private static class ManualMongoRepositoryConfiguration - extends - ManualRepositoryConfigInformation - implements MongoRepositoryConfiguration { + /** + * Implements manual lookup of the additional attributes. + * + * @author Oliver Gierke + */ + private static class ManualMongoRepositoryConfiguration extends + ManualRepositoryConfigInformation implements MongoRepositoryConfiguration { - /** - * Creates a new {@link ManualMongoRepositoryConfiguration} for the - * given {@link Element} and parent. - * - * @param element - * @param parent - */ - public ManualMongoRepositoryConfiguration(Element element, - SimpleMongoRepositoryConfiguration parent) { + /** + * Creates a new {@link ManualMongoRepositoryConfiguration} for the given {@link Element} and parent. + * + * @param element + * @param parent + */ + public ManualMongoRepositoryConfiguration(Element element, SimpleMongoRepositoryConfiguration parent) { - super(element, parent); - } + super(element, parent); + } + /* + * (non-Javadoc) + * + * @see org.springframework.data.document.mongodb.repository.config. + * SimpleMongoRepositoryConfiguration + * .MongoRepositoryConfiguration#getMongoTemplateRef() + */ + public String getMongoTemplateRef() { - /* - * (non-Javadoc) - * - * @see org.springframework.data.document.mongodb.repository.config. - * SimpleMongoRepositoryConfiguration - * .MongoRepositoryConfiguration#getMongoTemplateRef() - */ - public String getMongoTemplateRef() { + return getAttribute(MONGO_TEMPLATE_REF); + } - return getAttribute(MONGO_TEMPLATE_REF); - } - - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.config.SimpleMongoRepositoryConfiguration.MongoRepositoryConfiguration#getMappingContextRef() - */ - public String getMappingContextRef() { - return getAttribute(MAPPING_CONTEXT_REF); - } - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.config.SimpleMongoRepositoryConfiguration.MongoRepositoryConfiguration#getMappingContextRef() + */ + public String getMappingContextRef() { + return getAttribute(MAPPING_CONTEXT_REF); + } + } - /** - * Implements the lookup of the additional attributes during automatic - * configuration. - * - * @author Oliver Gierke - */ - private static class AutomaticMongoRepositoryConfiguration - extends - AutomaticRepositoryConfigInformation - implements MongoRepositoryConfiguration { + /** + * Implements the lookup of the additional attributes during automatic configuration. + * + * @author Oliver Gierke + */ + private static class AutomaticMongoRepositoryConfiguration extends + AutomaticRepositoryConfigInformation implements MongoRepositoryConfiguration { - /** - * Creates a new {@link AutomaticMongoRepositoryConfiguration} for the - * given interface and parent. - * - * @param interfaceName - * @param parent - */ - public AutomaticMongoRepositoryConfiguration(String interfaceName, - SimpleMongoRepositoryConfiguration parent) { + /** + * Creates a new {@link AutomaticMongoRepositoryConfiguration} for the given interface and parent. + * + * @param interfaceName + * @param parent + */ + public AutomaticMongoRepositoryConfiguration(String interfaceName, SimpleMongoRepositoryConfiguration parent) { - super(interfaceName, parent); - } + super(interfaceName, parent); + } + /* + * (non-Javadoc) + * + * @see org.springframework.data.document.mongodb.repository.config. + * SimpleMongoRepositoryConfiguration + * .MongoRepositoryConfiguration#getMongoTemplateRef() + */ + public String getMongoTemplateRef() { - /* - * (non-Javadoc) - * - * @see org.springframework.data.document.mongodb.repository.config. - * SimpleMongoRepositoryConfiguration - * .MongoRepositoryConfiguration#getMongoTemplateRef() - */ - public String getMongoTemplateRef() { + return getParent().getMongoTemplateRef(); + } - return getParent().getMongoTemplateRef(); - } - - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.config.SimpleMongoRepositoryConfiguration.MongoRepositoryConfiguration#getMappingContextRef() - */ - public String getMappingContextRef() { - return getParent().getMappingContextRef(); - } - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.config.SimpleMongoRepositoryConfiguration.MongoRepositoryConfiguration#getMappingContextRef() + */ + public String getMappingContextRef() { + return getParent().getMappingContextRef(); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/package-info.java index 4e53a77e4..ca2b4a77e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/config/package-info.java @@ -2,3 +2,4 @@ * Spring XML namespace configuration for MongoDB specific repositories. */ package org.springframework.data.document.mongodb.config; + diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MappingMongoConverter.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MappingMongoConverter.java index ee5a63301..9f90186fe 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MappingMongoConverter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MappingMongoConverter.java @@ -72,19 +72,22 @@ import org.springframework.expression.spel.support.StandardEvaluationContext; /** * {@link MongoConverter} that uses a {@link MappingContext} to do sophisticated mapping of domain objects to * {@link DBObject}. - * + * * @author Jon Brisbin * @author Oliver Gierke */ public class MappingMongoConverter extends AbstractMongoConverter implements ApplicationContextAware, InitializingBean { public static final String CUSTOM_TYPE_KEY = "_class"; - @SuppressWarnings({"unchecked"}) - private static final List> MONGO_TYPES = Arrays.asList(Number.class, Date.class, String.class, DBObject.class); - private static final List> VALID_ID_TYPES = Arrays.asList(new Class[]{ObjectId.class, String.class, BigInteger.class, byte[].class}); + @SuppressWarnings({ "unchecked" }) + private static final List> MONGO_TYPES = Arrays.asList(Number.class, Date.class, String.class, + DBObject.class); + private static final List> VALID_ID_TYPES = Arrays.asList(new Class[] { ObjectId.class, String.class, + BigInteger.class, byte[].class }); protected static final Log log = LogFactory.getLog(MappingMongoConverter.class); - protected final GenericConversionService conversionService = ConversionServiceFactory.createDefaultConversionService(); + protected final GenericConversionService conversionService = ConversionServiceFactory + .createDefaultConversionService(); protected final Set customTypeMapping = new HashSet(); protected final MappingContext, MongoPersistentProperty> mappingContext; protected SpelExpressionParser spelExpressionParser = new SpelExpressionParser(); @@ -95,10 +98,11 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App /** * Creates a new {@link MappingMongoConverter} with the given {@link MappingContext}. - * + * * @param mappingContext */ - public MappingMongoConverter(MappingContext, MongoPersistentProperty> mappingContext) { + public MappingMongoConverter( + MappingContext, MongoPersistentProperty> mappingContext) { this.mappingContext = mappingContext; this.conversionService.removeConvertible(Object.class, String.class); } @@ -106,7 +110,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App /** * Add custom {@link Converter} or {@link ConverterFactory} instances to be used that will take presidence over * metadata driven conversion between of objects to/from DBObject - * + * * @param converters */ public void setConverters(List> converters) { @@ -120,7 +124,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App /** * Inspects the given {@link Converter} for the types it can convert and registers the pair for custom type conversion * in case the target type is a Mongo basic type. - * + * * @param converter */ private void registerConverter(Converter converter) { @@ -177,50 +181,51 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App public S read(Class clazz, final DBObject dbo) { return read(ClassTypeInformation.from(clazz), dbo); } - + @SuppressWarnings("unchecked") - protected S read(TypeInformation type, DBObject dbo) { - - if (null == dbo) { - return null; - } - - TypeInformation typeToUse = getMoreConcreteTargetType(dbo, type); - Class rawType = typeToUse.getType(); - Class customTarget = getCustomTarget(rawType, DBObject.class); + protected S read(TypeInformation type, DBObject dbo) { - if (customTarget != null) { - return conversionService.convert(dbo, rawType); - } + if (null == dbo) { + return null; + } - if (typeToUse.isCollectionLike() && dbo instanceof BasicDBList) { - List l = new ArrayList(); - BasicDBList dbList = (BasicDBList) dbo; - for (Object o : dbList) { - if (o instanceof DBObject) { - - Object newObj = read(typeToUse.getComponentType(), (DBObject) o); - Class rawComponentType = typeToUse.getComponentType().getType(); - - if (newObj.getClass().isAssignableFrom(rawComponentType)) { - l.add(newObj); - } else { - l.add(conversionService.convert(newObj, rawComponentType)); - } - } else { - l.add(o); - } - } - return conversionService.convert(l, rawType); - } + TypeInformation typeToUse = getMoreConcreteTargetType(dbo, type); + Class rawType = typeToUse.getType(); + Class customTarget = getCustomTarget(rawType, DBObject.class); - // Retrieve persistent entity info - MongoPersistentEntity persistentEntity = (MongoPersistentEntity) mappingContext.getPersistentEntity(typeToUse); - if (persistentEntity == null) { - throw new MappingException("No mapping metadata found for " + rawType.getName()); - } + if (customTarget != null) { + return conversionService.convert(dbo, rawType); + } - return read(persistentEntity, dbo); + if (typeToUse.isCollectionLike() && dbo instanceof BasicDBList) { + List l = new ArrayList(); + BasicDBList dbList = (BasicDBList) dbo; + for (Object o : dbList) { + if (o instanceof DBObject) { + + Object newObj = read(typeToUse.getComponentType(), (DBObject) o); + Class rawComponentType = typeToUse.getComponentType().getType(); + + if (newObj.getClass().isAssignableFrom(rawComponentType)) { + l.add(newObj); + } else { + l.add(conversionService.convert(newObj, rawComponentType)); + } + } else { + l.add(o); + } + } + return conversionService.convert(l, rawType); + } + + // Retrieve persistent entity info + MongoPersistentEntity persistentEntity = (MongoPersistentEntity) mappingContext + .getPersistentEntity(typeToUse); + if (persistentEntity == null) { + throw new MappingException("No mapping metadata found for " + rawType.getName()); + } + + return read(persistentEntity, dbo); } private S read(final MongoPersistentEntity entity, final DBObject dbo) { @@ -230,7 +235,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App spelCtx.setBeanResolver(new BeanFactoryResolver(applicationContext)); } if (!(dbo instanceof BasicDBList)) { - String[] keySet = dbo.keySet().toArray(new String[]{}); + String[] keySet = dbo.keySet().toArray(new String[] {}); for (String key : keySet) { spelCtx.setVariable(key, dbo.get(key)); } @@ -240,7 +245,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App final MongoPersistentProperty idProperty = entity.getIdProperty(); final S instance = constructInstance(entity, new PreferredConstructor.ParameterValueProvider() { @SuppressWarnings("unchecked") - public T getParameterValue(PreferredConstructor.Parameter parameter) { + public T getParameterValue(PreferredConstructor.Parameter parameter) { String name = parameter.getName(); TypeInformation type = parameter.getType(); Class rawType = parameter.getRawType(); @@ -269,17 +274,17 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App // Set properties not already set in the constructor entity.doWithProperties(new PropertyHandler() { public void doWithPersistentProperty(MongoPersistentProperty prop) { - - boolean isConstructorProperty = ctorParamNames.contains(prop.getName()); - boolean hasValueForProperty = dbo.containsField(prop.getKey()); - + + boolean isConstructorProperty = ctorParamNames.contains(prop.getName()); + boolean hasValueForProperty = dbo.containsField(prop.getKey()); + if (!hasValueForProperty || isConstructorProperty) { return; } Object obj = getValueInternal(prop, dbo, spelCtx, prop.getSpelExpression()); try { - setProperty(instance, prop, obj, useFieldAccessOnly); + setProperty(instance, prop, obj, useFieldAccessOnly); } catch (IllegalAccessException e) { throw new MappingException(e.getMessage(), e); } catch (InvocationTargetException e) { @@ -306,56 +311,56 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App return instance; } - /** - * Root entry method into write conversion. Adds a type discriminator to the {@link DBObject}. Shouldn't be called for - * nested conversions. - * - * @see org.springframework.data.document.mongodb.MongoWriter#write(java.lang.Object, com.mongodb.DBObject) - */ - public void write(final Object obj, final DBObject dbo) { - + /** + * Root entry method into write conversion. Adds a type discriminator to the {@link DBObject}. Shouldn't be called for + * nested conversions. + * + * @see org.springframework.data.document.mongodb.MongoWriter#write(java.lang.Object, com.mongodb.DBObject) + */ + public void write(final Object obj, final DBObject dbo) { + if (null == obj) { return; } boolean handledByCustomConverter = getCustomTarget(obj.getClass(), DBObject.class) != null; - + if (!handledByCustomConverter) { - dbo.put(CUSTOM_TYPE_KEY, obj.getClass().getName()); + dbo.put(CUSTOM_TYPE_KEY, obj.getClass().getName()); } writeInternal(obj, dbo); } - - /** - * Internal write conversion method which should be used for nested invocations. - * - * @param obj - * @param dbo - */ + + /** + * Internal write conversion method which should be used for nested invocations. + * + * @param obj + * @param dbo + */ @SuppressWarnings("unchecked") - protected void writeInternal(final Object obj, final DBObject dbo) { - - if (null == obj) { - return; - } + protected void writeInternal(final Object obj, final DBObject dbo) { - Class customTarget = getCustomTarget(obj.getClass(), DBObject.class); + if (null == obj) { + return; + } - if (customTarget != null) { - DBObject result = conversionService.convert(obj, DBObject.class); - dbo.putAll(result); - return; - } - - if (Map.class.isAssignableFrom(obj.getClass())) { - writeMapInternal((Map) obj, dbo); - return; - } + Class customTarget = getCustomTarget(obj.getClass(), DBObject.class); - MongoPersistentEntity entity = mappingContext.getPersistentEntity(obj.getClass()); - writeInternal(obj, dbo, entity); - } + if (customTarget != null) { + DBObject result = conversionService.convert(obj, DBObject.class); + dbo.putAll(result); + return; + } + + if (Map.class.isAssignableFrom(obj.getClass())) { + writeMapInternal((Map) obj, dbo); + return; + } + + MongoPersistentEntity entity = mappingContext.getPersistentEntity(obj.getClass()); + writeInternal(obj, dbo, entity); + } protected void writeInternal(final Object obj, final DBObject dbo, MongoPersistentEntity entity) { @@ -383,7 +388,8 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App dbo.put("_id", idObj); } else { if (!VALID_ID_TYPES.contains(idProperty.getType())) { - throw new MappingException("Invalid data type " + idProperty.getType().getName() + " for Id property. Should be one of " + VALID_ID_TYPES); + throw new MappingException("Invalid data type " + idProperty.getType().getName() + + " for Id property. Should be one of " + VALID_ID_TYPES); } } } @@ -413,7 +419,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App entity.doWithAssociations(new AssociationHandler() { public void doWithAssociation(Association association) { - MongoPersistentProperty inverseProp = association.getInverse(); + MongoPersistentProperty inverseProp = association.getInverse(); Class type = inverseProp.getType(); Object propertyObj; try { @@ -456,10 +462,10 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App setConversionService(conversionService); } - @SuppressWarnings({"unchecked"}) + @SuppressWarnings({ "unchecked" }) protected void writePropertyInternal(MongoPersistentProperty prop, Object obj, DBObject dbo) { - org.springframework.data.document.mongodb.mapping.DBRef dbref = prop.getField() - .getAnnotation(org.springframework.data.document.mongodb.mapping.DBRef.class); + org.springframework.data.document.mongodb.mapping.DBRef dbref = prop.getField().getAnnotation( + org.springframework.data.document.mongodb.mapping.DBRef.class); String name = prop.getName(); Class type = prop.getType(); @@ -542,16 +548,15 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App Object key = entry.getKey(); Object val = entry.getValue(); if (isSimpleType(key.getClass())) { - // Don't use conversion service here as removal of ObjectToString converter results in some primitive types not - // being convertable + // Don't use conversion service here as removal of ObjectToString converter results in some primitive types not + // being convertable String simpleKey = key.toString(); if (isSimpleType(val.getClass())) { dbo.put(simpleKey, val); } else { DBObject newDbo = new BasicDBObject(); Class componentType = val.getClass(); - if (componentType.isArray() - || componentType.isAssignableFrom(Collection.class) + if (componentType.isArray() || componentType.isAssignableFrom(Collection.class) || componentType.isAssignableFrom(List.class)) { Class ctype = val.getClass().getComponentType(); dbo.put("_class", (null != ctype ? ctype.getName() : componentType.getName())); @@ -600,15 +605,16 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App return new DBRef(db, collection, id); } - @SuppressWarnings({"unchecked"}) - protected Object getValueInternal(MongoPersistentProperty prop, DBObject dbo, StandardEvaluationContext ctx, String spelExpr) { + @SuppressWarnings({ "unchecked" }) + protected Object getValueInternal(MongoPersistentProperty prop, DBObject dbo, StandardEvaluationContext ctx, + String spelExpr) { Object o; if (null != spelExpr) { Expression x = spelExpressionParser.parseExpression(spelExpr); o = x.getValue(ctx); } else { - + Object dbObj = dbo.get(prop.getKey()); if (dbObj == null) { @@ -636,10 +642,10 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App if (entry.getKey().equals(CUSTOM_TYPE_KEY)) { continue; } - + Class keyType = prop.getComponentType(); Object key = conversionService.convert(entry.getKey(), keyType); - + if (null != entry.getValue() && entry.getValue() instanceof DBObject) { m.put(key, read((null != toType ? toType : prop.getMapValueType()), (DBObject) entry.getValue())); } else { @@ -688,7 +694,7 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App /** * Returns the type to be used to convert the DBObject given to. - * + * * @param dbObject * @return */ @@ -706,21 +712,21 @@ public class MappingMongoConverter extends AbstractMongoConverter implements App } } - /** - * Inspects the a custom class definition stored inside the given {@link DBObject} and returns that in case it's a - * subtype of the given basic one. - * - * @param dbObject - * @param basicType - * @return - */ + /** + * Inspects the a custom class definition stored inside the given {@link DBObject} and returns that in case it's a + * subtype of the given basic one. + * + * @param dbObject + * @param basicType + * @return + */ @SuppressWarnings("unchecked") - private TypeInformation getMoreConcreteTargetType(DBObject dbObject, TypeInformation basicType) { - Class documentsTargetType = findTypeToBeUsed(dbObject); - Class rawType = basicType.getType(); - boolean isMoreConcreteCustomType = documentsTargetType != null && rawType.isAssignableFrom(documentsTargetType); - return isMoreConcreteCustomType ? (TypeInformation) ClassTypeInformation.from(documentsTargetType) - : basicType; + private TypeInformation getMoreConcreteTargetType(DBObject dbObject, TypeInformation basicType) { + Class documentsTargetType = findTypeToBeUsed(dbObject); + Class rawType = basicType.getType(); + boolean isMoreConcreteCustomType = documentsTargetType != null && rawType.isAssignableFrom(documentsTargetType); + return isMoreConcreteCustomType ? (TypeInformation) ClassTypeInformation.from(documentsTargetType) + : basicType; } protected List unwrapList(BasicDBList dbList, TypeInformation targetType) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoBeanWrapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoBeanWrapper.java index c56553cec..5527abada 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoBeanWrapper.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoBeanWrapper.java @@ -28,67 +28,67 @@ import org.springframework.util.Assert; /** * Custom Mongo specific {@link BeanWrapper} to allow access to bean properties via {@link MongoPropertyDescriptor}s. - * + * * @author Oliver Gierke */ class MongoBeanWrapper { - private final ConfigurablePropertyAccessor accessor; - private final MongoPropertyDescriptors descriptors; - private final boolean fieldAccess; + private final ConfigurablePropertyAccessor accessor; + private final MongoPropertyDescriptors descriptors; + private final boolean fieldAccess; - /** - * Creates a new {@link MongoBeanWrapper} for the given target object and {@link ConversionService}. - * - * @param target - * @param conversionService - * @param fieldAccess - */ - public MongoBeanWrapper(Object target, ConversionService conversionService, boolean fieldAccess) { + /** + * Creates a new {@link MongoBeanWrapper} for the given target object and {@link ConversionService}. + * + * @param target + * @param conversionService + * @param fieldAccess + */ + public MongoBeanWrapper(Object target, ConversionService conversionService, boolean fieldAccess) { - Assert.notNull(target); - Assert.notNull(conversionService); + Assert.notNull(target); + Assert.notNull(conversionService); - this.fieldAccess = fieldAccess; - this.accessor = fieldAccess ? forDirectFieldAccess(target) : forBeanPropertyAccess(target); - this.accessor.setConversionService(conversionService); - this.descriptors = new MongoPropertyDescriptors(target.getClass()); - } + this.fieldAccess = fieldAccess; + this.accessor = fieldAccess ? forDirectFieldAccess(target) : forBeanPropertyAccess(target); + this.accessor.setConversionService(conversionService); + this.descriptors = new MongoPropertyDescriptors(target.getClass()); + } - /** - * Returns all {@link MongoPropertyDescriptors.MongoPropertyDescriptor}s for the underlying target object. - * - * @return - */ - public MongoPropertyDescriptors getDescriptors() { - return this.descriptors; - } + /** + * Returns all {@link MongoPropertyDescriptors.MongoPropertyDescriptor}s for the underlying target object. + * + * @return + */ + public MongoPropertyDescriptors getDescriptors() { + return this.descriptors; + } - /** - * Returns the value of the underlying object for the given property. - * - * @param descriptor - * @return - */ - public Object getValue(MongoPropertyDescriptors.MongoPropertyDescriptor descriptor) { - Assert.notNull(descriptor); - return accessor.getPropertyValue(descriptor.getName()); - } + /** + * Returns the value of the underlying object for the given property. + * + * @param descriptor + * @return + */ + public Object getValue(MongoPropertyDescriptors.MongoPropertyDescriptor descriptor) { + Assert.notNull(descriptor); + return accessor.getPropertyValue(descriptor.getName()); + } - /** - * Sets the property of the underlying object to the given value. - * - * @param descriptor - * @param value - */ - public void setValue(MongoPropertyDescriptors.MongoPropertyDescriptor descriptor, Object value) { - Assert.notNull(descriptor); - try { - accessor.setPropertyValue(descriptor.getName(), value); - } catch (NotWritablePropertyException e) { - if (!fieldAccess) { - throw e; - } - } - } + /** + * Sets the property of the underlying object to the given value. + * + * @param descriptor + * @param value + */ + public void setValue(MongoPropertyDescriptors.MongoPropertyDescriptor descriptor, Object value) { + Assert.notNull(descriptor); + try { + accessor.setPropertyValue(descriptor.getName(), value); + } catch (NotWritablePropertyException e) { + if (!fieldAccess) { + throw e; + } + } + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoConverter.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoConverter.java index a57e97cbc..13415a2cb 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoConverter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/MongoConverter.java @@ -23,29 +23,30 @@ import org.springframework.data.document.mongodb.mapping.MongoPersistentEntity; import org.springframework.data.document.mongodb.mapping.MongoPersistentProperty; import org.springframework.data.mapping.model.MappingContext; - public interface MongoConverter extends MongoWriter, MongoReader { - /** - * Converts the given {@link ObjectId} to the given target type. - * - * @param the actual type to create - * @param id the source {@link ObjectId} - * @param targetType the target type to convert the {@link ObjectId} to - * @return - */ - public T convertObjectId(ObjectId id, Class targetType); + /** + * Converts the given {@link ObjectId} to the given target type. + * + * @param + * the actual type to create + * @param id + * the source {@link ObjectId} + * @param targetType + * the target type to convert the {@link ObjectId} to + * @return + */ + public T convertObjectId(ObjectId id, Class targetType); + /** + * Returns the {@link ObjectId} instance for the given id. + * + * @param id + * @return + */ + public ObjectId convertObjectId(Object id); - /** - * Returns the {@link ObjectId} instance for the given id. - * - * @param id - * @return - */ - public ObjectId convertObjectId(Object id); - - MappingContext, MongoPersistentProperty> getMappingContext(); + MappingContext, MongoPersistentProperty> getMappingContext(); Object maybeConvertObject(Object obj); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/ObjectIdConverters.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/ObjectIdConverters.java index d96633d24..2d81addcc 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/ObjectIdConverters.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/ObjectIdConverters.java @@ -22,67 +22,67 @@ import org.springframework.core.convert.converter.Converter; /** * Wrapper class to contain useful {@link ObjectId}-to-something-and-back converters. - * + * * @author Oliver Gierke */ abstract class ObjectIdConverters { - - /** - * Private constructor to prevent instantiation. - */ - private ObjectIdConverters() { - - } - /** - * Simple singleton to convert {@link ObjectId}s to their {@link String} representation. - * - * @author Oliver Gierke - */ - public static enum ObjectIdToStringConverter implements Converter { - INSTANCE; + /** + * Private constructor to prevent instantiation. + */ + private ObjectIdConverters() { - public String convert(ObjectId id) { - return id.toString(); - } - } - - /** - * Simple singleton to convert {@link String}s to their {@link ObjectId} representation. - * - * @author Oliver Gierke - */ - public static enum StringToObjectIdConverter implements Converter { - INSTANCE; + } - public ObjectId convert(String source) { - return new ObjectId(source); - } - } - - /** - * Simple singleton to convert {@link ObjectId}s to their {@link java.math.BigInteger} representation. - * - * @author Oliver Gierke - */ - public static enum ObjectIdToBigIntegerConverter implements Converter { - INSTANCE; + /** + * Simple singleton to convert {@link ObjectId}s to their {@link String} representation. + * + * @author Oliver Gierke + */ + public static enum ObjectIdToStringConverter implements Converter { + INSTANCE; - public BigInteger convert(ObjectId source) { - return new BigInteger(source.toString(), 16); - } - } - - /** - * Simple singleton to convert {@link BigInteger}s to their {@link ObjectId} representation. - * - * @author Oliver Gierke - */ - public static enum BigIntegerToObjectIdConverter implements Converter { - INSTANCE; + public String convert(ObjectId id) { + return id.toString(); + } + } - public ObjectId convert(BigInteger source) { - return new ObjectId(source.toString(16)); - } - } + /** + * Simple singleton to convert {@link String}s to their {@link ObjectId} representation. + * + * @author Oliver Gierke + */ + public static enum StringToObjectIdConverter implements Converter { + INSTANCE; + + public ObjectId convert(String source) { + return new ObjectId(source); + } + } + + /** + * Simple singleton to convert {@link ObjectId}s to their {@link java.math.BigInteger} representation. + * + * @author Oliver Gierke + */ + public static enum ObjectIdToBigIntegerConverter implements Converter { + INSTANCE; + + public BigInteger convert(ObjectId source) { + return new BigInteger(source.toString(), 16); + } + } + + /** + * Simple singleton to convert {@link BigInteger}s to their {@link ObjectId} representation. + * + * @author Oliver Gierke + */ + public static enum BigIntegerToObjectIdConverter implements Converter { + INSTANCE; + + public ObjectId convert(BigInteger source) { + return new ObjectId(source.toString(16)); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/SimpleMongoConverter.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/SimpleMongoConverter.java index d1b3ccbf9..7bae4b1ca 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/SimpleMongoConverter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/convert/SimpleMongoConverter.java @@ -64,7 +64,7 @@ import org.springframework.util.comparator.CompoundComparator; /** * Basic {@link MongoConverter} implementation to convert between domain classes and {@link DBObject}s. - * + * * @author Mark Pollack * @author Thomas Risberg * @author Oliver Gierke @@ -73,7 +73,8 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init private static final Log LOG = LogFactory.getLog(SimpleMongoConverter.class); @SuppressWarnings("unchecked") - private static final List> MONGO_TYPES = Arrays.asList(Number.class, Date.class, String.class, DBObject.class); + private static final List> MONGO_TYPES = Arrays.asList(Number.class, Date.class, String.class, + DBObject.class); private static final Set SIMPLE_TYPES; static { @@ -165,9 +166,9 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init } /** - * Add custom {@link Converter} or {@link ConverterFactory} instances to be used that will take presidence over - * using object traversal to convert and object to/from DBObject - * + * Add custom {@link Converter} or {@link ConverterFactory} instances to be used that will take presidence over using + * object traversal to convert and object to/from DBObject + * * @param converters */ public void setConverters(Set converters) { @@ -232,7 +233,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Writes the given value to the given {@link DBObject}. Will skip {@literal null} values. - * + * * @param dbo * @param keyToUse * @param value @@ -248,7 +249,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Writes the given {@link CompoundComparator} value to the given {@link DBObject}. - * + * * @param dbo * @param keyToUse * @param value @@ -284,7 +285,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Returns whether the {@link ConversionService} has a custom {@link Converter} registered that can convert the given * object into one of the types supported by MongoDB. - * + * * @param obj * @return */ @@ -300,7 +301,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Writes the given {@link Map} to the given {@link DBObject}. - * + * * @param dbo * @param mapKey * @param map @@ -335,7 +336,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Writes the given array to the given {@link DBObject}. - * + * * @param dbo * @param keyToUse * @param array @@ -381,24 +382,20 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init Object value = source.get(keyToUse); if (!isSimpleType(value.getClass())) { if (value instanceof Object[]) { - bw.setValue(descriptor, readCollection(descriptor, Arrays.asList((Object[]) value)) - .toArray()); + bw.setValue(descriptor, readCollection(descriptor, Arrays.asList((Object[]) value)).toArray()); } else if (value instanceof BasicDBList) { bw.setValue(descriptor, readCollection(descriptor, (BasicDBList) value)); } else if (value instanceof DBObject) { bw.setValue(descriptor, readCompoundValue(descriptor, (DBObject) value)); } else { - LOG.warn("Unable to map compound DBObject field " + keyToUse + " to property " - + descriptor.getName() - + ". The field value should have been a 'DBObject.class' but was " - + value.getClass().getName()); + LOG.warn("Unable to map compound DBObject field " + keyToUse + " to property " + descriptor.getName() + + ". The field value should have been a 'DBObject.class' but was " + value.getClass().getName()); } } else { bw.setValue(descriptor, value); } } else { - LOG.warn("Unable to map DBObject field " + keyToUse + " to property " + descriptor.getName() - + ". Skipping."); + LOG.warn("Unable to map DBObject field " + keyToUse + " to property " + descriptor.getName() + ". Skipping."); } } } @@ -409,7 +406,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Reads the given collection values (that are {@link DBObject}s potentially) into a {@link Collection} of domain * objects. - * + * * @param descriptor * @param values * @return @@ -442,7 +439,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Reads a compound value from the given {@link DBObject} for the given property. - * + * * @param pd * @param dbo * @return @@ -461,7 +458,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Create a {@link Map} instance. Will return a {@link HashMap} by default. Subclasses might want to override this * method to use a custom {@link Map} implementation. - * + * * @return */ protected Map createMap() { @@ -470,7 +467,7 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Reads every key/value pair from the {@link DBObject} into a {@link Map} instance. - * + * * @param pd * @param dbo * @param targetType @@ -503,9 +500,11 @@ public class SimpleMongoConverter extends AbstractMongoConverter implements Init /** * Callback to allow customizing creation of a {@link MongoBeanWrapper}. - * - * @param target the target object to wrap - * @param fieldAccess whether to use field access or property access + * + * @param target + * the target object to wrap + * @param fieldAccess + * whether to use field access or property access * @return */ protected MongoBeanWrapper createWrapper(Object target, boolean fieldAccess) { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Box.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Box.java index b51cfb926..9ef44fe9d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Box.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Box.java @@ -25,57 +25,57 @@ import org.springframework.util.Assert; */ public class Box { - private final Point first; - private final Point second; + private final Point first; + private final Point second; - public Box(Point lowerLeft, Point upperRight) { - Assert.notNull(lowerLeft); - Assert.notNull(upperRight); - this.first = lowerLeft; - this.second = upperRight; - } + public Box(Point lowerLeft, Point upperRight) { + Assert.notNull(lowerLeft); + Assert.notNull(upperRight); + this.first = lowerLeft; + this.second = upperRight; + } - public Box(double[] lowerLeft, double[] upperRight) { - Assert.isTrue(lowerLeft.length == 2, "Point array has to have 2 elements!"); - Assert.isTrue(upperRight.length == 2, "Point array has to have 2 elements!"); - this.first = new Point(lowerLeft[0], lowerLeft[1]); - this.second = new Point(upperRight[0], upperRight[1]); - } + public Box(double[] lowerLeft, double[] upperRight) { + Assert.isTrue(lowerLeft.length == 2, "Point array has to have 2 elements!"); + Assert.isTrue(upperRight.length == 2, "Point array has to have 2 elements!"); + this.first = new Point(lowerLeft[0], lowerLeft[1]); + this.second = new Point(upperRight[0], upperRight[1]); + } - public Point getLowerLeft() { - return first; - } + public Point getLowerLeft() { + return first; + } - public Point getUpperRight() { - return second; - } + public Point getUpperRight() { + return second; + } - @Override - public String toString() { - return String.format("Box [%s, %s]", first, second); - } + @Override + public String toString() { + return String.format("Box [%s, %s]", first, second); + } - @Override - public int hashCode() { + @Override + public int hashCode() { - int result = 31; - result += 17 * first.hashCode(); - result += 17 * second.hashCode(); - return result; - } + int result = 31; + result += 17 * first.hashCode(); + result += 17 * second.hashCode(); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Box that = (Box) obj; - return this.first.equals(that.first) && this.second.equals(that.second); - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Box that = (Box) obj; + return this.first.equals(that.first) && this.second.equals(that.second); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Circle.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Circle.java index 05ddaf7d4..8bb0e5b17 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Circle.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Circle.java @@ -19,35 +19,36 @@ import org.springframework.util.Assert; /** * Represents a geospatial circle value + * * @author Mark Pollack * @author Oliver Gierke */ public class Circle { - private Point center; - private double radius; - - public Circle(Point center, double radius) { - Assert.notNull(center); - Assert.isTrue(radius >= 0, "Radius must not be negative!"); - this.center = center; - this.radius = radius; - } - - public Circle(double centerX, double centerY, double radius) { - this(new Point(centerX, centerY), radius); - } + private Point center; + private double radius; - public Point getCenter() { - return center; - } + public Circle(Point center, double radius) { + Assert.notNull(center); + Assert.isTrue(radius >= 0, "Radius must not be negative!"); + this.center = center; + this.radius = radius; + } - public double getRadius() { - return radius; - } + public Circle(double centerX, double centerY, double radius) { + this(new Point(centerX, centerY), radius); + } - @Override - public String toString() { - return String.format("Circle [center=%s, radius=%d]", center, radius); - } + public Point getCenter() { + return center; + } + + public double getRadius() { + return radius; + } + + @Override + public String toString() { + return String.format("Circle [center=%s, radius=%d]", center, radius); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Point.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Point.java index 451bc277a..ad32b2525 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Point.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/geo/Point.java @@ -26,70 +26,68 @@ import org.springframework.util.Assert; */ public class Point { - private final double x; - private final double y; - - @PersistenceConstructor - public Point(double x, double y) { - this.x = x; - this.y = y; - } - - public Point(Point point) { - Assert.notNull(point); - this.x = point.x; - this.y = point.y; - } + private final double x; + private final double y; - public double getX() { - return x; - } + @PersistenceConstructor + public Point(double x, double y) { + this.x = x; + this.y = y; + } - public double getY() { - return y; - } - - public double[] asArray() { - return new double[] {x, y}; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - long temp; - temp = Double.doubleToLongBits(x); - result = prime * result + (int) (temp ^ (temp >>> 32)); - temp = Double.doubleToLongBits(y); - result = prime * result + (int) (temp ^ (temp >>> 32)); - return result; - } + public Point(Point point) { + Assert.notNull(point); + this.x = point.x; + this.y = point.y; + } - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - Point other = (Point) obj; - if (Double.doubleToLongBits(x) != Double - .doubleToLongBits(other.x)) { - return false; - } - if (Double.doubleToLongBits(y) != Double - .doubleToLongBits(other.y)) { - return false; - } - return true; - } + public double getX() { + return x; + } - @Override - public String toString() { - return String.format("Point [latitude=%d, longitude=%d]", x, y); - } + public double getY() { + return y; + } + + public double[] asArray() { + return new double[] { x, y }; + } + + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + long temp; + temp = Double.doubleToLongBits(x); + result = prime * result + (int) (temp ^ (temp >>> 32)); + temp = Double.doubleToLongBits(y); + result = prime * result + (int) (temp ^ (temp >>> 32)); + return result; + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + Point other = (Point) obj; + if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x)) { + return false; + } + if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) { + return false; + } + return true; + } + + @Override + public String toString() { + return String.format("Point [latitude=%d, longitude=%d]", x, y); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndex.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndex.java index b079ad7b0..6333636f2 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndex.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndex.java @@ -23,9 +23,10 @@ import java.lang.annotation.Target; /** * Mark a class to use compound indexes. + * * @author Jon Brisbin */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface CompoundIndex { diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndexes.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndexes.java index 72ac63adb..ae1b0f68d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndexes.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/CompoundIndexes.java @@ -24,10 +24,10 @@ import java.lang.annotation.Target; /** * @author Jon Brisbin */ -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) @Retention(RetentionPolicy.RUNTIME) public @interface CompoundIndexes { - CompoundIndex[] value(); + CompoundIndex[] value(); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/GeoSpatialIndexed.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/GeoSpatialIndexed.java index 613983355..d0345606e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/GeoSpatialIndexed.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/GeoSpatialIndexed.java @@ -23,7 +23,7 @@ import java.lang.annotation.Target; /** * Mark a field to be indexed using MongoDB's geospatial indexing feature. - * + * * @author Jon Brisbin */ @Target(ElementType.FIELD) @@ -32,35 +32,35 @@ public @interface GeoSpatialIndexed { /** * Name of the property in the document that contains the [x, y] or radial coordinates to index. - * + * * @return */ String name() default ""; /** * Name of the collection in which to create the index. - * + * * @return */ String collection() default ""; /** * Minimum value for indexed values. - * + * * @return */ int min() default -180; /** * Maximum value for indexed values. - * + * * @return */ int max() default 180; /** * Bits of precision for boundary calculations. - * + * * @return */ int bits() default 26; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDefinition.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDefinition.java index 576f9cf99..95507ebff 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDefinition.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDefinition.java @@ -23,8 +23,8 @@ import com.mongodb.DBObject; */ public interface IndexDefinition { - DBObject getIndexKeys(); + DBObject getIndexKeys(); - DBObject getIndexOptions(); + DBObject getIndexOptions(); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDirection.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDirection.java index 45fcd503f..09b991539 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDirection.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexDirection.java @@ -20,6 +20,5 @@ package org.springframework.data.document.mongodb.index; * @author Jon Brisbin */ public enum IndexDirection { - ASCENDING, - DESCENDING; + ASCENDING, DESCENDING; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexPredicate.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexPredicate.java index 41f64cc65..83cba5cd8 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexPredicate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/IndexPredicate.java @@ -21,31 +21,31 @@ package org.springframework.data.document.mongodb.index; */ public abstract class IndexPredicate { - private String name; - private IndexDirection direction = IndexDirection.ASCENDING; - private boolean unique = false; + private String name; + private IndexDirection direction = IndexDirection.ASCENDING; + private boolean unique = false; - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public IndexDirection getDirection() { - return direction; - } + public IndexDirection getDirection() { + return direction; + } - public void setDirection(IndexDirection direction) { - this.direction = direction; - } + public void setDirection(IndexDirection direction) { + this.direction = direction; + } - public boolean isUnique() { - return unique; - } + public boolean isUnique() { + return unique; + } - public void setUnique(boolean unique) { - this.unique = unique; - } + public void setUnique(boolean unique) { + this.unique = unique; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/Indexed.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/Indexed.java index 863e66ab0..7f78ba05e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/Indexed.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/index/Indexed.java @@ -22,22 +22,23 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Mark a field to be indexed using MongoDB's indexing feature. + * Mark a field to be indexed using MongoDB's indexing feature. + * * @author Jon Brisbin */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Indexed { - boolean unique() default false; + boolean unique() default false; - IndexDirection direction() default IndexDirection.ASCENDING; + IndexDirection direction() default IndexDirection.ASCENDING; - boolean sparse() default false; + boolean sparse() default false; - boolean dropDups() default false; + boolean dropDups() default false; - String name() default ""; + String name() default ""; - String collection() default ""; + String collection() default ""; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentEntity.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentEntity.java index eb3a122c3..529e3d070 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentEntity.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentEntity.java @@ -22,58 +22,58 @@ import org.springframework.data.mapping.model.PersistentEntity; import org.springframework.data.util.TypeInformation; import org.springframework.util.StringUtils; - /** * Mongo specific {@link PersistentEntity} implementation that adds Mongo specific meta-data such as the collection name * and the like. - * + * * @author Jon Brisbin * @author Oliver Gierke */ -public class BasicMongoPersistentEntity extends BasicPersistentEntity implements MongoPersistentEntity { +public class BasicMongoPersistentEntity extends BasicPersistentEntity implements + MongoPersistentEntity { - private final String collection; - private final boolean isRootEntity; + private final String collection; + private final boolean isRootEntity; - /** - * Creates a new {@link BasicMongoPersistentEntity} with the given {@link TypeInformation}. Will - * default the collection name to the entities simple type name. - * - * @param typeInformation - */ - public BasicMongoPersistentEntity(TypeInformation typeInformation) { - - super(typeInformation); - - Class rawType = typeInformation.getType(); - String fallback = rawType.getSimpleName().toLowerCase(); - - if (rawType.isAnnotationPresent(Document.class)) { - Document d = rawType.getAnnotation(Document.class); - this.collection = StringUtils.hasText(d.collection()) ? d.collection() : fallback; - this.isRootEntity = true; - } else { - this.collection = fallback; - this.isRootEntity = false; - } - } + /** + * Creates a new {@link BasicMongoPersistentEntity} with the given {@link TypeInformation}. Will default the + * collection name to the entities simple type name. + * + * @param typeInformation + */ + public BasicMongoPersistentEntity(TypeInformation typeInformation) { - /** - * Returns the collection the entity should be stored in. - * - * @return - */ - public String getCollection() { - return collection; - } + super(typeInformation); - /* (non-Javadoc) - * @see org.springframework.data.mapping.BasicPersistentEntity#verify() - */ - @Override - public void verify() { - if (isRootEntity && idProperty == null) { - throw new MappingException(String.format("Root entity %s has to have an id property!", getType().getName())); - } - } + Class rawType = typeInformation.getType(); + String fallback = rawType.getSimpleName().toLowerCase(); + + if (rawType.isAnnotationPresent(Document.class)) { + Document d = rawType.getAnnotation(Document.class); + this.collection = StringUtils.hasText(d.collection()) ? d.collection() : fallback; + this.isRootEntity = true; + } else { + this.collection = fallback; + this.isRootEntity = false; + } + } + + /** + * Returns the collection the entity should be stored in. + * + * @return + */ + public String getCollection() { + return collection; + } + + /* (non-Javadoc) + * @see org.springframework.data.mapping.BasicPersistentEntity#verify() + */ + @Override + public void verify() { + if (isRootEntity && idProperty == null) { + throw new MappingException(String.format("Root entity %s has to have an id property!", getType().getName())); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentProperty.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentProperty.java index 1251531bc..251889e66 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentProperty.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/BasicMongoPersistentProperty.java @@ -28,76 +28,73 @@ import org.springframework.data.mapping.model.Association; import com.mongodb.DBObject; /** - * Mongo specific - * {@link org.springframework.data.mapping.model.PersistentProperty} - * implementation. - * + * Mongo specific {@link org.springframework.data.mapping.model.PersistentProperty} implementation. + * * @author Oliver Gierke */ -public class BasicMongoPersistentProperty extends AnnotationBasedPersistentProperty implements MongoPersistentProperty { +public class BasicMongoPersistentProperty extends AnnotationBasedPersistentProperty implements + MongoPersistentProperty { - private static final Set> SUPPORTED_ID_TYPES = new HashSet>(); - private static final Set SUPPORTED_ID_PROPERTY_NAMES = new HashSet(); + private static final Set> SUPPORTED_ID_TYPES = new HashSet>(); + private static final Set SUPPORTED_ID_PROPERTY_NAMES = new HashSet(); - static { - SUPPORTED_ID_TYPES.add(ObjectId.class); - SUPPORTED_ID_TYPES.add(String.class); - SUPPORTED_ID_TYPES.add(BigInteger.class); + static { + SUPPORTED_ID_TYPES.add(ObjectId.class); + SUPPORTED_ID_TYPES.add(String.class); + SUPPORTED_ID_TYPES.add(BigInteger.class); - SUPPORTED_ID_PROPERTY_NAMES.add("id"); - SUPPORTED_ID_PROPERTY_NAMES.add("_id"); - } + SUPPORTED_ID_PROPERTY_NAMES.add("id"); + SUPPORTED_ID_PROPERTY_NAMES.add("_id"); + } - /** - * Creates a new {@link BasicMongoPersistentProperty}. - * - * @param field - * @param propertyDescriptor - * @param owningTypeInformation - */ - public BasicMongoPersistentProperty(Field field, - PropertyDescriptor propertyDescriptor, MongoPersistentEntity owner) { - super(field, propertyDescriptor, owner); - } - - /* (non-Javadoc) - * @see org.springframework.data.mapping.FooBasicPersistentProperty#isAssociation() - */ - @Override - public boolean isAssociation() { - return field.isAnnotationPresent(DBRef.class) || super.isAssociation(); - } + /** + * Creates a new {@link BasicMongoPersistentProperty}. + * + * @param field + * @param propertyDescriptor + * @param owningTypeInformation + */ + public BasicMongoPersistentProperty(Field field, PropertyDescriptor propertyDescriptor, MongoPersistentEntity owner) { + super(field, propertyDescriptor, owner); + } - /** - * Also considers fields as id that are of supported id type and name. - * - * @see #SUPPORTED_ID_PROPERTY_NAMES - * @see #SUPPORTED_ID_TYPES - */ - @Override - public boolean isIdProperty() { - if (super.isIdProperty()) { - return true; - } + /* (non-Javadoc) + * @see org.springframework.data.mapping.FooBasicPersistentProperty#isAssociation() + */ + @Override + public boolean isAssociation() { + return field.isAnnotationPresent(DBRef.class) || super.isAssociation(); + } - return SUPPORTED_ID_TYPES.contains(field.getType()) - && SUPPORTED_ID_PROPERTY_NAMES.contains(field.getName()); - } - - /** - * Returns the key to be used to store the value of the property inside a Mongo {@link DBObject}. - * - * @return - */ - public String getKey() { - return isIdProperty() ? "_id" : getName(); - } - - /* (non-Javadoc) - * @see org.springframework.data.mapping.AbstractPersistentProperty#createAssociation() - */ - @Override - protected Association createAssociation() { - return new Association(this, null); - } + /** + * Also considers fields as id that are of supported id type and name. + * + * @see #SUPPORTED_ID_PROPERTY_NAMES + * @see #SUPPORTED_ID_TYPES + */ + @Override + public boolean isIdProperty() { + if (super.isIdProperty()) { + return true; + } + + return SUPPORTED_ID_TYPES.contains(field.getType()) && SUPPORTED_ID_PROPERTY_NAMES.contains(field.getName()); + } + + /** + * Returns the key to be used to store the value of the property inside a Mongo {@link DBObject}. + * + * @return + */ + public String getKey() { + return isIdProperty() ? "_id" : getName(); + } + + /* (non-Javadoc) + * @see org.springframework.data.mapping.AbstractPersistentProperty#createAssociation() + */ + @Override + protected Association createAssociation() { + return new Association(this, null); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/DBRef.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/DBRef.java index 1bb9ae07d..b032607c9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/DBRef.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/DBRef.java @@ -24,20 +24,19 @@ import java.lang.annotation.Target; import org.springframework.data.annotation.Reference; /** - * An annotation that indicates the annotated field is to be stored using a com.mongodb.DBRef + * An annotation that indicates the annotated field is to be stored using a com.mongodb.DBRef + * * @author Jon Brisbin */ @Retention(RetentionPolicy.RUNTIME) -@Target({ - ElementType.FIELD -}) +@Target({ ElementType.FIELD }) @Reference public @interface DBRef { - String collection() default ""; + String collection() default ""; - String id() default ""; + String id() default ""; - String db() default ""; + String db() default ""; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/Document.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/Document.java index e0a3d32e3..6784b0280 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/Document.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/Document.java @@ -25,15 +25,14 @@ import org.springframework.data.annotation.Persistent; /** * Identifies a domain object to be persisted to MongoDB. + * * @author Jon Brisbin */ @Persistent @Retention(RetentionPolicy.RUNTIME) -@Target({ - ElementType.TYPE -}) +@Target({ ElementType.TYPE }) public @interface Document { - String collection() default ""; + String collection() default ""; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoMappingContext.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoMappingContext.java index d2fc701f5..074528971 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoMappingContext.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoMappingContext.java @@ -31,30 +31,31 @@ import org.springframework.data.util.TypeInformation; * @author Jon Brisbin */ public class MongoMappingContext extends AbstractMappingContext, MongoPersistentProperty> { - public MongoMappingContext() { - augmentSimpleTypes(); - } + public MongoMappingContext() { + augmentSimpleTypes(); + } - protected void augmentSimpleTypes() { - // Augment simpleTypes with MongoDB-specific classes - Set> simpleTypes = MappingBeanHelper.getSimpleTypes(); - simpleTypes.add(com.mongodb.DBRef.class); - simpleTypes.add(ObjectId.class); - simpleTypes.add(CodeWScope.class); - simpleTypes.add(Character.class); - simpleTypes.add(BigInteger.class); - } + protected void augmentSimpleTypes() { + // Augment simpleTypes with MongoDB-specific classes + Set> simpleTypes = MappingBeanHelper.getSimpleTypes(); + simpleTypes.add(com.mongodb.DBRef.class); + simpleTypes.add(ObjectId.class); + simpleTypes.add(CodeWScope.class); + simpleTypes.add(Character.class); + simpleTypes.add(BigInteger.class); + } - @Override - public MongoPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, BasicMongoPersistentEntity owner) { - return new BasicMongoPersistentProperty(field, descriptor, owner); - } - - /* (non-Javadoc) - * @see org.springframework.data.mapping.BasicMappingContext#createPersistentEntity(org.springframework.data.util.TypeInformation, org.springframework.data.mapping.model.MappingContext) - */ - @Override - protected BasicMongoPersistentEntity createPersistentEntity(TypeInformation typeInformation) { - return new BasicMongoPersistentEntity(typeInformation); - } + @Override + public MongoPersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, + BasicMongoPersistentEntity owner) { + return new BasicMongoPersistentProperty(field, descriptor, owner); + } + + /* (non-Javadoc) + * @see org.springframework.data.mapping.BasicMappingContext#createPersistentEntity(org.springframework.data.util.TypeInformation, org.springframework.data.mapping.model.MappingContext) + */ + @Override + protected BasicMongoPersistentEntity createPersistentEntity(TypeInformation typeInformation) { + return new BasicMongoPersistentEntity(typeInformation); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntity.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntity.java index 62ae6dc81..c4030a8b9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntity.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntity.java @@ -3,10 +3,10 @@ package org.springframework.data.document.mongodb.mapping; import org.springframework.data.mapping.model.PersistentEntity; /** - * + * * @author Oliver Gierke */ public interface MongoPersistentEntity extends PersistentEntity { - String getCollection(); + String getCollection(); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntityIndexCreator.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntityIndexCreator.java index 6a5ac5b52..4bb80be71 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntityIndexCreator.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/MongoPersistentEntityIndexCreator.java @@ -45,9 +45,9 @@ import org.springframework.util.Assert; import org.springframework.util.StringUtils; /** - * Component that inspects {@link BasicMongoPersistentEntity} instances contained in the given {@link MongoMappingContext} - * for indexing metadata and ensures the indexes to be available. - * + * Component that inspects {@link BasicMongoPersistentEntity} instances contained in the given + * {@link MongoMappingContext} for indexing metadata and ensures the indexes to be available. + * * @author Jon Brisbin * @author Oliver Gierke */ @@ -64,7 +64,7 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener entity : mappingContext.getPersistentEntities()) { checkForIndexes(entity); } @@ -92,7 +92,8 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener() { public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { DBObject defObj; @@ -163,7 +158,7 @@ public class MongoPersistentEntityIndexCreator implements ApplicationListener { - String getKey(); + String getKey(); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/SimpleMongoMappingContext.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/SimpleMongoMappingContext.java index 27a646e8e..1aa76afe6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/SimpleMongoMappingContext.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/SimpleMongoMappingContext.java @@ -27,79 +27,83 @@ import org.springframework.data.mapping.model.Association; import org.springframework.data.util.TypeInformation; /** - * + * * @author Oliver Gierke */ -public class SimpleMongoMappingContext extends AbstractMappingContext, MongoPersistentProperty> { +public class SimpleMongoMappingContext extends + AbstractMappingContext, MongoPersistentProperty> { - /* (non-Javadoc) - * @see org.springframework.data.mapping.BasicMappingContext#createPersistentEntity(org.springframework.data.util.TypeInformation) - */ - @Override - protected SimpleMongoPersistentEntity createPersistentEntity(TypeInformation typeInformation) { - return new SimpleMongoPersistentEntity(typeInformation); - } + /* (non-Javadoc) + * @see org.springframework.data.mapping.BasicMappingContext#createPersistentEntity(org.springframework.data.util.TypeInformation) + */ + @Override + protected SimpleMongoPersistentEntity createPersistentEntity(TypeInformation typeInformation) { + return new SimpleMongoPersistentEntity(typeInformation); + } - /* (non-Javadoc) - * @see org.springframework.data.mapping.BasicMappingContext#createPersistentProperty(java.lang.reflect.Field, java.beans.PropertyDescriptor, org.springframework.data.util.TypeInformation, org.springframework.data.mapping.BasicPersistentEntity) - */ - @Override - protected SimplePersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, SimpleMongoPersistentEntity owner) { - return new SimplePersistentProperty(field, descriptor, owner); - } - - static class SimplePersistentProperty extends AbstractPersistentProperty implements MongoPersistentProperty { - - private static final List ID_FIELD_NAMES = Arrays.asList("id", "_id"); + /* (non-Javadoc) + * @see org.springframework.data.mapping.BasicMappingContext#createPersistentProperty(java.lang.reflect.Field, java.beans.PropertyDescriptor, org.springframework.data.util.TypeInformation, org.springframework.data.mapping.BasicPersistentEntity) + */ + @Override + protected SimplePersistentProperty createPersistentProperty(Field field, PropertyDescriptor descriptor, + SimpleMongoPersistentEntity owner) { + return new SimplePersistentProperty(field, descriptor, owner); + } - /** - * Creates a new {@link SimplePersistentProperty}. - * - * @param field - * @param propertyDescriptor - * @param information - */ - public SimplePersistentProperty(Field field, PropertyDescriptor propertyDescriptor, MongoPersistentEntity owner) { - super(field, propertyDescriptor, owner); - } - - /* (non-Javadoc) - * @see org.springframework.data.mapping.BasicPersistentProperty#isIdProperty() - */ - public boolean isIdProperty() { - return ID_FIELD_NAMES.contains(field.getName()); - } - - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.mapping.MongoPersistentProperty#getKey() - */ - public String getKey() { - return isIdProperty() ? "_id" : getName(); - } - - /* (non-Javadoc) - * @see org.springframework.data.mapping.AbstractPersistentProperty#createAssociation() - */ - @Override - protected Association createAssociation() { - return new Association(this, null); - } - } - - static class SimpleMongoPersistentEntity extends BasicPersistentEntity implements MongoPersistentEntity { + static class SimplePersistentProperty extends AbstractPersistentProperty implements + MongoPersistentProperty { - /** - * @param information - */ - public SimpleMongoPersistentEntity(TypeInformation information) { - super(information); - } + private static final List ID_FIELD_NAMES = Arrays.asList("id", "_id"); - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.mapping.MongoPersistentEntity#getCollection() - */ - public String getCollection() { - return getType().getSimpleName(); - } - } + /** + * Creates a new {@link SimplePersistentProperty}. + * + * @param field + * @param propertyDescriptor + * @param information + */ + public SimplePersistentProperty(Field field, PropertyDescriptor propertyDescriptor, MongoPersistentEntity owner) { + super(field, propertyDescriptor, owner); + } + + /* (non-Javadoc) + * @see org.springframework.data.mapping.BasicPersistentProperty#isIdProperty() + */ + public boolean isIdProperty() { + return ID_FIELD_NAMES.contains(field.getName()); + } + + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.mapping.MongoPersistentProperty#getKey() + */ + public String getKey() { + return isIdProperty() ? "_id" : getName(); + } + + /* (non-Javadoc) + * @see org.springframework.data.mapping.AbstractPersistentProperty#createAssociation() + */ + @Override + protected Association createAssociation() { + return new Association(this, null); + } + } + + static class SimpleMongoPersistentEntity extends BasicPersistentEntity implements + MongoPersistentEntity { + + /** + * @param information + */ + public SimpleMongoPersistentEntity(TypeInformation information) { + super(information); + } + + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.mapping.MongoPersistentEntity#getCollection() + */ + public String getCollection() { + return getType().getSimpleName(); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AbstractMappingEventListener.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AbstractMappingEventListener.java index f2015f3e3..dafb7d8f1 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AbstractMappingEventListener.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AbstractMappingEventListener.java @@ -27,59 +27,59 @@ import org.springframework.context.ApplicationListener; */ public abstract class AbstractMappingEventListener implements ApplicationListener { - protected final Log log = LogFactory.getLog(getClass()); + protected final Log log = LogFactory.getLog(getClass()); - @SuppressWarnings({"unchecked"}) - public void onApplicationEvent(T appEvent) { - if (appEvent instanceof MongoMappingEvent) { - try { - MongoMappingEvent event = (MongoMappingEvent) appEvent; - if (event instanceof BeforeConvertEvent) { - onBeforeConvert(event.getSource()); - } else if (event instanceof BeforeSaveEvent) { - onBeforeSave(event.getSource(), event.getDBObject()); - } else if (event instanceof AfterSaveEvent) { - onAfterSave(event.getSource(), event.getDBObject()); - } else if (event instanceof AfterLoadEvent) { - onAfterLoad((DBObject) event.getSource()); - } else if (event instanceof AfterConvertEvent) { - onAfterConvert(event.getDBObject(), event.getSource()); - } - } catch (ClassCastException e) { - // Not a mapping event for this entity, apparently. - // Just ignore it for now. - } - } - } + @SuppressWarnings({ "unchecked" }) + public void onApplicationEvent(T appEvent) { + if (appEvent instanceof MongoMappingEvent) { + try { + MongoMappingEvent event = (MongoMappingEvent) appEvent; + if (event instanceof BeforeConvertEvent) { + onBeforeConvert(event.getSource()); + } else if (event instanceof BeforeSaveEvent) { + onBeforeSave(event.getSource(), event.getDBObject()); + } else if (event instanceof AfterSaveEvent) { + onAfterSave(event.getSource(), event.getDBObject()); + } else if (event instanceof AfterLoadEvent) { + onAfterLoad((DBObject) event.getSource()); + } else if (event instanceof AfterConvertEvent) { + onAfterConvert(event.getDBObject(), event.getSource()); + } + } catch (ClassCastException e) { + // Not a mapping event for this entity, apparently. + // Just ignore it for now. + } + } + } - public void onBeforeConvert(E source) { - if (log.isDebugEnabled()) { - log.debug("onBeforeConvert(" + source + ")"); - } - } + public void onBeforeConvert(E source) { + if (log.isDebugEnabled()) { + log.debug("onBeforeConvert(" + source + ")"); + } + } - public void onBeforeSave(E source, DBObject dbo) { - if (log.isDebugEnabled()) { - log.debug("onBeforeSave(" + source + ", " + dbo + ")"); - } - } + public void onBeforeSave(E source, DBObject dbo) { + if (log.isDebugEnabled()) { + log.debug("onBeforeSave(" + source + ", " + dbo + ")"); + } + } - public void onAfterSave(E source, DBObject dbo) { - if (log.isDebugEnabled()) { - log.debug("onAfterSave(" + source + ", " + dbo + ")"); - } - } + public void onAfterSave(E source, DBObject dbo) { + if (log.isDebugEnabled()) { + log.debug("onAfterSave(" + source + ", " + dbo + ")"); + } + } - public void onAfterLoad(DBObject dbo) { - if (log.isDebugEnabled()) { - log.debug("onAfterLoad(" + dbo + ")"); - } - } + public void onAfterLoad(DBObject dbo) { + if (log.isDebugEnabled()) { + log.debug("onAfterLoad(" + dbo + ")"); + } + } - public void onAfterConvert(DBObject dbo, E source) { - if (log.isDebugEnabled()) { - log.debug("onAfterConvert(" + dbo + "," + source + ")"); - } - } + public void onAfterConvert(DBObject dbo, E source) { + if (log.isDebugEnabled()) { + log.debug("onAfterConvert(" + dbo + "," + source + ")"); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterConvertEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterConvertEvent.java index 913d8be16..091deadbe 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterConvertEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterConvertEvent.java @@ -23,10 +23,10 @@ import com.mongodb.DBObject; */ public class AfterConvertEvent extends MongoMappingEvent { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AfterConvertEvent(DBObject dbo, E source) { - super(source, dbo); - } + public AfterConvertEvent(DBObject dbo, E source) { + super(source, dbo); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterLoadEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterLoadEvent.java index 1c7d4fecc..98268180b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterLoadEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterLoadEvent.java @@ -21,9 +21,9 @@ package org.springframework.data.document.mongodb.mapping.event; */ public class AfterLoadEvent extends MongoMappingEvent { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AfterLoadEvent(DBObject dbo) { - super(dbo, null); - } + public AfterLoadEvent(DBObject dbo) { + super(dbo, null); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterSaveEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterSaveEvent.java index 264abc9d6..72d900030 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterSaveEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/AfterSaveEvent.java @@ -24,10 +24,10 @@ import org.springframework.data.mapping.model.PersistentEntity; */ public class AfterSaveEvent extends MongoMappingEvent { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public AfterSaveEvent(E source, DBObject dbo) { - super(source, dbo); - } + public AfterSaveEvent(E source, DBObject dbo) { + super(source, dbo); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeConvertEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeConvertEvent.java index 50bd43c0b..6813d0eb5 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeConvertEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeConvertEvent.java @@ -21,10 +21,9 @@ package org.springframework.data.document.mongodb.mapping.event; */ public class BeforeConvertEvent extends MongoMappingEvent { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public BeforeConvertEvent(T source) { - super(source, null); - } + public BeforeConvertEvent(T source) { + super(source, null); + } } - diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeSaveEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeSaveEvent.java index 6d5bff3b1..9de80489d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeSaveEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/BeforeSaveEvent.java @@ -23,10 +23,10 @@ import com.mongodb.DBObject; */ public class BeforeSaveEvent extends MongoMappingEvent { - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - public BeforeSaveEvent(E source, DBObject dbo) { - super(source, dbo); - } + public BeforeSaveEvent(E source, DBObject dbo) { + super(source, dbo); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/MongoMappingEvent.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/MongoMappingEvent.java index 8f9938782..2a4c81e03 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/MongoMappingEvent.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/mapping/event/MongoMappingEvent.java @@ -24,21 +24,21 @@ import org.springframework.context.ApplicationEvent; */ public class MongoMappingEvent extends ApplicationEvent { - private static final long serialVersionUID = 1L; - private final DBObject dbo; + private static final long serialVersionUID = 1L; + private final DBObject dbo; - public MongoMappingEvent(T source, DBObject dbo) { - super(source); - this.dbo = dbo; - } + public MongoMappingEvent(T source, DBObject dbo) { + super(source); + this.dbo = dbo; + } - public DBObject getDBObject() { - return dbo; - } + public DBObject getDBObject() { + return dbo; + } - @SuppressWarnings({"unchecked"}) - @Override - public T getSource() { - return (T) super.getSource(); - } + @SuppressWarnings({ "unchecked" }) + @Override + public T getSource() { + return (T) super.getSource(); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AbstractMonitor.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AbstractMonitor.java index ec94808b8..99cf8dfdf 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AbstractMonitor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AbstractMonitor.java @@ -25,47 +25,48 @@ import org.springframework.data.document.mongodb.MongoDbUtils; /** * Base class to encapsulate common configuration settings when connecting to a database - * + * * @author Mark Pollack */ public abstract class AbstractMonitor { - private final Log logger = LogFactory.getLog(getClass()); + private final Log logger = LogFactory.getLog(getClass()); - protected Mongo mongo; - private String username; - private String password; + protected Mongo mongo; + private String username; + private String password; + /** + * Sets the username to use to connect to the Mongo database + * + * @param username + * The username to use + */ + public void setUsername(String username) { + this.username = username; + } - /** - * Sets the username to use to connect to the Mongo database - * - * @param username The username to use - */ - public void setUsername(String username) { - this.username = username; - } + /** + * Sets the password to use to authenticate with the Mongo database. + * + * @param password + * The password to use + */ + public void setPassword(String password) { - /** - * Sets the password to use to authenticate with the Mongo database. - * - * @param password The password to use - */ - public void setPassword(String password) { + this.password = password; + } - this.password = password; - } + public CommandResult getServerStatus() { + CommandResult result = getDb("admin").command("serverStatus"); + if (!result.ok()) { + logger.error("Could not query for server status. Command Result = " + result); + throw new MongoException("could not query for server status. Command Result = " + result); + } + return result; + } - public CommandResult getServerStatus() { - CommandResult result = getDb("admin").command("serverStatus"); - if (!result.ok()) { - logger.error("Could not query for server status. Command Result = " + result); - throw new MongoException("could not query for server status. Command Result = " + result); - } - return result; - } - - public DB getDb(String databaseName) { - return MongoDbUtils.getDB(mongo, databaseName, username, password == null ? null : password.toCharArray()); - } + public DB getDb(String databaseName) { + return MongoDbUtils.getDB(mongo, databaseName, username, password == null ? null : password.toCharArray()); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AssertMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AssertMetrics.java index fd7ad4c39..7c8edbc32 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AssertMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/AssertMetrics.java @@ -23,45 +23,45 @@ import org.springframework.jmx.support.MetricType; /** * JMX Metrics for assertions - * + * * @author Mark Pollack */ @ManagedResource(description = "Assertion Metrics") public class AssertMetrics extends AbstractMonitor { - public AssertMetrics(Mongo mongo) { - this.mongo = mongo; - } + public AssertMetrics(Mongo mongo) { + this.mongo = mongo; + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Regular") - public int getRegular() { - return getBtree("regular"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Regular") + public int getRegular() { + return getBtree("regular"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Warning") - public int getWarning() { - return getBtree("warning"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Warning") + public int getWarning() { + return getBtree("warning"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Msg") - public int getMsg() { - return getBtree("msg"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Msg") + public int getMsg() { + return getBtree("msg"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "User") - public int getUser() { - return getBtree("user"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "User") + public int getUser() { + return getBtree("user"); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Rollovers") - public int getRollovers() { - return getBtree("rollovers"); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Rollovers") + public int getRollovers() { + return getBtree("rollovers"); + } - private int getBtree(String key) { - DBObject asserts = (DBObject) getServerStatus().get("asserts"); - //Class c = btree.get(key).getClass(); - return (Integer) asserts.get(key); - } + private int getBtree(String key) { + DBObject asserts = (DBObject) getServerStatus().get("asserts"); + // Class c = btree.get(key).getClass(); + return (Integer) asserts.get(key); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BackgroundFlushingMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BackgroundFlushingMetrics.java index 4958e7354..da761a2ac 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BackgroundFlushingMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BackgroundFlushingMetrics.java @@ -25,54 +25,51 @@ import org.springframework.jmx.support.MetricType; /** * JMX Metrics for Background Flushing - * + * * @author Mark Pollack */ @ManagedResource(description = "Background Flushing Metrics") public class BackgroundFlushingMetrics extends AbstractMonitor { + public BackgroundFlushingMetrics(Mongo mongo) { + this.mongo = mongo; + } - public BackgroundFlushingMetrics(Mongo mongo) { - this.mongo = mongo; - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Flushes") + public int getFlushes() { + return getFlushingData("flushes", java.lang.Integer.class); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Flushes") - public int getFlushes() { - return getFlushingData("flushes", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total ms", unit = "ms") + public int getTotalMs() { + return getFlushingData("total_ms", java.lang.Integer.class); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total ms", unit = "ms") - public int getTotalMs() { - return getFlushingData("total_ms", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Average ms", unit = "ms") + public double getAverageMs() { + return getFlushingData("average_ms", java.lang.Double.class); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Average ms", unit = "ms") - public double getAverageMs() { - return getFlushingData("average_ms", java.lang.Double.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last Ms", unit = "ms") + public int getLastMs() { + return getFlushingData("last_ms", java.lang.Integer.class); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last Ms", unit = "ms") - public int getLastMs() { - return getFlushingData("last_ms", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last finished") + public Date getLastFinished() { + return getLast(); + } + @SuppressWarnings("unchecked") + private T getFlushingData(String key, Class targetClass) { + DBObject mem = (DBObject) getServerStatus().get("backgroundFlushing"); + return (T) mem.get(key); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Last finished") - public Date getLastFinished() { - return getLast(); - } - - @SuppressWarnings("unchecked") - private T getFlushingData(String key, Class targetClass) { - DBObject mem = (DBObject) getServerStatus().get("backgroundFlushing"); - return (T) mem.get(key); - } - - private Date getLast() { - DBObject bgFlush = (DBObject) getServerStatus().get("backgroundFlushing"); - Date lastFinished = (Date) bgFlush.get("last_finished"); - return lastFinished; - } - + private Date getLast() { + DBObject bgFlush = (DBObject) getServerStatus().get("backgroundFlushing"); + Date lastFinished = (Date) bgFlush.get("last_finished"); + return lastFinished; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BtreeIndexCounters.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BtreeIndexCounters.java index 4a7d0f5e2..20fdf426e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BtreeIndexCounters.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/BtreeIndexCounters.java @@ -23,52 +23,52 @@ import org.springframework.jmx.support.MetricType; /** * JMX Metrics for B-tree index counters - * + * * @author Mark Pollack */ @ManagedResource(description = "Btree Metrics") public class BtreeIndexCounters extends AbstractMonitor { - public BtreeIndexCounters(Mongo mongo) { - this.mongo = mongo; - } + public BtreeIndexCounters(Mongo mongo) { + this.mongo = mongo; + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Accesses") - public int getAccesses() { - return getBtree("accesses"); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Accesses") + public int getAccesses() { + return getBtree("accesses"); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Hits") - public int getHits() { - return getBtree("hits"); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Hits") + public int getHits() { + return getBtree("hits"); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Misses") - public int getMisses() { - return getBtree("misses"); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Misses") + public int getMisses() { + return getBtree("misses"); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resets") - public int getResets() { - return getBtree("resets"); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resets") + public int getResets() { + return getBtree("resets"); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Miss Ratio") - public int getMissRatio() { - return getBtree("missRatio"); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Miss Ratio") + public int getMissRatio() { + return getBtree("missRatio"); + } - private int getBtree(String key) { - DBObject indexCounters = (DBObject) getServerStatus().get("indexCounters"); - if (indexCounters.get("note") != null) { - String message = (String) indexCounters.get("note"); - if (message.contains("not supported")) { - return -1; - } - } - DBObject btree = (DBObject) indexCounters.get("btree"); - //Class c = btree.get(key).getClass(); - return (Integer) btree.get(key); - } + private int getBtree(String key) { + DBObject indexCounters = (DBObject) getServerStatus().get("indexCounters"); + if (indexCounters.get("note") != null) { + String message = (String) indexCounters.get("note"); + if (message.contains("not supported")) { + return -1; + } + } + DBObject btree = (DBObject) indexCounters.get("btree"); + // Class c = btree.get(key).getClass(); + return (Integer) btree.get(key); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ConnectionMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ConnectionMetrics.java index 4b5cdd988..911b6840a 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ConnectionMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ConnectionMetrics.java @@ -23,31 +23,31 @@ import org.springframework.jmx.support.MetricType; /** * JMX Metrics for Connections - * + * * @author Mark Pollack */ @ManagedResource(description = "Connection metrics") public class ConnectionMetrics extends AbstractMonitor { - public ConnectionMetrics(Mongo mongo) { - this.mongo = mongo; - } + public ConnectionMetrics(Mongo mongo) { + this.mongo = mongo; + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Connections") - public int getCurrent() { - return getConnectionData("current", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Connections") + public int getCurrent() { + return getConnectionData("current", java.lang.Integer.class); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Available Connections") - public int getAvailable() { - return getConnectionData("available", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Available Connections") + public int getAvailable() { + return getConnectionData("available", java.lang.Integer.class); + } - @SuppressWarnings("unchecked") - private T getConnectionData(String key, Class targetClass) { - DBObject mem = (DBObject) getServerStatus().get("connections"); - //Class c = mem.get(key).getClass(); - return (T) mem.get(key); - } + @SuppressWarnings("unchecked") + private T getConnectionData(String key, Class targetClass) { + DBObject mem = (DBObject) getServerStatus().get("connections"); + // Class c = mem.get(key).getClass(); + return (T) mem.get(key); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/GlobalLockMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/GlobalLockMetrics.java index c157ac188..282bfe70e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/GlobalLockMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/GlobalLockMetrics.java @@ -23,57 +23,55 @@ import org.springframework.jmx.support.MetricType; /** * JMX Metrics for Global Locks - * + * * @author Mark Pollack */ @ManagedResource(description = "Global Lock Metrics") public class GlobalLockMetrics extends AbstractMonitor { + public GlobalLockMetrics(Mongo mongo) { + this.mongo = mongo; + } - public GlobalLockMetrics(Mongo mongo) { - this.mongo = mongo; - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total time") + public double getTotalTime() { + return getGlobalLockData("totalTime", java.lang.Double.class); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total time") - public double getTotalTime() { - return getGlobalLockData("totalTime", java.lang.Double.class); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Lock time", unit = "s") + public double getLockTime() { + return getGlobalLockData("lockTime", java.lang.Double.class); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Lock time", unit = "s") - public double getLockTime() { - return getGlobalLockData("lockTime", java.lang.Double.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Lock time") + public double getLockTimeRatio() { + return getGlobalLockData("ratio", java.lang.Double.class); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Lock time") - public double getLockTimeRatio() { - return getGlobalLockData("ratio", java.lang.Double.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Queue") + public int getCurrentQueueTotal() { + return getCurrentQueue("total"); + } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Reader Queue") + public int getCurrentQueueReaders() { + return getCurrentQueue("readers"); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Queue") - public int getCurrentQueueTotal() { - return getCurrentQueue("total"); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Writer Queue") + public int getCurrentQueueWriters() { + return getCurrentQueue("writers"); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Reader Queue") - public int getCurrentQueueReaders() { - return getCurrentQueue("readers"); - } + @SuppressWarnings("unchecked") + private T getGlobalLockData(String key, Class targetClass) { + DBObject globalLock = (DBObject) getServerStatus().get("globalLock"); + return (T) globalLock.get(key); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Writer Queue") - public int getCurrentQueueWriters() { - return getCurrentQueue("writers"); - } - - @SuppressWarnings("unchecked") - private T getGlobalLockData(String key, Class targetClass) { - DBObject globalLock = (DBObject) getServerStatus().get("globalLock"); - return (T) globalLock.get(key); - } - - private int getCurrentQueue(String key) { - DBObject globalLock = (DBObject) getServerStatus().get("globalLock"); - DBObject currentQueue = (DBObject) globalLock.get("currentQueue"); - return (Integer) currentQueue.get(key); - } + private int getCurrentQueue(String key) { + DBObject globalLock = (DBObject) getServerStatus().get("globalLock"); + DBObject currentQueue = (DBObject) globalLock.get("currentQueue"); + return (Integer) currentQueue.get(key); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/MemoryMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/MemoryMetrics.java index b9d329945..4b6e6fa87 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/MemoryMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/MemoryMetrics.java @@ -23,50 +23,46 @@ import org.springframework.jmx.support.MetricType; /** * JMX Metrics for Memory - * + * * @author Mark Pollack */ @ManagedResource(description = "Memory Metrics") public class MemoryMetrics extends AbstractMonitor { + public MemoryMetrics(Mongo mongo) { + this.mongo = mongo; + } - public MemoryMetrics(Mongo mongo) { - this.mongo = mongo; - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Memory address size") + public int getBits() { + return getMemData("bits", java.lang.Integer.class); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Memory address size") - public int getBits() { - return getMemData("bits", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resident in Physical Memory", unit = "MB") + public int getResidentSpace() { + return getMemData("resident", java.lang.Integer.class); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Resident in Physical Memory", unit = "MB") - public int getResidentSpace() { - return getMemData("resident", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Virtual Address Space", unit = "MB") + public int getVirtualAddressSpace() { + return getMemData("virtual", java.lang.Integer.class); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Virtual Address Space", unit = "MB") - public int getVirtualAddressSpace() { - return getMemData("virtual", java.lang.Integer.class); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Is memory info supported on this platform") + public boolean getMemoryInfoSupported() { + return getMemData("supported", java.lang.Boolean.class); + } - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Is memory info supported on this platform") - public boolean getMemoryInfoSupported() { - return getMemData("supported", java.lang.Boolean.class); - } - - - @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Memory Mapped Space", unit = "MB") - public int getMemoryMappedSpace() { - return getMemData("mapped", java.lang.Integer.class); - } - - - @SuppressWarnings("unchecked") - private T getMemData(String key, Class targetClass) { - DBObject mem = (DBObject) getServerStatus().get("mem"); - //Class c = mem.get(key).getClass(); - return (T) mem.get(key); - } + @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Memory Mapped Space", unit = "MB") + public int getMemoryMappedSpace() { + return getMemData("mapped", java.lang.Integer.class); + } + @SuppressWarnings("unchecked") + private T getMemData(String key, Class targetClass) { + DBObject mem = (DBObject) getServerStatus().get("mem"); + // Class c = mem.get(key).getClass(); + return (T) mem.get(key); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/OperationCounters.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/OperationCounters.java index 297d60fa6..6b3bcae0f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/OperationCounters.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/OperationCounters.java @@ -23,49 +23,48 @@ import org.springframework.jmx.support.MetricType; /** * JMX Metrics for Operation counters - * + * * @author Mark Pollack */ @ManagedResource(description = "Operation Counters") public class OperationCounters extends AbstractMonitor { + public OperationCounters(Mongo mongo) { + this.mongo = mongo; + } - public OperationCounters(Mongo mongo) { - this.mongo = mongo; - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Insert operation count") + public int getInsertCount() { + return getOpCounter("insert"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Insert operation count") - public int getInsertCount() { - return getOpCounter("insert"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Query operation count") + public int getQueryCount() { + return getOpCounter("query"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Query operation count") - public int getQueryCount() { - return getOpCounter("query"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Update operation count") + public int getUpdateCount() { + return getOpCounter("update"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Update operation count") - public int getUpdateCount() { - return getOpCounter("update"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Delete operation count") + public int getDeleteCount() { + return getOpCounter("delete"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Delete operation count") - public int getDeleteCount() { - return getOpCounter("delete"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "GetMore operation count") + public int getGetMoreCount() { + return getOpCounter("getmore"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "GetMore operation count") - public int getGetMoreCount() { - return getOpCounter("getmore"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Command operation count") + public int getCommandCount() { + return getOpCounter("command"); + } - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Command operation count") - public int getCommandCount() { - return getOpCounter("command"); - } - - private int getOpCounter(String key) { - DBObject opCounters = (DBObject) getServerStatus().get("opcounters"); - return (Integer) opCounters.get(key); - } + private int getOpCounter(String key) { + DBObject opCounters = (DBObject) getServerStatus().get("opcounters"); + return (Integer) opCounters.get(key); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ServerInfo.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ServerInfo.java index 4e79a84f6..69fc4b3bc 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ServerInfo.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/ServerInfo.java @@ -26,41 +26,39 @@ import org.springframework.jmx.support.MetricType; /** * Expose basic server information via JMX - * + * * @author Mark Pollack */ @ManagedResource(description = "Server Information") public class ServerInfo extends AbstractMonitor { - public ServerInfo(Mongo mongo) { - this.mongo = mongo; - } + public ServerInfo(Mongo mongo) { + this.mongo = mongo; + } + @ManagedOperation(description = "Server host name") + public String getHostName() throws UnknownHostException { + return InetAddress.getLocalHost().getHostName(); + } - @ManagedOperation(description = "Server host name") - public String getHostName() throws UnknownHostException { - return InetAddress.getLocalHost().getHostName(); - } + @ManagedMetric(displayName = "Uptime Estimate") + public double getUptimeEstimate() { + return (Double) getServerStatus().get("uptimeEstimate"); + } - @ManagedMetric(displayName = "Uptime Estimate") - public double getUptimeEstimate() { - return (Double) getServerStatus().get("uptimeEstimate"); - } + @ManagedOperation(description = "MongoDB Server Version") + public String getVersion() { + return (String) getServerStatus().get("version"); + } - @ManagedOperation(description = "MongoDB Server Version") - public String getVersion() { - return (String) getServerStatus().get("version"); - } + @ManagedOperation(description = "Local Time") + public String getLocalTime() { + return (String) getServerStatus().get("localTime"); + } - @ManagedOperation(description = "Local Time") - public String getLocalTime() { - return (String) getServerStatus().get("localTime"); - } - - - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Server uptime in seconds", unit = "seconds") - public double getUptime() { - return (Double) getServerStatus().get("uptime"); - } + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Server uptime in seconds", unit = "seconds") + public double getUptime() { + return (Double) getServerStatus().get("uptime"); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/package-info.java index 6ccef7a13..4467b5ec6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/monitor/package-info.java @@ -2,3 +2,4 @@ * MongoDB specific JMX monitoring support. */ package org.springframework.data.document.mongodb.monitor; + diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/package-info.java index 9f38f637e..716e2e20e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/package-info.java @@ -2,3 +2,4 @@ * MongoDB core support. */ package org.springframework.data.document.mongodb; + diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicQuery.java index 19bfe22a7..b42685764 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/BasicQuery.java @@ -20,72 +20,72 @@ import com.mongodb.util.JSON; public class BasicQuery extends Query { - private DBObject queryObject = null; + private DBObject queryObject = null; - private DBObject fieldsObject = null; + private DBObject fieldsObject = null; - private DBObject sortObject = null; + private DBObject sortObject = null; - private int skip; + private int skip; - private int limit; + private int limit; - public BasicQuery(String query) { - super(); - this.queryObject = (DBObject) JSON.parse(query); - } + public BasicQuery(String query) { + super(); + this.queryObject = (DBObject) JSON.parse(query); + } - public BasicQuery(DBObject queryObject) { - super(); - this.queryObject = queryObject; - } + public BasicQuery(DBObject queryObject) { + super(); + this.queryObject = queryObject; + } - public BasicQuery(String query, String fields) { - this.queryObject = (DBObject) JSON.parse(query); - this.fieldsObject = (DBObject) JSON.parse(fields); - } + public BasicQuery(String query, String fields) { + this.queryObject = (DBObject) JSON.parse(query); + this.fieldsObject = (DBObject) JSON.parse(fields); + } - public BasicQuery(DBObject queryObject, DBObject fieldsObject) { - this.queryObject = queryObject; - this.fieldsObject = fieldsObject; - } + public BasicQuery(DBObject queryObject, DBObject fieldsObject) { + this.queryObject = queryObject; + this.fieldsObject = fieldsObject; + } - @Override - public Query addCriteria(Criteria criteria) { - this.queryObject.putAll(criteria.getCriteriaObject()); - return this; - } + @Override + public Query addCriteria(Criteria criteria) { + this.queryObject.putAll(criteria.getCriteriaObject()); + return this; + } - public DBObject getQueryObject() { - return this.queryObject; - } + public DBObject getQueryObject() { + return this.queryObject; + } - public DBObject getFieldsObject() { - return fieldsObject; - } + public DBObject getFieldsObject() { + return fieldsObject; + } - public DBObject getSortObject() { - return sortObject; - } + public DBObject getSortObject() { + return sortObject; + } - public void setSortObject(DBObject sortObject) { - this.sortObject = sortObject; - } + public void setSortObject(DBObject sortObject) { + this.sortObject = sortObject; + } - public int getSkip() { - return skip; - } + public int getSkip() { + return skip; + } - public void setSkip(int skip) { - this.skip = skip; - } + public void setSkip(int skip) { + this.skip = skip; + } - public int getLimit() { - return this.limit; - } + public int getLimit() { + return this.limit; + } - public void setLimit(int limit) { - this.limit = limit; - } + public void setLimit(int limit) { + this.limit = limit; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java index a4bbb68aa..698bdf2fb 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Criteria.java @@ -30,398 +30,401 @@ import org.springframework.data.document.mongodb.geo.Point; import org.springframework.util.Assert; public class Criteria implements CriteriaDefinition { - - /** - * Custom "not-null" object as we have to be able to work with {@literal null} values as well. - */ - private static final Object NOT_SET = new Object(); - private String key; + /** + * Custom "not-null" object as we have to be able to work with {@literal null} values as well. + */ + private static final Object NOT_SET = new Object(); - private List criteriaChain; + private String key; - private LinkedHashMap criteria = new LinkedHashMap(); + private List criteriaChain; - private Object isValue = NOT_SET; + private LinkedHashMap criteria = new LinkedHashMap(); - public Criteria(String key) { - this.criteriaChain = new ArrayList(); - this.criteriaChain.add(this); - this.key = key; - } + private Object isValue = NOT_SET; - protected Criteria(List criteriaChain, String key) { - this.criteriaChain = criteriaChain; - this.criteriaChain.add(this); - this.key = key; - } - - /** - * Static factory method to create a Criteria using the provided key - * - * @param key - * @return - */ - public static Criteria where(String key) { - return new Criteria(key); - } - - public static Criteria whereId() { - return new Criteria("id"); - } - - /** - * Static factory method to create a Criteria using the provided key - * - * @param key - * @return - */ - public Criteria and(String key) { - return new Criteria(this.criteriaChain, key); - } - - /** - * Creates a criterion using equality - * - * @param o - * @return - */ - public Criteria is(Object o) { - if (isValue != NOT_SET) { - throw new InvalidDocumentStoreApiUsageException( - "Multiple 'is' values declared. You need to use 'and' with multiple criteria"); - } - if (this.criteria.size() > 0 && "$not".equals(this.criteria.keySet().toArray()[this.criteria.size() - 1])) { - throw new InvalidDocumentStoreApiUsageException( - "Invalid query: 'not' can't be used with 'is' - use 'ne' instead."); - } - this.isValue = o; - return this; - } - - /** - * Creates a criterion using the $ne operator - * - * @param o - * @return - */ - public Criteria ne(Object o) { - criteria.put("$ne", o); - return this; - } - - /** - * Creates a criterion using the $lt operator - * - * @param o - * @return - */ - public Criteria lt(Object o) { - criteria.put("$lt", o); - return this; - } - - /** - * Creates a criterion using the $lte operator - * - * @param o - * @return - */ - public Criteria lte(Object o) { - criteria.put("$lte", o); - return this; - } - - /** - * Creates a criterion using the $gt operator - * - * @param o - * @return - */ - public Criteria gt(Object o) { - criteria.put("$gt", o); - return this; - } - - /** - * Creates a criterion using the $gte operator - * - * @param o - * @return - */ - public Criteria gte(Object o) { - criteria.put("$gte", o); - return this; - } - - /** - * Creates a criterion using the $in operator - * - * @param o the values to match against - * @return - */ - public Criteria in(Object... o) { - if (o.length > 1 && o[1] instanceof Collection) { - throw new InvalidDocumentStoreApiUsageException("You can only pass in one argument of type " + o[1].getClass().getName()); + public Criteria(String key) { + this.criteriaChain = new ArrayList(); + this.criteriaChain.add(this); + this.key = key; } - criteria.put("$in", o); - return this; - } - /** - * Creates a criterion using the $in operator - * - * @param c the collection containing the values to match against - * @return - */ - public Criteria in(Collection c) { - System.out.println(c.getClass()); - criteria.put("$in", c.toArray()); - return this; - } + protected Criteria(List criteriaChain, String key) { + this.criteriaChain = criteriaChain; + this.criteriaChain.add(this); + this.key = key; + } - /** - * Creates a criterion using the $nin operator - * - * @param o - * @return - */ - public Criteria nin(Object... o) { - criteria.put("$nin", o); - return this; - } + /** + * Static factory method to create a Criteria using the provided key + * + * @param key + * @return + */ + public static Criteria where(String key) { + return new Criteria(key); + } - /** - * Creates a criterion using the $mod operator - * - * @param value - * @param remainder - * @return - */ - public Criteria mod(Number value, Number remainder) { - List l = new ArrayList(); - l.add(value); - l.add(remainder); - criteria.put("$mod", l); - return this; - } + public static Criteria whereId() { + return new Criteria("id"); + } - /** - * Creates a criterion using the $all operator - * - * @param o - * @return - */ - public Criteria all(Object... o) { - criteria.put("$all", o); - return this; - } + /** + * Static factory method to create a Criteria using the provided key + * + * @param key + * @return + */ + public Criteria and(String key) { + return new Criteria(this.criteriaChain, key); + } - /** - * Creates a criterion using the $size operator - * - * @param s - * @return - */ - public Criteria size(int s) { - criteria.put("$size", s); - return this; - } + /** + * Creates a criterion using equality + * + * @param o + * @return + */ + public Criteria is(Object o) { + if (isValue != NOT_SET) { + throw new InvalidDocumentStoreApiUsageException( + "Multiple 'is' values declared. You need to use 'and' with multiple criteria"); + } + if (this.criteria.size() > 0 && "$not".equals(this.criteria.keySet().toArray()[this.criteria.size() - 1])) { + throw new InvalidDocumentStoreApiUsageException( + "Invalid query: 'not' can't be used with 'is' - use 'ne' instead."); + } + this.isValue = o; + return this; + } - /** - * Creates a criterion using the $exists operator - * - * @param b - * @return - */ - public Criteria exists(boolean b) { - criteria.put("$exists", b); - return this; - } + /** + * Creates a criterion using the $ne operator + * + * @param o + * @return + */ + public Criteria ne(Object o) { + criteria.put("$ne", o); + return this; + } - /** - * Creates a criterion using the $type operator - * - * @param t - * @return - */ - public Criteria type(int t) { - criteria.put("$type", t); - return this; - } + /** + * Creates a criterion using the $lt operator + * + * @param o + * @return + */ + public Criteria lt(Object o) { + criteria.put("$lt", o); + return this; + } - /** - * Creates a criterion using the $not meta operator which affects the clause directly following - * - * @return - */ - public Criteria not() { - criteria.put("$not", null); - return this; - } + /** + * Creates a criterion using the $lte operator + * + * @param o + * @return + */ + public Criteria lte(Object o) { + criteria.put("$lte", o); + return this; + } - /** - * Creates a criterion using a $regex - * - * @param re - * @return - */ - public Criteria regex(String re) { - criteria.put("$regex", re); - return this; - } + /** + * Creates a criterion using the $gt operator + * + * @param o + * @return + */ + public Criteria gt(Object o) { + criteria.put("$gt", o); + return this; + } - /** - * Creates a geospatial criterion using a $within $center operation - * - * @param circle - * must not be {@literal null} - * @return - */ - public Criteria withinCenter(Circle circle) { - Assert.notNull(circle); - LinkedList list = new LinkedList(); - list.addLast(circle.getCenter().asArray()); - list.add(circle.getRadius()); - criteria.put("$within", new BasicDBObject("$center", list)); - return this; - } + /** + * Creates a criterion using the $gte operator + * + * @param o + * @return + */ + public Criteria gte(Object o) { + criteria.put("$gte", o); + return this; + } - /** - * Creates a geospatial criterion using a $within $center operation. This is only available for Mongo 1.7 and higher. - * - * @param circle - * must not be {@literal null} - * @return - */ - public Criteria withinCenterSphere(Circle circle) { - Assert.notNull(circle); - LinkedList list = new LinkedList(); - list.addLast(circle.getCenter().asArray()); - list.add(circle.getRadius()); - criteria.put("$within", new BasicDBObject("$centerSphere", list)); - return this; - } + /** + * Creates a criterion using the $in operator + * + * @param o + * the values to match against + * @return + */ + public Criteria in(Object... o) { + if (o.length > 1 && o[1] instanceof Collection) { + throw new InvalidDocumentStoreApiUsageException("You can only pass in one argument of type " + + o[1].getClass().getName()); + } + criteria.put("$in", o); + return this; + } - /** - * Creates a geospatial criterion using a $within $box operation - * - * @param box - * @return - */ - public Criteria withinBox(Box box) { - Assert.notNull(box); - LinkedList list = new LinkedList(); - list.addLast(box.getLowerLeft().asArray()); - list.addLast(box.getUpperRight().asArray()); - criteria.put("$within", new BasicDBObject("$box", list)); - return this; - } + /** + * Creates a criterion using the $in operator + * + * @param c + * the collection containing the values to match against + * @return + */ + public Criteria in(Collection c) { + System.out.println(c.getClass()); + criteria.put("$in", c.toArray()); + return this; + } - /** - * Creates a geospatial criterion using a $near operation - * - * @param point - * must not be {@literal null} - * @return - */ - public Criteria near(Point point) { - Assert.notNull(point); - criteria.put("$near", point.asArray()); - return this; - } + /** + * Creates a criterion using the $nin operator + * + * @param o + * @return + */ + public Criteria nin(Object... o) { + criteria.put("$nin", o); + return this; + } - /** - * Creates a geospatial criterion using a $nearSphere operation. This is only available for Mongo 1.7 and higher. - * - * @param point - * must not be {@literal null} - * @return - */ - public Criteria nearSphere(Point point) { - Assert.notNull(point); - criteria.put("$nearSphere", point.asArray()); - return this; - } + /** + * Creates a criterion using the $mod operator + * + * @param value + * @param remainder + * @return + */ + public Criteria mod(Number value, Number remainder) { + List l = new ArrayList(); + l.add(value); + l.add(remainder); + criteria.put("$mod", l); + return this; + } - /** - * Creates a geospatical criterion using a $maxDistance operation, for use with $near - * - * @param maxDistance - * @return - */ - public Criteria maxDistance(double maxDistance) { - criteria.put("$maxDistance", maxDistance); - return this; - } + /** + * Creates a criterion using the $all operator + * + * @param o + * @return + */ + public Criteria all(Object... o) { + criteria.put("$all", o); + return this; + } - /** - * Creates a criterion using the $elemMatch operator - * - * @param c - * @return - */ - public Criteria elemMatch(Criteria c) { - criteria.put("$elemMatch", c.getCriteriaObject()); - return this; - } + /** + * Creates a criterion using the $size operator + * + * @param s + * @return + */ + public Criteria size(int s) { + criteria.put("$size", s); + return this; + } - /** - * Creates an or query using the $or operator for all of the provided queries - * - * @param queries - */ - public void or(List queries) { - criteria.put("$or", queries); - } + /** + * Creates a criterion using the $exists operator + * + * @param b + * @return + */ + public Criteria exists(boolean b) { + criteria.put("$exists", b); + return this; + } - public String getKey() { - return this.key; - } + /** + * Creates a criterion using the $type operator + * + * @param t + * @return + */ + public Criteria type(int t) { + criteria.put("$type", t); + return this; + } - /* - * (non-Javadoc) - * - * @see org.springframework.datastore.document.mongodb.query.Criteria# - * getCriteriaObject(java.lang.String) - */ - public DBObject getCriteriaObject() { - if (this.criteriaChain.size() == 1) { - return criteriaChain.get(0).getSingleCriteriaObject(); - } else { - DBObject criteriaObject = new BasicDBObject(); - for (Criteria c : this.criteriaChain) { - criteriaObject.putAll(c.getSingleCriteriaObject()); - } - return criteriaObject; - } - } + /** + * Creates a criterion using the $not meta operator which affects the clause directly following + * + * @return + */ + public Criteria not() { + criteria.put("$not", null); + return this; + } - protected DBObject getSingleCriteriaObject() { - DBObject dbo = new BasicDBObject(); - boolean not = false; - for (String k : this.criteria.keySet()) { - if (not) { - DBObject notDbo = new BasicDBObject(); - notDbo.put(k, this.criteria.get(k)); - dbo.put("$not", notDbo); - not = false; - } else { - if ("$not".equals(k)) { - not = true; - } else { - dbo.put(k, this.criteria.get(k)); - } - } - } - DBObject queryCriteria = new BasicDBObject(); - if (isValue != NOT_SET) { - queryCriteria.put(this.key, this.isValue); - queryCriteria.putAll(dbo); - } else { - queryCriteria.put(this.key, dbo); - } - return queryCriteria; - } + /** + * Creates a criterion using a $regex + * + * @param re + * @return + */ + public Criteria regex(String re) { + criteria.put("$regex", re); + return this; + } + + /** + * Creates a geospatial criterion using a $within $center operation + * + * @param circle + * must not be {@literal null} + * @return + */ + public Criteria withinCenter(Circle circle) { + Assert.notNull(circle); + LinkedList list = new LinkedList(); + list.addLast(circle.getCenter().asArray()); + list.add(circle.getRadius()); + criteria.put("$within", new BasicDBObject("$center", list)); + return this; + } + + /** + * Creates a geospatial criterion using a $within $center operation. This is only available for Mongo 1.7 and higher. + * + * @param circle + * must not be {@literal null} + * @return + */ + public Criteria withinCenterSphere(Circle circle) { + Assert.notNull(circle); + LinkedList list = new LinkedList(); + list.addLast(circle.getCenter().asArray()); + list.add(circle.getRadius()); + criteria.put("$within", new BasicDBObject("$centerSphere", list)); + return this; + } + + /** + * Creates a geospatial criterion using a $within $box operation + * + * @param box + * @return + */ + public Criteria withinBox(Box box) { + Assert.notNull(box); + LinkedList list = new LinkedList(); + list.addLast(box.getLowerLeft().asArray()); + list.addLast(box.getUpperRight().asArray()); + criteria.put("$within", new BasicDBObject("$box", list)); + return this; + } + + /** + * Creates a geospatial criterion using a $near operation + * + * @param point + * must not be {@literal null} + * @return + */ + public Criteria near(Point point) { + Assert.notNull(point); + criteria.put("$near", point.asArray()); + return this; + } + + /** + * Creates a geospatial criterion using a $nearSphere operation. This is only available for Mongo 1.7 and higher. + * + * @param point + * must not be {@literal null} + * @return + */ + public Criteria nearSphere(Point point) { + Assert.notNull(point); + criteria.put("$nearSphere", point.asArray()); + return this; + } + + /** + * Creates a geospatical criterion using a $maxDistance operation, for use with $near + * + * @param maxDistance + * @return + */ + public Criteria maxDistance(double maxDistance) { + criteria.put("$maxDistance", maxDistance); + return this; + } + + /** + * Creates a criterion using the $elemMatch operator + * + * @param c + * @return + */ + public Criteria elemMatch(Criteria c) { + criteria.put("$elemMatch", c.getCriteriaObject()); + return this; + } + + /** + * Creates an or query using the $or operator for all of the provided queries + * + * @param queries + */ + public void or(List queries) { + criteria.put("$or", queries); + } + + public String getKey() { + return this.key; + } + + /* + * (non-Javadoc) + * + * @see org.springframework.datastore.document.mongodb.query.Criteria# + * getCriteriaObject(java.lang.String) + */ + public DBObject getCriteriaObject() { + if (this.criteriaChain.size() == 1) { + return criteriaChain.get(0).getSingleCriteriaObject(); + } else { + DBObject criteriaObject = new BasicDBObject(); + for (Criteria c : this.criteriaChain) { + criteriaObject.putAll(c.getSingleCriteriaObject()); + } + return criteriaObject; + } + } + + protected DBObject getSingleCriteriaObject() { + DBObject dbo = new BasicDBObject(); + boolean not = false; + for (String k : this.criteria.keySet()) { + if (not) { + DBObject notDbo = new BasicDBObject(); + notDbo.put(k, this.criteria.get(k)); + dbo.put("$not", notDbo); + not = false; + } else { + if ("$not".equals(k)) { + not = true; + } else { + dbo.put(k, this.criteria.get(k)); + } + } + } + DBObject queryCriteria = new BasicDBObject(); + if (isValue != NOT_SET) { + queryCriteria.put(this.key, this.isValue); + queryCriteria.putAll(dbo); + } else { + queryCriteria.put(this.key, dbo); + } + return queryCriteria; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/CriteriaDefinition.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/CriteriaDefinition.java index 3616cb41a..c99748964 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/CriteriaDefinition.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/CriteriaDefinition.java @@ -19,6 +19,6 @@ import com.mongodb.DBObject; public interface CriteriaDefinition { - DBObject getCriteriaObject(); + DBObject getCriteriaObject(); } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Field.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Field.java index 2940192e8..f26f3b532 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Field.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Field.java @@ -21,41 +21,40 @@ import java.util.Map; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; - public class Field { - private Map criteria = new HashMap(); + private Map criteria = new HashMap(); - private Map slices = new HashMap(); + private Map slices = new HashMap(); - public Field include(String key) { - criteria.put(key, Integer.valueOf(1)); - return this; - } + public Field include(String key) { + criteria.put(key, Integer.valueOf(1)); + return this; + } - public Field exclude(String key) { - criteria.put(key, Integer.valueOf(0)); - return this; - } + public Field exclude(String key) { + criteria.put(key, Integer.valueOf(0)); + return this; + } - public Field slice(String key, int size) { - slices.put(key, Integer.valueOf(size)); - return this; - } + public Field slice(String key, int size) { + slices.put(key, Integer.valueOf(size)); + return this; + } - public Field slice(String key, int offset, int size) { - slices.put(key, new Integer[]{Integer.valueOf(offset), Integer.valueOf(size)}); - return this; - } + public Field slice(String key, int offset, int size) { + slices.put(key, new Integer[] { Integer.valueOf(offset), Integer.valueOf(size) }); + return this; + } - public DBObject getFieldsObject() { - DBObject dbo = new BasicDBObject(); - for (String k : criteria.keySet()) { - dbo.put(k, (criteria.get(k))); - } - for (String k : slices.keySet()) { - dbo.put(k, new BasicDBObject("$slice", (slices.get(k)))); - } - return dbo; - } + public DBObject getFieldsObject() { + DBObject dbo = new BasicDBObject(); + for (String k : criteria.keySet()) { + dbo.put(k, (criteria.get(k))); + } + for (String k : slices.keySet()) { + dbo.put(k, new BasicDBObject("$slice", (slices.get(k)))); + } + return dbo; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/GeospatialIndex.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/GeospatialIndex.java index 5a6b27746..0ee9b9ecf 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/GeospatialIndex.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/GeospatialIndex.java @@ -20,74 +20,73 @@ import org.springframework.data.document.mongodb.index.IndexDefinition; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; - public class GeospatialIndex implements IndexDefinition { - private String keyField; + private String keyField; - private String name; + private String name; - private Integer min = null; + private Integer min = null; - private Integer max = null; - - private Integer bits = null; + private Integer max = null; - public GeospatialIndex(String key) { - keyField = key; - } + private Integer bits = null; - public GeospatialIndex named(String name) { - this.name = name; - return this; - } + public GeospatialIndex(String key) { + keyField = key; + } - public GeospatialIndex withMin(int min) { - this.min = Integer.valueOf(min); - return this; - } + public GeospatialIndex named(String name) { + this.name = name; + return this; + } - public GeospatialIndex withMax(int max) { - this.max = Integer.valueOf(max); - return this; - } + public GeospatialIndex withMin(int min) { + this.min = Integer.valueOf(min); + return this; + } - public GeospatialIndex withBits(int bits) { - this.bits = Integer.valueOf(bits); - return this; - } - - public DBObject getIndexKeys() { - DBObject dbo = new BasicDBObject(); - dbo.put(keyField, "2d"); - return dbo; - } + public GeospatialIndex withMax(int max) { + this.max = Integer.valueOf(max); + return this; + } - public DBObject getIndexOptions() { - if (name == null && min == null && max == null) { - return null; - } - DBObject dbo = new BasicDBObject(); - if (name != null) { - dbo.put("name", name); - } - if (min != null) { - dbo.put("min", min); - } - if (max != null) { - dbo.put("max", max); - } - if (bits != null) { - dbo.put("bits", bits); - } - return dbo; - } + public GeospatialIndex withBits(int bits) { + this.bits = Integer.valueOf(bits); + return this; + } - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return String.format("Geo index: %s - Options: %s", getIndexKeys(), getIndexOptions()); - } + public DBObject getIndexKeys() { + DBObject dbo = new BasicDBObject(); + dbo.put(keyField, "2d"); + return dbo; + } + + public DBObject getIndexOptions() { + if (name == null && min == null && max == null) { + return null; + } + DBObject dbo = new BasicDBObject(); + if (name != null) { + dbo.put("name", name); + } + if (min != null) { + dbo.put("min", min); + } + if (max != null) { + dbo.put("max", max); + } + if (bits != null) { + dbo.put("bits", bits); + } + return dbo; + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("Geo index: %s - Options: %s", getIndexKeys(), getIndexOptions()); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Index.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Index.java index de7be56eb..36a92cce3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Index.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Index.java @@ -23,88 +23,86 @@ import org.springframework.data.document.mongodb.index.IndexDefinition; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; - public class Index implements IndexDefinition { - public enum Duplicates { - RETAIN, - DROP - } + public enum Duplicates { + RETAIN, DROP + } - private Map fieldSpec = new HashMap(); + private Map fieldSpec = new HashMap(); - private String name; + private String name; - private boolean unique = false; + private boolean unique = false; - private boolean dropDuplicates = false; - - private boolean sparse = false; + private boolean dropDuplicates = false; - public Index() { - } + private boolean sparse = false; - public Index(String key, Order order) { - fieldSpec.put(key, order); - } + public Index() { + } - public Index on(String key, Order order) { - fieldSpec.put(key, order); - return this; - } + public Index(String key, Order order) { + fieldSpec.put(key, order); + } - public Index named(String name) { - this.name = name; - return this; - } + public Index on(String key, Order order) { + fieldSpec.put(key, order); + return this; + } - public Index unique() { - this.unique = true; - return this; - } - - public Index sparse() { - this.sparse = true; - return this; - } + public Index named(String name) { + this.name = name; + return this; + } - public Index unique(Duplicates duplicates) { - if (duplicates == Duplicates.DROP) { - this.dropDuplicates = true; - } - return unique(); - } + public Index unique() { + this.unique = true; + return this; + } - public DBObject getIndexKeys() { - DBObject dbo = new BasicDBObject(); - for (String k : fieldSpec.keySet()) { - dbo.put(k, (fieldSpec.get(k).equals(Order.ASCENDING) ? 1 : -1)); - } - return dbo; - } + public Index sparse() { + this.sparse = true; + return this; + } - public DBObject getIndexOptions() { - if (name == null && !unique) { - return null; - } - DBObject dbo = new BasicDBObject(); - if (name != null) { - dbo.put("name", name); - } - if (unique) { - dbo.put("unique", true); - } - if (dropDuplicates) { - dbo.put("dropDups", true); - } - if (sparse) { - dbo.put("sparse", true); - } - return dbo; - } - - @Override - public String toString() { - return String.format("Index: %s - Options: %s", getIndexKeys(), getIndexOptions()); - } + public Index unique(Duplicates duplicates) { + if (duplicates == Duplicates.DROP) { + this.dropDuplicates = true; + } + return unique(); + } + + public DBObject getIndexKeys() { + DBObject dbo = new BasicDBObject(); + for (String k : fieldSpec.keySet()) { + dbo.put(k, (fieldSpec.get(k).equals(Order.ASCENDING) ? 1 : -1)); + } + return dbo; + } + + public DBObject getIndexOptions() { + if (name == null && !unique) { + return null; + } + DBObject dbo = new BasicDBObject(); + if (name != null) { + dbo.put("name", name); + } + if (unique) { + dbo.put("unique", true); + } + if (dropDuplicates) { + dbo.put("dropDups", true); + } + if (sparse) { + dbo.put("sparse", true); + } + return dbo; + } + + @Override + public String toString() { + return String.format("Index: %s - Options: %s", getIndexKeys(), getIndexOptions()); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Order.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Order.java index b254caee3..40d8a770b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Order.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Order.java @@ -17,9 +17,9 @@ package org.springframework.data.document.mongodb.query; /** * An enum that specifies the ordering for sort or index specifications - * + * * @author trisberg */ public enum Order { - ASCENDING, DESCENDING + ASCENDING, DESCENDING } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Query.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Query.java index d671534da..7d663145c 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Query.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Query.java @@ -30,7 +30,7 @@ public class Query { /** * Static factory method to create a Query using the provided criteria - * + * * @param critera * @return */ diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java index c04831a72..06c040db3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/QueryMapper.java @@ -31,7 +31,7 @@ import org.springframework.util.Assert; /** * A helper class to encapsulate any modifications of a Query object before it gets submitted to the database. - * + * * @author Jon Brisbin * @author Oliver Gierke */ @@ -41,7 +41,7 @@ public class QueryMapper { /** * Creates a new {@link QueryMapper} with the given {@link MongoConverter}. - * + * * @param converter */ public QueryMapper(MongoConverter converter) { @@ -52,7 +52,7 @@ public class QueryMapper { /** * Replaces the property keys used in the given {@link DBObject} with the appropriate keys by using the * {@link PersistentEntity} metadata. - * + * * @param query * @param entity * @return diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Sort.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Sort.java index a4e61ae09..d47192533 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Sort.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Sort.java @@ -21,29 +21,28 @@ import java.util.Map; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; - public class Sort { - private Map fieldSpec = new HashMap(); + private Map fieldSpec = new HashMap(); - public Sort() { - } + public Sort() { + } - public Sort(String key, Order order) { - fieldSpec.put(key, order); - } + public Sort(String key, Order order) { + fieldSpec.put(key, order); + } - public Sort on(String key, Order order) { - fieldSpec.put(key, order); - return this; - } + public Sort on(String key, Order order) { + fieldSpec.put(key, order); + return this; + } - public DBObject getSortObject() { - DBObject dbo = new BasicDBObject(); - for (String k : fieldSpec.keySet()) { - dbo.put(k, (fieldSpec.get(k).equals(Order.ASCENDING) ? 1 : -1)); - } - return dbo; - } + public DBObject getSortObject() { + DBObject dbo = new BasicDBObject(); + for (String k : fieldSpec.keySet()) { + dbo.put(k, (fieldSpec.get(k).equals(Order.ASCENDING) ? 1 : -1)); + } + return dbo; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Update.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Update.java index 11b310b4b..32aa3c66a 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Update.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/Update.java @@ -32,7 +32,7 @@ public class Update { /** * Static factory method to create an Update using the provided key - * + * * @param key * @return */ @@ -42,7 +42,7 @@ public class Update { /** * Update using the $set update modifier - * + * * @param key * @param value * @return @@ -54,7 +54,7 @@ public class Update { /** * Update using the $unset update modifier - * + * * @param key * @return */ @@ -65,7 +65,7 @@ public class Update { /** * Update using the $inc update modifier - * + * * @param key * @param inc * @return @@ -77,7 +77,7 @@ public class Update { /** * Update using the $push update modifier - * + * * @param key * @param value * @return @@ -89,7 +89,7 @@ public class Update { /** * Update using the $pushAll update modifier - * + * * @param key * @param values * @return @@ -107,7 +107,7 @@ public class Update { /** * Update using the $addToSet update modifier - * + * * @param key * @param value * @return @@ -119,20 +119,19 @@ public class Update { /** * Update using the $pop update modifier - * + * * @param key * @param pos * @return */ public Update pop(String key, Position pos) { - addMultiFieldOperation("$pop", key, - (pos == Position.FIRST ? -1 : 1)); + addMultiFieldOperation("$pop", key, (pos == Position.FIRST ? -1 : 1)); return this; } /** * Update using the $pull update modifier - * + * * @param key * @param value * @return @@ -144,7 +143,7 @@ public class Update { /** * Update using the $pullAll update modifier - * + * * @param key * @param values * @return @@ -162,7 +161,7 @@ public class Update { /** * Update using the $rename update modifier - * + * * @param oldName * @param newName * @return @@ -181,8 +180,7 @@ public class Update { } @SuppressWarnings("unchecked") - protected void addMultiFieldOperation(String operator, String key, - Object value) { + protected void addMultiFieldOperation(String operator, String key, Object value) { Object existingValue = this.modifierOps.get(operator); LinkedHashMap keyValueMap; if (existingValue == null) { @@ -192,8 +190,8 @@ public class Update { if (existingValue instanceof LinkedHashMap) { keyValueMap = (LinkedHashMap) existingValue; } else { - throw new InvalidDataAccessApiUsageException("Modifier Operations should be a LinkedHashMap but was " + - existingValue.getClass()); + throw new InvalidDataAccessApiUsageException("Modifier Operations should be a LinkedHashMap but was " + + existingValue.getClass()); } } keyValueMap.put(key, value); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/package-info.java index 993e03849..49bdc8c00 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/query/package-info.java @@ -2,3 +2,4 @@ * MongoDB specific query and update support. */ package org.springframework.data.document.mongodb.query; + diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/AbstractMongoQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/AbstractMongoQuery.java index c65e110dc..f0665b4a3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/AbstractMongoQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/AbstractMongoQuery.java @@ -34,165 +34,165 @@ import org.springframework.util.Assert; /** * Base class for {@link RepositoryQuery} implementations for Mongo. - * + * * @author Oliver Gierke */ public abstract class AbstractMongoQuery implements RepositoryQuery { - private final MongoQueryMethod method; - private final MongoTemplate template; + private final MongoQueryMethod method; + private final MongoTemplate template; - /** - * Creates a new {@link AbstractMongoQuery} from the given {@link MongoQueryMethod} and {@link MongoTemplate}. - * - * @param method - * @param template - */ - public AbstractMongoQuery(MongoQueryMethod method, MongoTemplate template) { + /** + * Creates a new {@link AbstractMongoQuery} from the given {@link MongoQueryMethod} and {@link MongoTemplate}. + * + * @param method + * @param template + */ + public AbstractMongoQuery(MongoQueryMethod method, MongoTemplate template) { - Assert.notNull(template); - Assert.notNull(method); + Assert.notNull(template); + Assert.notNull(method); - this.method = method; - this.template = template; - } + this.method = method; + this.template = template; + } - /* (non-Javadoc) - * @see org.springframework.data.repository.query.RepositoryQuery#getQueryMethod() - */ - public MongoQueryMethod getQueryMethod() { + /* (non-Javadoc) + * @see org.springframework.data.repository.query.RepositoryQuery#getQueryMethod() + */ + public MongoQueryMethod getQueryMethod() { - return method; - } + return method; + } - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.query.RepositoryQuery#execute(java .lang.Object[]) - */ - public Object execute(Object[] parameters) { + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.query.RepositoryQuery#execute(java .lang.Object[]) + */ + public Object execute(Object[] parameters) { - ParameterAccessor accessor = new ParametersParameterAccessor(method.getParameters(), parameters); - Query query = createQuery(new ConvertingParameterAccessor(template.getConverter(), accessor)); + ParameterAccessor accessor = new ParametersParameterAccessor(method.getParameters(), parameters); + Query query = createQuery(new ConvertingParameterAccessor(template.getConverter(), accessor)); - switch (method.getType()) { - case COLLECTION: - return new CollectionExecution().execute(query); - case PAGING: - return new PagedExecution(accessor.getPageable()).execute(query); - default: - return new SingleEntityExecution().execute(query); - } - } + switch (method.getType()) { + case COLLECTION: + return new CollectionExecution().execute(query); + case PAGING: + return new PagedExecution(accessor.getPageable()).execute(query); + default: + return new SingleEntityExecution().execute(query); + } + } - /** - * Create a {@link Query} instance using the given {@link ParameterAccessor} - * - * @param accessor - * @param converter - * @return - */ - protected abstract Query createQuery(ConvertingParameterAccessor accessor); + /** + * Create a {@link Query} instance using the given {@link ParameterAccessor} + * + * @param accessor + * @param converter + * @return + */ + protected abstract Query createQuery(ConvertingParameterAccessor accessor); - private abstract class Execution { + private abstract class Execution { - abstract Object execute(Query query); + abstract Object execute(Query query); - protected List readCollection(Query query) { + protected List readCollection(Query query) { - MongoEntityInformation metadata = method.getEntityInformation(); + MongoEntityInformation metadata = method.getEntityInformation(); - String collectionName = metadata.getCollectionName(); - return template.find(collectionName, query, metadata.getJavaType()); - } - } + String collectionName = metadata.getCollectionName(); + return template.find(collectionName, query, metadata.getJavaType()); + } + } - /** - * {@link Execution} for collection returning queries. - * - * @author Oliver Gierke - */ - class CollectionExecution extends Execution { + /** + * {@link Execution} for collection returning queries. + * + * @author Oliver Gierke + */ + class CollectionExecution extends Execution { - /* - * (non-Javadoc) - * - * @see org.springframework.data.document.mongodb.repository.MongoQuery.Execution #execute(com.mongodb.DBObject) - */ - @Override - public Object execute(Query query) { + /* + * (non-Javadoc) + * + * @see org.springframework.data.document.mongodb.repository.MongoQuery.Execution #execute(com.mongodb.DBObject) + */ + @Override + public Object execute(Query query) { - return readCollection(query); - } - } + return readCollection(query); + } + } - /** - * {@link Execution} for pagination queries. - * - * @author Oliver Gierke - */ - class PagedExecution extends Execution { + /** + * {@link Execution} for pagination queries. + * + * @author Oliver Gierke + */ + class PagedExecution extends Execution { - private final Pageable pageable; + private final Pageable pageable; - /** - * Creates a new {@link PagedExecution}. - * - * @param pageable - */ - public PagedExecution(Pageable pageable) { + /** + * Creates a new {@link PagedExecution}. + * + * @param pageable + */ + public PagedExecution(Pageable pageable) { - Assert.notNull(pageable); - this.pageable = pageable; - } + Assert.notNull(pageable); + this.pageable = pageable; + } - /* - * (non-Javadoc) - * - * @see org.springframework.data.document.mongodb.repository.MongoQuery.Execution #execute(com.mongodb.DBObject) - */ - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - Object execute(Query query) { + /* + * (non-Javadoc) + * + * @see org.springframework.data.document.mongodb.repository.MongoQuery.Execution #execute(com.mongodb.DBObject) + */ + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + Object execute(Query query) { - MongoEntityInformation metadata = method.getEntityInformation(); - int count = getCollectionCursor(metadata.getCollectionName(), query.getQueryObject()).count(); + MongoEntityInformation metadata = method.getEntityInformation(); + int count = getCollectionCursor(metadata.getCollectionName(), query.getQueryObject()).count(); - List result = template.find(metadata.getCollectionName(), applyPagination(query, pageable), - metadata.getJavaType()); + List result = template.find(metadata.getCollectionName(), applyPagination(query, pageable), + metadata.getJavaType()); - return new PageImpl(result, pageable, count); - } + return new PageImpl(result, pageable, count); + } - private DBCursor getCollectionCursor(String collectionName, final DBObject query) { + private DBCursor getCollectionCursor(String collectionName, final DBObject query) { - return template.execute(collectionName, new CollectionCallback() { + return template.execute(collectionName, new CollectionCallback() { - public DBCursor doInCollection(DBCollection collection) { + public DBCursor doInCollection(DBCollection collection) { - return collection.find(query); - } - }); - } - } + return collection.find(query); + } + }); + } + } - /** - * {@link Execution} to return a single entity. - * - * @author Oliver Gierke - */ - class SingleEntityExecution extends Execution { + /** + * {@link Execution} to return a single entity. + * + * @author Oliver Gierke + */ + class SingleEntityExecution extends Execution { - /* - * (non-Javadoc) - * - * @see org.springframework.data.document.mongodb.repository.MongoQuery.Execution #execute(com.mongodb.DBObject) - */ - @Override - Object execute(Query query) { + /* + * (non-Javadoc) + * + * @see org.springframework.data.document.mongodb.repository.MongoQuery.Execution #execute(com.mongodb.DBObject) + */ + @Override + Object execute(Query query) { - List result = readCollection(query); - return result.isEmpty() ? null : result.get(0); - } - } + List result = readCollection(query); + return result.isEmpty() ? null : result.get(0); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/ConvertingParameterAccessor.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/ConvertingParameterAccessor.java index 2bd5b8881..801f75c2e 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/ConvertingParameterAccessor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/ConvertingParameterAccessor.java @@ -28,160 +28,160 @@ import org.springframework.data.repository.query.ParameterAccessor; /** * Custom {@link ParameterAccessor} that uses a {@link MongoWriter} to serialize parameters into Mongo format. - * + * * @author Oliver Gierke */ public class ConvertingParameterAccessor implements ParameterAccessor { - - private final MongoWriter writer; - private final ParameterAccessor delegate; - /** - * Creates a new {@link ConvertingParameterAccessor} with the given {@link MongoWriter} and delegate. - * - * @param writer - */ - public ConvertingParameterAccessor(MongoWriter writer, ParameterAccessor delegate) { - this.writer = writer; - this.delegate = delegate; - } + private final MongoWriter writer; + private final ParameterAccessor delegate; - /* - * (non-Javadoc) - * - * @see java.lang.Iterable#iterator() - */ - public Iterator iterator() { - return new ConvertingIterator(delegate.iterator()); - } + /** + * Creates a new {@link ConvertingParameterAccessor} with the given {@link MongoWriter} and delegate. + * + * @param writer + */ + public ConvertingParameterAccessor(MongoWriter writer, ParameterAccessor delegate) { + this.writer = writer; + this.delegate = delegate; + } - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.query.ParameterAccessor#getPageable() - */ - public Pageable getPageable() { - return delegate.getPageable(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Iterable#iterator() + */ + public Iterator iterator() { + return new ConvertingIterator(delegate.iterator()); + } - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.query.ParameterAccessor#getSort() - */ - public Sort getSort() { - return delegate.getSort(); - } + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.query.ParameterAccessor#getPageable() + */ + public Pageable getPageable() { + return delegate.getPageable(); + } - /* (non-Javadoc) - * @see org.springframework.data.repository.query.ParameterAccessor#getBindableParameter(int) - */ - public Object getBindableValue(int index) { + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.query.ParameterAccessor#getSort() + */ + public Sort getSort() { + return delegate.getSort(); + } - return getConvertedValue(delegate.getBindableValue(index)); - } + /* (non-Javadoc) + * @see org.springframework.data.repository.query.ParameterAccessor#getBindableParameter(int) + */ + public Object getBindableValue(int index) { - /** - * Converts the given value with the underlying {@link MongoWriter}. - * - * @param value - * @return - */ - private Object getConvertedValue(Object value) { - - DBObject result = new BasicDBObject(); - writer.write(new ValueHolder(value), result); - return ((DBObject) result.get("value")).get("value"); - } + return getConvertedValue(delegate.getBindableValue(index)); + } - /** - * Custom {@link Iterator} to convert items before returning them. - * - * @author Oliver Gierke - */ - private class ConvertingIterator implements PotentiallyConvertingIterator { + /** + * Converts the given value with the underlying {@link MongoWriter}. + * + * @param value + * @return + */ + private Object getConvertedValue(Object value) { - private final Iterator delegate; + DBObject result = new BasicDBObject(); + writer.write(new ValueHolder(value), result); + return ((DBObject) result.get("value")).get("value"); + } - /** - * Creates a new {@link ConvertingIterator} for the given delegate. - * - * @param delegate - */ - public ConvertingIterator(Iterator delegate) { - this.delegate = delegate; - } + /** + * Custom {@link Iterator} to convert items before returning them. + * + * @author Oliver Gierke + */ + private class ConvertingIterator implements PotentiallyConvertingIterator { - /* - * (non-Javadoc) - * - * @see java.util.Iterator#hasNext() - */ - public boolean hasNext() { - return delegate.hasNext(); - } + private final Iterator delegate; - /* - * (non-Javadoc) - * - * @see java.util.Iterator#next() - */ - public Object next() { + /** + * Creates a new {@link ConvertingIterator} for the given delegate. + * + * @param delegate + */ + public ConvertingIterator(Iterator delegate) { + this.delegate = delegate; + } - return delegate.next(); - } - - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.repository.ConvertingParameterAccessor.PotentiallConvertingIterator#nextConverted() - */ - public Object nextConverted() { - - return getConvertedValue(next()); - } + /* + * (non-Javadoc) + * + * @see java.util.Iterator#hasNext() + */ + public boolean hasNext() { + return delegate.hasNext(); + } - /* - * (non-Javadoc) - * - * @see java.util.Iterator#remove() - */ - public void remove() { - delegate.remove(); - } - } + /* + * (non-Javadoc) + * + * @see java.util.Iterator#next() + */ + public Object next() { - /** - * Simple value holder class to allow conversion and accessing the converted value in a deterministic way. - * - * @author Oliver Gierke - */ - private static class ValueHolder { + return delegate.next(); + } - private Map value = new HashMap(); + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.repository.ConvertingParameterAccessor.PotentiallConvertingIterator#nextConverted() + */ + public Object nextConverted() { - public ValueHolder(Object value) { + return getConvertedValue(next()); + } - this.value.put("value", value); - } + /* + * (non-Javadoc) + * + * @see java.util.Iterator#remove() + */ + public void remove() { + delegate.remove(); + } + } - @SuppressWarnings("unused") - public Map getValue() { + /** + * Simple value holder class to allow conversion and accessing the converted value in a deterministic way. + * + * @author Oliver Gierke + */ + private static class ValueHolder { - return value; - } - } + private Map value = new HashMap(); - /** - * 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(); - } + public ValueHolder(Object value) { + + this.value.put("value", value); + } + + @SuppressWarnings("unused") + public Map getValue() { + + return value; + } + } + + /** + * 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(); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MappingMongoEntityInformation.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MappingMongoEntityInformation.java index 33773cc8c..4f5562816 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MappingMongoEntityInformation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MappingMongoEntityInformation.java @@ -23,61 +23,61 @@ import org.springframework.data.mapping.MappingBeanHelper; import org.springframework.data.repository.support.AbstractEntityInformation; /** - * {@link MongoEntityInformation} implementation using a {@link BasicMongoPersistentEntity} instance to lookup the necessary - * information. + * {@link MongoEntityInformation} implementation using a {@link BasicMongoPersistentEntity} instance to lookup the + * necessary information. * * @author Oliver Gierke */ public class MappingMongoEntityInformation extends AbstractEntityInformation - implements MongoEntityInformation { + implements MongoEntityInformation { - private final MongoPersistentEntity entityMetadata; + private final MongoPersistentEntity entityMetadata; - /** - * Creates a new {@link MappingMongoEntityInformation} for the given {@link MongoPersistentEntity}. - * - * @param domainClass - * @param entity - */ - public MappingMongoEntityInformation(MongoPersistentEntity entity) { - super(entity.getType()); - this.entityMetadata = entity; - } + /** + * Creates a new {@link MappingMongoEntityInformation} for the given {@link MongoPersistentEntity}. + * + * @param domainClass + * @param entity + */ + public MappingMongoEntityInformation(MongoPersistentEntity entity) { + super(entity.getType()); + this.entityMetadata = entity; + } - /* (non-Javadoc) - * @see org.springframework.data.repository.support.EntityInformation#getId(java.lang.Object) - */ - @SuppressWarnings("unchecked") - public ID getId(T entity) { + /* (non-Javadoc) + * @see org.springframework.data.repository.support.EntityInformation#getId(java.lang.Object) + */ + @SuppressWarnings("unchecked") + public ID getId(T entity) { - MongoPersistentProperty idProperty = entityMetadata.getIdProperty(); + MongoPersistentProperty idProperty = entityMetadata.getIdProperty(); - try { - return (ID) MappingBeanHelper.getProperty(entity, idProperty, idProperty.getType(), false); - } catch (Exception e) { - throw new RuntimeException(e); - } - } + try { + return (ID) MappingBeanHelper.getProperty(entity, idProperty, idProperty.getType(), false); + } catch (Exception e) { + throw new RuntimeException(e); + } + } - /* (non-Javadoc) - * @see org.springframework.data.repository.support.EntityInformation#getIdType() - */ - @SuppressWarnings("unchecked") - public Class getIdType() { - return (Class) entityMetadata.getIdProperty().getType(); - } + /* (non-Javadoc) + * @see org.springframework.data.repository.support.EntityInformation#getIdType() + */ + @SuppressWarnings("unchecked") + public Class getIdType() { + return (Class) entityMetadata.getIdProperty().getType(); + } - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.repository.MongoEntityInformation#getCollectionName() - */ - public String getCollectionName() { - return entityMetadata.getCollection(); - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.repository.MongoEntityInformation#getCollectionName() + */ + public String getCollectionName() { + return entityMetadata.getCollection(); + } - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.repository.MongoEntityInformation#getIdAttribute() - */ - public String getIdAttribute() { - return entityMetadata.getIdProperty().getName(); - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.repository.MongoEntityInformation#getIdAttribute() + */ + public String getIdAttribute() { + return entityMetadata.getIdProperty().getName(); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoAnnotationProcessor.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoAnnotationProcessor.java index 35b313430..1617dcdfd 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoAnnotationProcessor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoAnnotationProcessor.java @@ -46,20 +46,20 @@ import com.mysema.query.apt.Processor; @SupportedSourceVersion(SourceVersion.RELEASE_6) public class MongoAnnotationProcessor extends AbstractProcessor { - private Class entities, entity, embedded, skip; + private Class entities, entity, embedded, skip; - @Override - public boolean process(Set annotations, RoundEnvironment roundEnv) { + @Override + public boolean process(Set annotations, RoundEnvironment roundEnv) { - processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Running " + getClass().getSimpleName()); + processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "Running " + getClass().getSimpleName()); - DefaultConfiguration configuration = new DefaultConfiguration(roundEnv, processingEnv.getOptions(), - Collections. emptySet(), QueryEntities.class, Document.class, QuerySupertype.class, - QueryEmbeddable.class, QueryEmbedded.class, QueryTransient.class); - configuration.setUnknownAsEmbedded(true); + DefaultConfiguration configuration = new DefaultConfiguration(roundEnv, processingEnv.getOptions(), + Collections. emptySet(), QueryEntities.class, Document.class, QuerySupertype.class, + QueryEmbeddable.class, QueryEmbedded.class, QueryTransient.class); + configuration.setUnknownAsEmbedded(true); - Processor processor = new Processor(processingEnv, roundEnv, configuration); - processor.process(); - return true; - } + Processor processor = new Processor(processingEnv, roundEnv, configuration); + processor.process(); + return true; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoEntityInformation.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoEntityInformation.java index 061792af2..f75baba7d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoEntityInformation.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoEntityInformation.java @@ -21,22 +21,22 @@ import org.springframework.data.repository.support.EntityInformation; /** * Mongo specific {@link EntityInformation}. - * + * * @author Oliver Gierke */ public interface MongoEntityInformation extends EntityInformation { - /** - * Returns the name of the collection the entity shall be persisted to. - * - * @return - */ - String getCollectionName(); + /** + * Returns the name of the collection the entity shall be persisted to. + * + * @return + */ + String getCollectionName(); - /** - * Returns the attribute that the id will be persisted to. - * - * @return - */ - String getIdAttribute(); + /** + * Returns the attribute that the id will be persisted to. + * + * @return + */ + String getIdAttribute(); } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryCreator.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryCreator.java index 6967e2142..b9297daa0 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryCreator.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryCreator.java @@ -38,174 +38,165 @@ import org.springframework.data.repository.query.parser.Part; import org.springframework.data.repository.query.parser.Part.Type; import org.springframework.data.repository.query.parser.PartTree; - /** * Custom query creator to create Mongo criterias. - * + * * @author Oliver Gierke */ class MongoQueryCreator extends AbstractQueryCreator { - private static final Log LOG = LogFactory.getLog(MongoQueryCreator.class); + private static final Log LOG = LogFactory.getLog(MongoQueryCreator.class); + /** + * Creates a new {@link MongoQueryCreator} from the given {@link PartTree} and {@link ParametersParameterAccessor}. + * + * @param tree + * @param accessor + */ + public MongoQueryCreator(PartTree tree, ParameterAccessor accessor) { - /** - * Creates a new {@link MongoQueryCreator} from the given {@link PartTree} - * and {@link ParametersParameterAccessor}. - * - * @param tree - * @param accessor - */ - public MongoQueryCreator(PartTree tree, ParameterAccessor accessor) { + super(tree, accessor); + } - super(tree, accessor); - } + /* + * (non-Javadoc) + * @see org.springframework.data.repository.query.parser.AbstractQueryCreator#create(org.springframework.data.repository.query.parser.Part, java.util.Iterator) + */ + @Override + protected Query create(Part part, Iterator iterator) { + Criteria criteria = from(part.getType(), where(part.getProperty().toDotPath()), + (PotentiallyConvertingIterator) iterator); - /* - * (non-Javadoc) - * @see org.springframework.data.repository.query.parser.AbstractQueryCreator#create(org.springframework.data.repository.query.parser.Part, java.util.Iterator) - */ - @Override - protected Query create(Part part, Iterator iterator) { + return new Query(criteria); + } - Criteria criteria = from(part.getType(), - where(part.getProperty().toDotPath()), (PotentiallyConvertingIterator) iterator); + /* + * (non-Javadoc) + * @see org.springframework.data.repository.query.parser.AbstractQueryCreator#and(org.springframework.data.repository.query.parser.Part, java.lang.Object, java.util.Iterator) + */ + @Override + protected Query and(Part part, Query base, Iterator iterator) { - return new Query(criteria); - } + Criteria criteria = from(part.getType(), where(part.getProperty().toDotPath()), + (PotentiallyConvertingIterator) iterator); + return base.addCriteria(criteria); + } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.query.parser.AbstractQueryCreator + * #or(java.lang.Object, java.lang.Object) + */ + @Override + protected Query or(Query base, Query query) { - /* - * (non-Javadoc) - * @see org.springframework.data.repository.query.parser.AbstractQueryCreator#and(org.springframework.data.repository.query.parser.Part, java.lang.Object, java.util.Iterator) - */ - @Override - protected Query and(Part part, Query base, - Iterator iterator) { + return new Query().or(base, query); + } - Criteria criteria = from(part.getType(), where(part.getProperty().toDotPath()), - (PotentiallyConvertingIterator) iterator); - return base.addCriteria(criteria); - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.query.parser.AbstractQueryCreator + * #complete(java.lang.Object, org.springframework.data.domain.Sort) + */ + @Override + protected Query complete(Query query, Sort sort) { + if (LOG.isDebugEnabled()) { + LOG.debug("Created query " + query.getQueryObject()); + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.query.parser.AbstractQueryCreator - * #or(java.lang.Object, java.lang.Object) - */ - @Override - protected Query or(Query base, Query query) { + return query; + } - return new Query().or(base, query); - } + /** + * Populates the given {@link CriteriaDefinition} depending on the {@link Type} given. + * + * @param type + * @param criteria + * @param parameters + * @return + */ + private Criteria from(Type type, Criteria criteria, PotentiallyConvertingIterator parameters) { + switch (type) { + case GREATER_THAN: + return criteria.gt(parameters.nextConverted()); + case LESS_THAN: + return criteria.lt(parameters.nextConverted()); + case BETWEEN: + return criteria.gt(parameters.nextConverted()).lt(parameters.nextConverted()); + case IS_NOT_NULL: + return criteria.ne(null); + case IS_NULL: + return criteria.is(null); + case NOT_IN: + return criteria.nin(nextAsArray(parameters)); + case IN: + return criteria.in(nextAsArray(parameters)); + case LIKE: + String value = parameters.next().toString(); + return criteria.is(toLikeRegex(value)); + case NEAR: + return criteria.near(nextAs(parameters, Point.class)); + case WITHIN: - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.query.parser.AbstractQueryCreator - * #complete(java.lang.Object, org.springframework.data.domain.Sort) - */ - @Override - protected Query complete(Query query, Sort sort) { + Object parameter = parameters.next(); + if (parameter instanceof Box) { + return criteria.withinBox((Box) parameter); + } else if (parameter instanceof Circle) { + return criteria.withinCenter((Circle) parameter); + } + throw new IllegalArgumentException("Parameter has to be either Box or Circle!"); + case SIMPLE_PROPERTY: + return criteria.is(parameters.nextConverted()); + case NEGATING_SIMPLE_PROPERTY: + return criteria.not().is(parameters.nextConverted()); + } - if (LOG.isDebugEnabled()) { - LOG.debug("Created query " + query.getQueryObject()); - } + throw new IllegalArgumentException("Unsupported keyword!"); + } - return query; - } + /** + * Returns the next element from the given {@link Iterator} expecting it to be of a certain type. + * + * @param + * @param iterator + * @param type + * @throws IllegalArgumentException + * in case the next element in the iterator is not of the given type. + * @return + */ + @SuppressWarnings("unchecked") + private T nextAs(Iterator iterator, Class type) { + Object parameter = iterator.next(); + if (parameter.getClass().isAssignableFrom(type)) { + return (T) parameter; + } + throw new IllegalArgumentException(String.format("Expected parameter type of %s but got %s!", type, + parameter.getClass())); + } - /** - * Populates the given {@link CriteriaDefinition} depending on the {@link Type} given. - * - * @param type - * @param criteria - * @param parameters - * @return - */ - private Criteria from(Type type, Criteria criteria, PotentiallyConvertingIterator parameters) { + private Object[] nextAsArray(PotentiallyConvertingIterator iterator) { + Object next = iterator.nextConverted(); - switch (type) { - case GREATER_THAN: - return criteria.gt(parameters.nextConverted()); - case LESS_THAN: - return criteria.lt(parameters.nextConverted()); - case BETWEEN: - return criteria.gt(parameters.nextConverted()).lt(parameters.nextConverted()); - case IS_NOT_NULL: - return criteria.ne(null); - case IS_NULL: - return criteria.is(null); - case NOT_IN: - return criteria.nin(nextAsArray(parameters)); - case IN: - return criteria.in(nextAsArray(parameters)); - case LIKE: - String value = parameters.next().toString(); - return criteria.is(toLikeRegex(value)); - case NEAR: - return criteria.near(nextAs(parameters, Point.class)); - case WITHIN: - - Object parameter = parameters.next(); - if (parameter instanceof Box) { - return criteria.withinBox((Box) parameter); - } else if (parameter instanceof Circle) { - return criteria.withinCenter((Circle) parameter); - } - throw new IllegalArgumentException("Parameter has to be either Box or Circle!"); - case SIMPLE_PROPERTY: - return criteria.is(parameters.nextConverted()); - case NEGATING_SIMPLE_PROPERTY: - return criteria.not().is(parameters.nextConverted()); - } + if (next instanceof Collection) { + return ((Collection) next).toArray(); + } else if (next.getClass().isArray()) { + return (Object[]) next; + } - throw new IllegalArgumentException("Unsupported keyword!"); - } + return new Object[] { next }; + } - /** - * Returns the next element from the given {@link Iterator} expecting it to be of a certain type. - * - * @param - * @param iterator - * @param type - * @throws IllegalArgumentException - * in case the next element in the iterator is not of the given type. - * @return - */ - @SuppressWarnings("unchecked") - private T nextAs(Iterator iterator, Class type) { - Object parameter = iterator.next(); - if (parameter.getClass().isAssignableFrom(type)) { - return (T) parameter; - } + private Pattern toLikeRegex(String source) { - throw new IllegalArgumentException(String.format("Expected parameter type of %s but got %s!", type, - parameter.getClass())); - } - - private Object[] nextAsArray(PotentiallyConvertingIterator iterator) { - Object next = iterator.nextConverted(); - - if (next instanceof Collection) { - return ((Collection) next).toArray(); - } else if (next.getClass().isArray()) { - return (Object[]) next; - } - - return new Object[]{next}; - } - - private Pattern toLikeRegex(String source) { - - String regex = source.replaceAll("\\*", ".*"); - return Pattern.compile(regex); - } + String regex = source.replaceAll("\\*", ".*"); + return Pattern.compile(regex); + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryMethod.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryMethod.java index bfe65863c..98f3981d9 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryMethod.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoQueryMethod.java @@ -32,68 +32,68 @@ import org.springframework.util.StringUtils; */ class MongoQueryMethod extends QueryMethod { - private final Method method; - private final MongoEntityInformation entityInformation; + private final Method method; + private final MongoEntityInformation entityInformation; - /** - * Creates a new {@link MongoQueryMethod} from the given {@link Method}. - * - * @param method - */ - public MongoQueryMethod(Method method, RepositoryMetadata metadata, EntityInformationCreator entityInformationCreator) { - super(method, metadata); - this.method = method; - this.entityInformation = entityInformationCreator.getEntityInformation(ClassUtils.getReturnedDomainClass(method)); - } + /** + * Creates a new {@link MongoQueryMethod} from the given {@link Method}. + * + * @param method + */ + public MongoQueryMethod(Method method, RepositoryMetadata metadata, EntityInformationCreator entityInformationCreator) { + super(method, metadata); + this.method = method; + this.entityInformation = entityInformationCreator.getEntityInformation(ClassUtils.getReturnedDomainClass(method)); + } - /** - * Returns whether the method has an annotated query. - * - * @return - */ - boolean hasAnnotatedQuery() { - return getAnnotatedQuery() != null; - } + /** + * Returns whether the method has an annotated query. + * + * @return + */ + boolean hasAnnotatedQuery() { + return getAnnotatedQuery() != null; + } - /** - * Returns the query string declared in a {@link Query} annotation or {@literal null} if neither the annotation found - * nor the attribute was specified. - * - * @return - */ - String getAnnotatedQuery() { + /** + * Returns the query string declared in a {@link Query} annotation or {@literal null} if neither the annotation found + * nor the attribute was specified. + * + * @return + */ + String getAnnotatedQuery() { - String query = (String) AnnotationUtils.getValue(getQueryAnnotation()); - return StringUtils.hasText(query) ? query : null; - } + String query = (String) AnnotationUtils.getValue(getQueryAnnotation()); + return StringUtils.hasText(query) ? query : null; + } - /** - * Returns the field specification to be used for the query. - * - * @return - */ - String getFieldSpecification() { + /** + * Returns the field specification to be used for the query. + * + * @return + */ + String getFieldSpecification() { - String value = (String) AnnotationUtils.getValue(getQueryAnnotation(), "fields"); - return StringUtils.hasText(value) ? value : null; - } + String value = (String) AnnotationUtils.getValue(getQueryAnnotation(), "fields"); + return StringUtils.hasText(value) ? value : null; + } - /* (non-Javadoc) - * @see org.springframework.data.repository.query.QueryMethod#getEntityMetadata() - */ - @Override - public MongoEntityInformation getEntityInformation() { + /* (non-Javadoc) + * @see org.springframework.data.repository.query.QueryMethod#getEntityMetadata() + */ + @Override + public MongoEntityInformation getEntityInformation() { - return entityInformation; - } + return entityInformation; + } - /** - * Returns the {@link Query} annotation that is applied to the method or {@code null} if none available. - * - * @return - */ - private Query getQueryAnnotation() { + /** + * Returns the {@link Query} annotation that is applied to the method or {@code null} if none available. + * + * @return + */ + private Query getQueryAnnotation() { - return method.getAnnotation(Query.class); - } + return method.getAnnotation(Query.class); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepository.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepository.java index c93fbf8f3..ddea9ac43 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepository.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepository.java @@ -23,7 +23,7 @@ import org.springframework.data.repository.PagingAndSortingRepository; /** * Mongo specific {@link org.springframework.data.repository.Repository} interface. - * + * * @author Oliver Gierke */ public interface MongoRepository extends PagingAndSortingRepository { @@ -34,18 +34,18 @@ public interface MongoRepository extends PagingAndSo * @see org.springframework.data.repository.Repository#save(java.lang.Iterable) */ List save(Iterable entites); - - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.Repository#findAll() - */ - List findAll(); - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort) - */ - List findAll(Sort sort); + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.Repository#findAll() + */ + List findAll(); + + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.PagingAndSortingRepository#findAll(org.springframework.data.domain.Sort) + */ + List findAll(Sort sort); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryBean.java index 34fb3d379..1d18a8ef1 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryBean.java @@ -50,272 +50,277 @@ import org.springframework.util.StringUtils; /** * {@link org.springframework.beans.factory.FactoryBean} to create {@link MongoRepository} instances. - * + * * @author Oliver Gierke */ public class MongoRepositoryFactoryBean, S, ID extends Serializable> extends - RepositoryFactoryBeanSupport { + RepositoryFactoryBeanSupport { - private MongoTemplate template; - private MappingContext, MongoPersistentProperty> mappingContext; + private MongoTemplate template; + private MappingContext, MongoPersistentProperty> mappingContext; - /** - * Configures the {@link MongoTemplate} to be used. - * - * @param template the template to set - */ - public void setTemplate(MongoTemplate template) { + /** + * Configures the {@link MongoTemplate} to be used. + * + * @param template + * the template to set + */ + public void setTemplate(MongoTemplate template) { - this.template = template; - } + this.template = template; + } - /** - * Sets the {@link MappingContext} used with the underlying {@link MongoTemplate}. - * - * @param mappingContext the mappingContext to set - */ - public void setMappingContext(MappingContext, MongoPersistentProperty> mappingContext) { - this.mappingContext = mappingContext; - } + /** + * Sets the {@link MappingContext} used with the underlying {@link MongoTemplate}. + * + * @param mappingContext + * the mappingContext to set + */ + public void setMappingContext(MappingContext, MongoPersistentProperty> mappingContext) { + this.mappingContext = mappingContext; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.support.RepositoryFactoryBeanSupport - * #createRepositoryFactory() - */ - @Override - protected RepositoryFactorySupport createRepositoryFactory() { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.support.RepositoryFactoryBeanSupport + * #createRepositoryFactory() + */ + @Override + protected RepositoryFactorySupport createRepositoryFactory() { - MongoRepositoryFactory factory = new MongoRepositoryFactory(template, mappingContext); - factory.addQueryCreationListener(new IndexEnsuringQueryCreationListener(template)); - return factory; - } + MongoRepositoryFactory factory = new MongoRepositoryFactory(template, mappingContext); + factory.addQueryCreationListener(new IndexEnsuringQueryCreationListener(template)); + return factory; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.support.RepositoryFactoryBeanSupport - * #afterPropertiesSet() - */ - @Override - public void afterPropertiesSet() { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.support.RepositoryFactoryBeanSupport + * #afterPropertiesSet() + */ + @Override + public void afterPropertiesSet() { - super.afterPropertiesSet(); - Assert.notNull(template, "MongoTemplate must not be null!"); - Assert.notNull(mappingContext, "MappingContext must not be null!"); - } + super.afterPropertiesSet(); + Assert.notNull(template, "MongoTemplate must not be null!"); + Assert.notNull(mappingContext, "MappingContext must not be null!"); + } - /** - * Repository to create {@link MongoRepository} instances. - * - * @author Oliver Gierke - */ - public static class MongoRepositoryFactory extends RepositoryFactorySupport { + /** + * Repository to create {@link MongoRepository} instances. + * + * @author Oliver Gierke + */ + public static class MongoRepositoryFactory extends RepositoryFactorySupport { - private final MongoTemplate template; - private final EntityInformationCreator entityInformationCreator; + private final MongoTemplate template; + private final EntityInformationCreator entityInformationCreator; - /** - * Creates a new {@link MongoRepositoryFactory} with the given {@link MongoTemplate} and {@link MappingContext}. - * - * @param template must not be {@literal null} - * @param mappingContext - */ - public MongoRepositoryFactory(MongoTemplate template, MappingContext, MongoPersistentProperty> mappingContext) { + /** + * Creates a new {@link MongoRepositoryFactory} with the given {@link MongoTemplate} and {@link MappingContext}. + * + * @param template + * must not be {@literal null} + * @param mappingContext + */ + public MongoRepositoryFactory(MongoTemplate template, + MappingContext, MongoPersistentProperty> mappingContext) { - Assert.notNull(template); - Assert.notNull(mappingContext); - this.template = template; - this.entityInformationCreator = new EntityInformationCreator(mappingContext); - } + Assert.notNull(template); + Assert.notNull(mappingContext); + this.template = template; + this.entityInformationCreator = new EntityInformationCreator(mappingContext); + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.support.RepositoryFactorySupport - * #getRepositoryBaseClass() - */ - @Override - protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.support.RepositoryFactorySupport + * #getRepositoryBaseClass() + */ + @Override + protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { - return isQueryDslRepository(metadata.getRepositoryInterface()) ? QueryDslMongoRepository.class - : SimpleMongoRepository.class; - } + return isQueryDslRepository(metadata.getRepositoryInterface()) ? QueryDslMongoRepository.class + : SimpleMongoRepository.class; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.support.RepositoryFactorySupport - * #getTargetRepository - * (org.springframework.data.repository.support.RepositoryMetadata) - */ - @Override - @SuppressWarnings({"rawtypes", "unchecked"}) - protected Object getTargetRepository(RepositoryMetadata metadata) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.support.RepositoryFactorySupport + * #getTargetRepository + * (org.springframework.data.repository.support.RepositoryMetadata) + */ + @Override + @SuppressWarnings({ "rawtypes", "unchecked" }) + protected Object getTargetRepository(RepositoryMetadata metadata) { - Class repositoryInterface = metadata.getRepositoryInterface(); - MongoEntityInformation entityInformation = getEntityInformation(metadata.getDomainClass()); + Class repositoryInterface = metadata.getRepositoryInterface(); + MongoEntityInformation entityInformation = getEntityInformation(metadata.getDomainClass()); - if (isQueryDslRepository(repositoryInterface)) { - return new QueryDslMongoRepository(entityInformation, template); - } else { - return new SimpleMongoRepository(entityInformation, template); - } - } + if (isQueryDslRepository(repositoryInterface)) { + return new QueryDslMongoRepository(entityInformation, template); + } else { + return new SimpleMongoRepository(entityInformation, template); + } + } - private static boolean isQueryDslRepository(Class repositoryInterface) { + private static boolean isQueryDslRepository(Class repositoryInterface) { - return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface); - } + return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface); + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.support.RepositoryFactorySupport - * #getQueryLookupStrategy - * (org.springframework.data.repository.query.QueryLookupStrategy.Key) - */ - @Override - protected QueryLookupStrategy getQueryLookupStrategy(Key key) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.support.RepositoryFactorySupport + * #getQueryLookupStrategy + * (org.springframework.data.repository.query.QueryLookupStrategy.Key) + */ + @Override + protected QueryLookupStrategy getQueryLookupStrategy(Key key) { - return new MongoQueryLookupStrategy(); - } + return new MongoQueryLookupStrategy(); + } - /** - * {@link QueryLookupStrategy} to create {@link PartTreeMongoQuery} instances. - * - * @author Oliver Gierke - */ - private class MongoQueryLookupStrategy implements QueryLookupStrategy { + /** + * {@link QueryLookupStrategy} to create {@link PartTreeMongoQuery} instances. + * + * @author Oliver Gierke + */ + private class MongoQueryLookupStrategy implements QueryLookupStrategy { - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.query.QueryLookupStrategy - * #resolveQuery(java.lang.reflect.Method, java.lang.Class) - */ - public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.query.QueryLookupStrategy + * #resolveQuery(java.lang.reflect.Method, java.lang.Class) + */ + public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata) { - MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, entityInformationCreator); + MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, entityInformationCreator); - if (queryMethod.hasAnnotatedQuery()) { - return new StringBasedMongoQuery(queryMethod, template); - } else { - return new PartTreeMongoQuery(queryMethod, template); - } - } - } + if (queryMethod.hasAnnotatedQuery()) { + return new StringBasedMongoQuery(queryMethod, template); + } else { + return new PartTreeMongoQuery(queryMethod, template); + } + } + } - /* - * (non-Javadoc) - * @see org.springframework.data.repository.support.RepositoryFactorySupport#validate(org.springframework.data.repository.support.RepositoryMetadata) - */ - @Override - protected void validate(RepositoryMetadata metadata) { + /* + * (non-Javadoc) + * @see org.springframework.data.repository.support.RepositoryFactorySupport#validate(org.springframework.data.repository.support.RepositoryMetadata) + */ + @Override + protected void validate(RepositoryMetadata metadata) { - Class idClass = metadata.getIdClass(); - if (!MongoPropertyDescriptor.SUPPORTED_ID_CLASSES.contains(idClass)) { - throw new IllegalArgumentException(String.format("Unsupported id class! Only %s are supported!", - StringUtils.collectionToCommaDelimitedString(MongoPropertyDescriptor.SUPPORTED_ID_CLASSES))); - } - } + Class idClass = metadata.getIdClass(); + if (!MongoPropertyDescriptor.SUPPORTED_ID_CLASSES.contains(idClass)) { + throw new IllegalArgumentException(String.format("Unsupported id class! Only %s are supported!", + StringUtils.collectionToCommaDelimitedString(MongoPropertyDescriptor.SUPPORTED_ID_CLASSES))); + } + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.support.RepositoryFactorySupport - * #getEntityInformation(java.lang.Class) - */ - @Override - public MongoEntityInformation getEntityInformation(Class domainClass) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.support.RepositoryFactorySupport + * #getEntityInformation(java.lang.Class) + */ + @Override + public MongoEntityInformation getEntityInformation(Class domainClass) { - return entityInformationCreator.getEntityInformation(domainClass); - } - } + return entityInformationCreator.getEntityInformation(domainClass); + } + } - /** - * Simple wrapper to to create {@link MongoEntityInformation} instances based on a {@link MappingContext}. - * - * @author Oliver Gierke - */ - static class EntityInformationCreator { + /** + * Simple wrapper to to create {@link MongoEntityInformation} instances based on a {@link MappingContext}. + * + * @author Oliver Gierke + */ + static class EntityInformationCreator { - private final MappingContext, MongoPersistentProperty> mappingContext; + private final MappingContext, MongoPersistentProperty> mappingContext; - public EntityInformationCreator(MappingContext, MongoPersistentProperty> mappingContext) { - Assert.notNull(mappingContext); - this.mappingContext = mappingContext; - } + public EntityInformationCreator(MappingContext, MongoPersistentProperty> mappingContext) { + Assert.notNull(mappingContext); + this.mappingContext = mappingContext; + } - @SuppressWarnings("unchecked") - public MongoEntityInformation getEntityInformation(Class domainClass) { - MongoPersistentEntity persistentEntity = (MongoPersistentEntity) mappingContext.getPersistentEntity(domainClass); - return new MappingMongoEntityInformation(persistentEntity); - } - } + @SuppressWarnings("unchecked") + public MongoEntityInformation getEntityInformation(Class domainClass) { + MongoPersistentEntity persistentEntity = (MongoPersistentEntity) mappingContext + .getPersistentEntity(domainClass); + return new MappingMongoEntityInformation(persistentEntity); + } + } - /** - * {@link QueryCreationListener} inspecting {@link PartTreeMongoQuery}s and creating an index for the properties it - * refers to. - * - * @author Oliver Gierke - */ - private static class IndexEnsuringQueryCreationListener implements QueryCreationListener { + /** + * {@link QueryCreationListener} inspecting {@link PartTreeMongoQuery}s and creating an index for the properties it + * refers to. + * + * @author Oliver Gierke + */ + private static class IndexEnsuringQueryCreationListener implements QueryCreationListener { - private static final Set GEOSPATIAL_TYPES = new HashSet(Arrays.asList(Type.NEAR, Type.WITHIN)); - private static final Log LOG = LogFactory.getLog(IndexEnsuringQueryCreationListener.class); - private final MongoOperations operations; + private static final Set GEOSPATIAL_TYPES = new HashSet(Arrays.asList(Type.NEAR, Type.WITHIN)); + private static final Log LOG = LogFactory.getLog(IndexEnsuringQueryCreationListener.class); + private final MongoOperations operations; - public IndexEnsuringQueryCreationListener(MongoOperations operations) { + public IndexEnsuringQueryCreationListener(MongoOperations operations) { - this.operations = operations; - } + this.operations = operations; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.support.QueryCreationListener - * #onCreation(org.springframework.data.repository - * .query.RepositoryQuery) - */ - public void onCreation(PartTreeMongoQuery query) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.support.QueryCreationListener + * #onCreation(org.springframework.data.repository + * .query.RepositoryQuery) + */ + public void onCreation(PartTreeMongoQuery query) { - PartTree tree = query.getTree(); - Index index = new Index(); - index.named(query.getQueryMethod().getName()); - Sort sort = tree.getSort(); + PartTree tree = query.getTree(); + Index index = new Index(); + index.named(query.getQueryMethod().getName()); + Sort sort = tree.getSort(); - for (Part part : tree.getParts()) { - if (GEOSPATIAL_TYPES.contains(part.getType())) { - return; - } - String property = part.getProperty().toDotPath(); - Order order = toOrder(sort, property); - index.on(property, order); - } + for (Part part : tree.getParts()) { + if (GEOSPATIAL_TYPES.contains(part.getType())) { + return; + } + String property = part.getProperty().toDotPath(); + Order order = toOrder(sort, property); + index.on(property, order); + } - MongoEntityInformation metadata = query.getQueryMethod().getEntityInformation(); - operations.ensureIndex(metadata.getCollectionName(), index); - LOG.debug(String.format("Created %s!", index)); - } + MongoEntityInformation metadata = query.getQueryMethod().getEntityInformation(); + operations.ensureIndex(metadata.getCollectionName(), index); + LOG.debug(String.format("Created %s!", index)); + } - private static Order toOrder(Sort sort, String property) { + private static Order toOrder(Sort sort, String property) { - if (sort == null) { - return Order.DESCENDING; - } + if (sort == null) { + return Order.DESCENDING; + } - org.springframework.data.domain.Sort.Order order = sort.getOrderFor(property); - return order == null ? Order.DESCENDING : order.isAscending() ? Order.ASCENDING : Order.DESCENDING; - } - } + org.springframework.data.domain.Sort.Order order = sort.getOrderFor(property); + return order == null ? Order.DESCENDING : order.isAscending() ? Order.ASCENDING : Order.DESCENDING; + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/PartTreeMongoQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/PartTreeMongoQuery.java index 7af92121d..158c7e278 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/PartTreeMongoQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/PartTreeMongoQuery.java @@ -23,43 +23,43 @@ import org.springframework.data.repository.query.parser.PartTree; /** * {@link RepositoryQuery} implementation for Mongo. - * + * * @author Oliver Gierke */ public class PartTreeMongoQuery extends AbstractMongoQuery { - private final PartTree tree; + private final PartTree tree; - /** - * Creates a new {@link PartTreeMongoQuery} from the given {@link QueryMethod} and {@link MongoTemplate}. - * - * @param method - * @param template - */ - public PartTreeMongoQuery(MongoQueryMethod method, MongoTemplate template) { + /** + * Creates a new {@link PartTreeMongoQuery} from the given {@link QueryMethod} and {@link MongoTemplate}. + * + * @param method + * @param template + */ + public PartTreeMongoQuery(MongoQueryMethod method, MongoTemplate template) { - super(method, template); - this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType()); - } + super(method, template); + this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType()); + } - /** - * @return the tree - */ - public PartTree getTree() { - return tree; - } + /** + * @return the tree + */ + public PartTree getTree() { + return tree; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.document.mongodb.repository.AbstractMongoQuery#createQuery(org.springframework.data. - * document.mongodb.repository.ConvertingParameterAccessor) - */ - @Override - protected Query createQuery(ConvertingParameterAccessor accessor) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.document.mongodb.repository.AbstractMongoQuery#createQuery(org.springframework.data. + * document.mongodb.repository.ConvertingParameterAccessor) + */ + @Override + protected Query createQuery(ConvertingParameterAccessor accessor) { - MongoQueryCreator creator = new MongoQueryCreator(tree, accessor); - return creator.createQuery(); - } + MongoQueryCreator creator = new MongoQueryCreator(tree, accessor); + return creator.createQuery(); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/Query.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/Query.java index 82bd7b269..0a7891ac0 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/Query.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/Query.java @@ -28,19 +28,19 @@ import java.lang.annotation.*; @Documented public @interface Query { - /** - * Takes a MongoDB JSON string to define the actual query to be executed. This one will take precendece over the - * method name then. - * - * @return - */ - String value() default ""; + /** + * Takes a MongoDB JSON string to define the actual query to be executed. This one will take precendece over the + * method name then. + * + * @return + */ + String value() default ""; - /** - * Defines the fields that should be returned for the given query. Note that only these fields will make it into the - * domain object returned. - * - * @return - */ - String fields() default ""; + /** + * Defines the fields that should be returned for the given query. Note that only these fields will make it into the + * domain object returned. + * + * @return + */ + String fields() default ""; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslMongoRepository.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslMongoRepository.java index 71fdfad7c..7b44f66e8 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslMongoRepository.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslMongoRepository.java @@ -40,250 +40,221 @@ import com.mysema.query.types.OrderSpecifier; import com.mysema.query.types.Predicate; import com.mysema.query.types.path.PathBuilder; - /** - * Special QueryDsl based repository implementation that allows execution - * {@link Predicate}s in various forms. TODO: Extract {@link EntityPathResolver} - * into Spring Data Commons TODO: Refactor Spring Data JPA to use this common + * Special QueryDsl based repository implementation that allows execution {@link Predicate}s in various forms. TODO: + * Extract {@link EntityPathResolver} into Spring Data Commons TODO: Refactor Spring Data JPA to use this common * infrastructure * * @author Oliver Gierke */ -public class QueryDslMongoRepository extends - SimpleMongoRepository implements QueryDslPredicateExecutor { +public class QueryDslMongoRepository extends SimpleMongoRepository implements + QueryDslPredicateExecutor { - private final MongoConverterTransformer transformer; - private final MongodbSerializer serializer; - private final PathBuilder builder; + private final MongoConverterTransformer transformer; + private final MongodbSerializer serializer; + private final PathBuilder builder; + /** + * Creates a new {@link QueryDslMongoRepository} for the given {@link EntityMetadata} and {@link MongoTemplate}. Uses + * the {@link SimpleEntityPathResolver} to create an {@link EntityPath} for the given domain class. + * + * @param entityInformation + * @param template + */ + public QueryDslMongoRepository(MongoEntityInformation entityInformation, MongoTemplate template) { - /** - * Creates a new {@link QueryDslMongoRepository} for the given - * {@link EntityMetadata} and {@link MongoTemplate}. Uses the - * {@link SimpleEntityPathResolver} to create an {@link EntityPath} for the - * given domain class. - * - * @param entityInformation - * @param template - */ - public QueryDslMongoRepository( - MongoEntityInformation entityInformation, MongoTemplate template) { + this(entityInformation, template, SimpleEntityPathResolver.INSTANCE); + } - this(entityInformation, template, SimpleEntityPathResolver.INSTANCE); - } + /** + * Creates a new {@link QueryDslMongoRepository} for the given {@link MongoEntityInformation}, {@link MongoTemplate} + * and {@link EntityPathResolver}. + * + * @param entityInformation + * @param template + * @param resolver + */ + public QueryDslMongoRepository(MongoEntityInformation entityInformation, MongoTemplate template, + EntityPathResolver resolver) { + super(entityInformation, template); + this.transformer = new MongoConverterTransformer(template.getConverter()); + this.serializer = new MongodbSerializer(); - /** - * Creates a new {@link QueryDslMongoRepository} for the given {@link MongoEntityInformation}, - * {@link MongoTemplate} and {@link EntityPathResolver}. - * - * @param entityInformation - * @param template - * @param resolver - */ - public QueryDslMongoRepository( - MongoEntityInformation entityInformation, - MongoTemplate template, EntityPathResolver resolver) { + EntityPath path = resolver.createPath(entityInformation.getJavaType()); + this.builder = new PathBuilder(path.getType(), path.getMetadata()); + } - super(entityInformation, template); - this.transformer = new MongoConverterTransformer(template.getConverter()); - this.serializer = new MongodbSerializer(); - - EntityPath path = resolver.createPath(entityInformation.getJavaType()); - this.builder = new PathBuilder(path.getType(), path.getMetadata()); - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.document.mongodb.repository.QueryDslExecutor + * #findOne(com.mysema.query.types.Predicate) + */ + public T findOne(Predicate predicate) { + return createQueryFor(predicate).uniqueResult(); + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.document.mongodb.repository.QueryDslExecutor - * #findOne(com.mysema.query.types.Predicate) - */ - public T findOne(Predicate predicate) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.document.mongodb.repository.QueryDslExecutor + * #findAll(com.mysema.query.types.Predicate) + */ + public List findAll(Predicate predicate) { - return createQueryFor(predicate).uniqueResult(); - } + return createQueryFor(predicate).list(); + } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.document.mongodb.repository.QueryDslExecutor + * #findAll(com.mysema.query.types.Predicate, + * com.mysema.query.types.OrderSpecifier[]) + */ + public List findAll(Predicate predicate, OrderSpecifier... orders) { - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.document.mongodb.repository.QueryDslExecutor - * #findAll(com.mysema.query.types.Predicate) - */ - public List findAll(Predicate predicate) { + return createQueryFor(predicate).orderBy(orders).list(); + } - return createQueryFor(predicate).list(); - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.document.mongodb.repository.QueryDslExecutor + * #findAll(com.mysema.query.types.Predicate, + * org.springframework.data.domain.Pageable) + */ + public Page findAll(Predicate predicate, Pageable pageable) { + MongodbQuery countQuery = createQueryFor(predicate); + MongodbQuery query = createQueryFor(predicate); - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.document.mongodb.repository.QueryDslExecutor - * #findAll(com.mysema.query.types.Predicate, - * com.mysema.query.types.OrderSpecifier[]) - */ - public List findAll(Predicate predicate, OrderSpecifier... orders) { + return new PageImpl(applyPagination(query, pageable).list(), pageable, countQuery.count()); + } - return createQueryFor(predicate).orderBy(orders).list(); - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.document.mongodb.repository.QueryDslExecutor + * #count(com.mysema.query.types.Predicate) + */ + public long count(Predicate predicate) { + return createQueryFor(predicate).count(); + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.document.mongodb.repository.QueryDslExecutor - * #findAll(com.mysema.query.types.Predicate, - * org.springframework.data.domain.Pageable) - */ - public Page findAll(Predicate predicate, Pageable pageable) { + /** + * Creates a {@link MongodbQuery} for the given {@link Predicate}. + * + * @param predicate + * @return + */ + private MongodbQuery createQueryFor(Predicate predicate) { - MongodbQuery countQuery = createQueryFor(predicate); - MongodbQuery query = createQueryFor(predicate); + MongodbQuery query = new MongoTemplateQuery(getMongoOperations()); + return query.where(predicate); + } - return new PageImpl(applyPagination(query, pageable).list(), - pageable, countQuery.count()); - } + /** + * Applies the given {@link Pageable} to the given {@link MongodbQuery}. + * + * @param query + * @param pageable + * @return + */ + private MongodbQuery applyPagination(MongodbQuery query, Pageable pageable) { + if (pageable == null) { + return query; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.document.mongodb.repository.QueryDslExecutor - * #count(com.mysema.query.types.Predicate) - */ - public long count(Predicate predicate) { + query = query.offset(pageable.getOffset()).limit(pageable.getPageSize()); + return applySorting(query, pageable.getSort()); + } - return createQueryFor(predicate).count(); - } + /** + * Applies the given {@link Sort} to the given {@link MongodbQuery}. + * + * @param query + * @param sort + * @return + */ + private MongodbQuery applySorting(MongodbQuery query, Sort sort) { + if (sort == null) { + return query; + } - /** - * Creates a {@link MongodbQuery} for the given {@link Predicate}. - * - * @param predicate - * @return - */ - private MongodbQuery createQueryFor(Predicate predicate) { + for (Order order : sort) { + query.orderBy(toOrder(order)); + } - MongodbQuery query = new MongoTemplateQuery(getMongoOperations()); - return query.where(predicate); - } + return query; + } + /** + * Transforms a plain {@link Order} into a QueryDsl specific {@link OrderSpecifier}. + * + * @param order + * @return + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + private OrderSpecifier toOrder(Order order) { - /** - * Applies the given {@link Pageable} to the given {@link MongodbQuery}. - * - * @param query - * @param pageable - * @return - */ - private MongodbQuery applyPagination(MongodbQuery query, - Pageable pageable) { + Expression property = builder.get(order.getProperty()); - if (pageable == null) { - return query; - } + return new OrderSpecifier(order.isAscending() ? com.mysema.query.types.Order.ASC + : com.mysema.query.types.Order.DESC, property); + } - query = - query.offset(pageable.getOffset()) - .limit(pageable.getPageSize()); - return applySorting(query, pageable.getSort()); - } + /** + * Special {@link MongodbQuery} implementation to use our {@link MongoOperations} for actually accessing Mongo. + * + * @author Oliver Gierke + */ + private class MongoTemplateQuery extends MongodbQuery { + public MongoTemplateQuery(MongoOperations operations) { + super(operations.getCollection(getEntityInformation().getCollectionName()), transformer, serializer); + } + } - /** - * Applies the given {@link Sort} to the given {@link MongodbQuery}. - * - * @param query - * @param sort - * @return - */ - private MongodbQuery applySorting(MongodbQuery query, Sort sort) { + /** + * {@link Transformer} implementation to delegate to a {@link MongoConverter}. + * + * @author Oliver Gierke + */ + private class MongoConverterTransformer implements Transformer { - if (sort == null) { - return query; - } + private final MongoConverter converter; - for (Order order : sort) { - query.orderBy(toOrder(order)); - } + /** + * Creates a new {@link MongoConverterTransformer} with the given {@link MongoConverter}. + * + * @param converter + */ + public MongoConverterTransformer(MongoConverter converter) { - return query; - } + this.converter = converter; + } + /* + * (non-Javadoc) + * + * @see + * org.apache.commons.collections15.Transformer#transform(java.lang. + * Object) + */ + public T transform(DBObject input) { - /** - * Transforms a plain {@link Order} into a QueryDsl specific - * {@link OrderSpecifier}. - * - * @param order - * @return - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - private OrderSpecifier toOrder(Order order) { - - Expression property = builder.get(order.getProperty()); - - return new OrderSpecifier( - order.isAscending() ? com.mysema.query.types.Order.ASC - : com.mysema.query.types.Order.DESC, property); - } - - /** - * Special {@link MongodbQuery} implementation to use our - * {@link MongoOperations} for actually accessing Mongo. - * - * @author Oliver Gierke - */ - private class MongoTemplateQuery extends MongodbQuery { - - public MongoTemplateQuery(MongoOperations operations) { - super(operations.getCollection(getEntityInformation() - .getCollectionName()), transformer, serializer); - } - } - - /** - * {@link Transformer} implementation to delegate to a - * {@link MongoConverter}. - * - * @author Oliver Gierke - */ - private class MongoConverterTransformer implements Transformer { - - private final MongoConverter converter; - - - /** - * Creates a new {@link MongoConverterTransformer} with the given - * {@link MongoConverter}. - * - * @param converter - */ - public MongoConverterTransformer(MongoConverter converter) { - - this.converter = converter; - } - - - /* - * (non-Javadoc) - * - * @see - * org.apache.commons.collections15.Transformer#transform(java.lang. - * Object) - */ - public T transform(DBObject input) { - - return converter.read(getEntityInformation().getJavaType(), input); - } - } + return converter.read(getEntityInformation().getJavaType(), input); + } + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslPredicateExecutor.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslPredicateExecutor.java index 13d8a02e3..7de0500ec 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslPredicateExecutor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryDslPredicateExecutor.java @@ -67,7 +67,8 @@ public interface QueryDslPredicateExecutor { /** * Returns the number of instances that the given {@link Predicate} will return. * - * @param predicate the {@link Predicate} to count instances for + * @param predicate + * the {@link Predicate} to count instances for * @return the number of instances */ long count(Predicate predicate); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryUtils.java index f4bc1de0a..5c0d2dc9f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/QueryUtils.java @@ -21,65 +21,58 @@ import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Order; - /** - * Collection of utility methods to apply sorting and pagination to a - * {@link DBCursor}. - * + * Collection of utility methods to apply sorting and pagination to a {@link DBCursor}. + * * @author Oliver Gierke */ abstract class QueryUtils { - private QueryUtils() { + private QueryUtils() { - } + } + /** + * Applies the given {@link Pageable} to the given {@link Query}. Will do nothing if {@link Pageable} is + * {@literal null}. + * + * @param query + * @param pageable + * @return + */ + public static Query applyPagination(Query query, Pageable pageable) { - /** - * Applies the given {@link Pageable} to the given {@link Query}. Will do - * nothing if {@link Pageable} is {@literal null}. - * - * @param query - * @param pageable - * @return - */ - public static Query applyPagination(Query query, Pageable pageable) { + if (pageable == null) { + return query; + } - if (pageable == null) { - return query; - } + query.limit(pageable.getPageSize()); + query.skip(pageable.getOffset()); - query.limit(pageable.getPageSize()); - query.skip(pageable.getOffset()); + return applySorting(query, pageable.getSort()); + } - return applySorting(query, pageable.getSort()); - } + /** + * Applies the given {@link Sort} to the {@link Query}. Will do nothing if {@link Sort} is {@literal null}. + * + * @param query + * @param sort + * @return + */ + public static Query applySorting(Query query, Sort sort) { + if (sort == null) { + return query; + } - /** - * Applies the given {@link Sort} to the {@link Query}. Will do nothing if - * {@link Sort} is {@literal null}. - * - * @param query - * @param sort - * @return - */ - public static Query applySorting(Query query, Sort sort) { + org.springframework.data.document.mongodb.query.Sort bSort = query.sort(); - if (sort == null) { - return query; - } + for (Order order : sort) { + bSort.on(order.getProperty(), + order.isAscending() ? org.springframework.data.document.mongodb.query.Order.ASCENDING + : org.springframework.data.document.mongodb.query.Order.DESCENDING); + } - org.springframework.data.document.mongodb.query.Sort bSort = - query.sort(); - - for (Order order : sort) { - bSort.on( - order.getProperty(), - order.isAscending() ? org.springframework.data.document.mongodb.query.Order.ASCENDING - : org.springframework.data.document.mongodb.query.Order.DESCENDING); - } - - return query; - } + return query; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java index 8a3aef063..ea1bc3d9f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/SimpleMongoRepository.java @@ -40,220 +40,221 @@ import org.springframework.util.Assert; */ public class SimpleMongoRepository implements PagingAndSortingRepository { - private final MongoTemplate template; - private final MongoEntityInformation entityInformation; + private final MongoTemplate template; + private final MongoEntityInformation entityInformation; - /** - * Creates a ew {@link SimpleMongoRepository} for the given {@link MongoEntityInformation} and {@link MongoTemplate}. - * - * @param metadata - * @param template - */ - public SimpleMongoRepository(MongoEntityInformation metadata, MongoTemplate template) { + /** + * Creates a ew {@link SimpleMongoRepository} for the given {@link MongoEntityInformation} and {@link MongoTemplate}. + * + * @param metadata + * @param template + */ + public SimpleMongoRepository(MongoEntityInformation metadata, MongoTemplate template) { - Assert.notNull(template); - Assert.notNull(metadata); - this.entityInformation = metadata; - this.template = template; - } + Assert.notNull(template); + Assert.notNull(metadata); + this.entityInformation = metadata; + this.template = template; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.Repository#save(java.lang.Object) - */ - public T save(T entity) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.Repository#save(java.lang.Object) + */ + public T save(T entity) { - template.save(entityInformation.getCollectionName(), entity); - return entity; - } + template.save(entityInformation.getCollectionName(), entity); + return entity; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.Repository#save(java.lang.Iterable) - */ - public List save(Iterable entities) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.Repository#save(java.lang.Iterable) + */ + public List save(Iterable entities) { - List result = new ArrayList(); + List result = new ArrayList(); - for (T entity : entities) { - save(entity); - result.add(entity); - } + for (T entity : entities) { + save(entity); + result.add(entity); + } - return result; - } + return result; + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.Repository#findById(java.io.Serializable - * ) - */ - public T findOne(ID id) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.Repository#findById(java.io.Serializable + * ) + */ + public T findOne(ID id) { - return template.findOne(entityInformation.getCollectionName(), getIdQuery(id), entityInformation.getJavaType()); - } + return template.findOne(entityInformation.getCollectionName(), getIdQuery(id), entityInformation.getJavaType()); + } - private Query getIdQuery(Object id) { - return new Query(getIdCriteria(id)); - } + private Query getIdQuery(Object id) { + return new Query(getIdCriteria(id)); + } - private Criteria getIdCriteria(Object id) { - return where(entityInformation.getIdAttribute()).is(id); - } + private Criteria getIdCriteria(Object id) { + return where(entityInformation.getIdAttribute()).is(id); + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.Repository#exists(java.io.Serializable - * ) - */ - public boolean exists(ID id) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.Repository#exists(java.io.Serializable + * ) + */ + public boolean exists(ID id) { - return findOne(id) != null; - } + return findOne(id) != null; + } - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.Repository#count() - */ - public long count() { + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.Repository#count() + */ + public long count() { - return template.getCollection(entityInformation.getCollectionName()).count(); - } + return template.getCollection(entityInformation.getCollectionName()).count(); + } - /* - * (non-Javadoc) - * @see org.springframework.data.repository.Repository#delete(java.io.Serializable) - */ - public void delete(ID id) { - delete(findOne(id)); - } - - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.Repository#delete(java.lang.Object) - */ - public void delete(T entity) { + /* + * (non-Javadoc) + * @see org.springframework.data.repository.Repository#delete(java.io.Serializable) + */ + public void delete(ID id) { + delete(findOne(id)); + } - template.remove(entityInformation.getCollectionName(), getIdQuery(entityInformation.getId(entity)), entity.getClass()); - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.Repository#delete(java.lang.Object) + */ + public void delete(T entity) { - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.Repository#delete(java.lang.Iterable) - */ - public void delete(Iterable entities) { + template.remove(entityInformation.getCollectionName(), getIdQuery(entityInformation.getId(entity)), + entity.getClass()); + } - for (T entity : entities) { - delete(entity); - } - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.Repository#delete(java.lang.Iterable) + */ + public void delete(Iterable entities) { - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.Repository#deleteAll() - */ - public void deleteAll() { + for (T entity : entities) { + delete(entity); + } + } - template.remove(entityInformation.getCollectionName(), new Query()); - } + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.Repository#deleteAll() + */ + public void deleteAll() { - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.Repository#findAll() - */ - public List findAll() { + template.remove(entityInformation.getCollectionName(), new Query()); + } - return findAll(new Query()); - } + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.Repository#findAll() + */ + public List findAll() { - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.PagingAndSortingRepository#findAll - * (org.springframework.data.domain.Pageable) - */ - public Page findAll(final Pageable pageable) { + return findAll(new Query()); + } - Long count = count(); - List list = findAll(QueryUtils.applyPagination(new Query(), pageable)); + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.PagingAndSortingRepository#findAll + * (org.springframework.data.domain.Pageable) + */ + public Page findAll(final Pageable pageable) { - return new PageImpl(list, pageable, count); - } + Long count = count(); + List list = findAll(QueryUtils.applyPagination(new Query(), pageable)); - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.PagingAndSortingRepository#findAll - * (org.springframework.data.domain.Sort) - */ - public List findAll(final Sort sort) { + return new PageImpl(list, pageable, count); + } - return findAll(QueryUtils.applySorting(new Query(), sort)); - } + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.PagingAndSortingRepository#findAll + * (org.springframework.data.domain.Sort) + */ + public List findAll(final Sort sort) { - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.repository.Repository#findAll(java.lang.Iterable - * ) - */ - public List findAll(Iterable ids) { + return findAll(QueryUtils.applySorting(new Query(), sort)); + } - Query query = null; + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.repository.Repository#findAll(java.lang.Iterable + * ) + */ + public List findAll(Iterable ids) { - for (ID id : ids) { - if (query == null) { - query = getIdQuery(id); - } else { - query = new Query().or(getIdQuery(id)); - } - } + Query query = null; - return findAll(query); - } + for (ID id : ids) { + if (query == null) { + query = getIdQuery(id); + } else { + query = new Query().or(getIdQuery(id)); + } + } - private List findAll(Query query) { + return findAll(query); + } - if (query == null) { - return Collections.emptyList(); - } + private List findAll(Query query) { - return template.find(entityInformation.getCollectionName(), query, entityInformation.getJavaType()); - } + if (query == null) { + return Collections.emptyList(); + } - /** - * Returns the underlying {@link MongoOperations} instance. - * - * @return - */ - protected MongoOperations getMongoOperations() { + return template.find(entityInformation.getCollectionName(), query, entityInformation.getJavaType()); + } - return this.template; - } + /** + * Returns the underlying {@link MongoOperations} instance. + * + * @return + */ + protected MongoOperations getMongoOperations() { - /** - * @return the entityInformation - */ - protected MongoEntityInformation getEntityInformation() { + return this.template; + } - return entityInformation; - } + /** + * @return the entityInformation + */ + protected MongoEntityInformation getEntityInformation() { + + return entityInformation; + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java index d573a0751..b744c9e80 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQuery.java @@ -27,79 +27,79 @@ import org.springframework.data.document.mongodb.query.Query; /** * Query to use a plain JSON String to create the {@link Query} to actually execute. - * + * * @author Oliver Gierke */ public class StringBasedMongoQuery extends AbstractMongoQuery { - private static final Pattern PLACEHOLDER = Pattern.compile("\\?(\\d+)"); - private static final Log LOG = LogFactory.getLog(StringBasedMongoQuery.class); + private static final Pattern PLACEHOLDER = Pattern.compile("\\?(\\d+)"); + private static final Log LOG = LogFactory.getLog(StringBasedMongoQuery.class); - private final String query; - private final String fieldSpec; + private final String query; + private final String fieldSpec; - /** - * Creates a new {@link StringBasedMongoQuery}. - * - * @param method - * @param template - */ - public StringBasedMongoQuery(MongoQueryMethod method, MongoTemplate template) { - super(method, template); - this.query = method.getAnnotatedQuery(); - this.fieldSpec = method.getFieldSpecification(); - } + /** + * Creates a new {@link StringBasedMongoQuery}. + * + * @param method + * @param template + */ + public StringBasedMongoQuery(MongoQueryMethod method, MongoTemplate template) { + super(method, template); + this.query = method.getAnnotatedQuery(); + this.fieldSpec = method.getFieldSpecification(); + } - /* - * (non-Javadoc) - * - * @see - * org.springframework.data.document.mongodb.repository.AbstractMongoQuery#createQuery(org.springframework.data. - * repository.query.SimpleParameterAccessor, org.springframework.data.document.mongodb.support.convert.MongoConverter) - */ - @Override - protected Query createQuery(ConvertingParameterAccessor accessor) { + /* + * (non-Javadoc) + * + * @see + * org.springframework.data.document.mongodb.repository.AbstractMongoQuery#createQuery(org.springframework.data. + * repository.query.SimpleParameterAccessor, org.springframework.data.document.mongodb.support.convert.MongoConverter) + */ + @Override + protected Query createQuery(ConvertingParameterAccessor accessor) { - String queryString = replacePlaceholders(query, accessor); + String queryString = replacePlaceholders(query, accessor); - Query query = null; + Query query = null; - if (fieldSpec != null) { - String fieldString = replacePlaceholders(fieldSpec, accessor); - query = new BasicQuery(queryString, fieldString); - } else { - query = new BasicQuery(queryString); - } + if (fieldSpec != null) { + String fieldString = replacePlaceholders(fieldSpec, accessor); + query = new BasicQuery(queryString, fieldString); + } else { + query = new BasicQuery(queryString); + } - if (LOG.isDebugEnabled()) { - LOG.debug(String.format("Created query {}", query.getQueryObject())); - } + if (LOG.isDebugEnabled()) { + LOG.debug(String.format("Created query {}", query.getQueryObject())); + } - return query; - } + return query; + } - private String replacePlaceholders(String input, ConvertingParameterAccessor accessor) { + private String replacePlaceholders(String input, ConvertingParameterAccessor accessor) { - Matcher matcher = PLACEHOLDER.matcher(input); - String result = input; + Matcher matcher = PLACEHOLDER.matcher(input); + String result = input; - while (matcher.find()) { - String group = matcher.group(); - int index = Integer.parseInt(matcher.group(1)); - result = input.replace(group, getParameterWithIndex(accessor, index)); - } + while (matcher.find()) { + String group = matcher.group(); + int index = Integer.parseInt(matcher.group(1)); + result = input.replace(group, getParameterWithIndex(accessor, index)); + } - return result; - } + return result; + } - private String getParameterWithIndex(ConvertingParameterAccessor accessor, int index) { - Object parameter = accessor.getBindableValue(index); - if (parameter instanceof String || parameter.getClass().isEnum()) { - return String.format("\"%s\"", parameter); - } else if (parameter instanceof ObjectId) { - return String.format("{ '$oid' : '%s' }", parameter); - } + private String getParameterWithIndex(ConvertingParameterAccessor accessor, int index) { + Object parameter = accessor.getBindableValue(index); + if (parameter instanceof String || parameter.getClass().isEnum()) { + return String.format("\"%s\"", parameter); + } else if (parameter instanceof ObjectId) { + return String.format("{ '$oid' : '%s' }", parameter); + } - return parameter.toString(); - } + return parameter.toString(); + } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/package-info.java b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/package-info.java index ddab9303b..9c078e437 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/package-info.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/document/mongodb/repository/package-info.java @@ -2,3 +2,4 @@ * MongoDB specific repository implementation. */ package org.springframework.data.document.mongodb.repository; + diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialAppConfig.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialAppConfig.java index f13192b49..862d674fa 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialAppConfig.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialAppConfig.java @@ -26,25 +26,23 @@ import com.mongodb.Mongo; @Configuration public class GeoSpatialAppConfig extends AbstractMongoConfiguration { - @Bean - public Mongo mongo() throws Exception { - return new Mongo("localhost"); - } - - @Bean - public MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), "geospatial", mappingMongoConverter()); - } - - @Bean - public LoggingEventListener mappingEventsListener() { - return new LoggingEventListener(); - } - + @Bean + public Mongo mongo() throws Exception { + return new Mongo("localhost"); + } - public String getMappingBasePackage() { - return "org.springframework.data.document.mongodb"; - } + @Bean + public MongoTemplate mongoTemplate() throws Exception { + return new MongoTemplate(mongo(), "geospatial", mappingMongoConverter()); + } + @Bean + public LoggingEventListener mappingEventsListener() { + return new LoggingEventListener(); + } + + public String getMappingBasePackage() { + return "org.springframework.data.document.mongodb"; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialTests.java index dedacf35d..faaeef601 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/GeoSpatialTests.java @@ -51,137 +51,134 @@ import com.mongodb.DBObject; import com.mongodb.Mongo; import com.mongodb.MongoException; import com.mongodb.WriteConcern; + /** * Modified from https://github.com/deftlabs/mongo-java-geospatial-example + * * @author Mark Pollack - * + * */ public class GeoSpatialTests { - private static final Log LOGGER = LogFactory.getLog(GeoSpatialTests.class); - private final String[] collectionsToDrop = new String[]{"newyork"}; + private static final Log LOGGER = LogFactory.getLog(GeoSpatialTests.class); + private final String[] collectionsToDrop = new String[] { "newyork" }; - ApplicationContext applicationContext; - MongoTemplate template; - ServerInfo serverInfo; - - ExpressionParser parser; + ApplicationContext applicationContext; + MongoTemplate template; + ServerInfo serverInfo; - @Before - public void setUp() throws Exception { - Mongo mongo = new Mongo(); - serverInfo = new ServerInfo(mongo); - DB db = mongo.getDB("geospatial"); - for (String coll : collectionsToDrop) { - db.getCollection(coll).drop(); - } - applicationContext = new AnnotationConfigApplicationContext(GeoSpatialAppConfig.class); - template = applicationContext.getBean(MongoTemplate.class); - template.setWriteConcern(WriteConcern.FSYNC_SAFE); - template.ensureIndex(Venue.class, new GeospatialIndex("location")); - indexCreated(); - addVenues(); - parser = new SpelExpressionParser(); - } + ExpressionParser parser; - private void addVenues() { - - template.insert(new Venue("Penn Station", -73.99408, 40.75057)); - template.insert(new Venue("10gen Office", -73.99171, 40.738868)); - template.insert(new Venue("Flatiron Building", -73.988135, 40.741404)); - template.insert(new Venue("Players Club", -73.997812, 40.739128)); - template.insert(new Venue("City Bakery ", -73.992491, 40.738673)); - template.insert(new Venue("Splash Bar", -73.992491, 40.738673)); - template.insert(new Venue("Momofuku Milk Bar", -73.985839, 40.731698)); - template.insert(new Venue("Shake Shack", -73.98820, 40.74164)); - template.insert(new Venue("Penn Station", -73.99408, 40.75057)); - template.insert(new Venue("Empire State Building", -73.98602, 40.74894)); - //template.insert(new Venue("Washington Square Park", -73.99756, 40.73083)); - template.insert(new Venue("Ulaanbaatar, Mongolia", 106.9154, 47.9245)); - template.insert(new Venue("Maplewood, NJ", -74.2713, 40.73137)); - } + @Before + public void setUp() throws Exception { + Mongo mongo = new Mongo(); + serverInfo = new ServerInfo(mongo); + DB db = mongo.getDB("geospatial"); + for (String coll : collectionsToDrop) { + db.getCollection(coll).drop(); + } + applicationContext = new AnnotationConfigApplicationContext(GeoSpatialAppConfig.class); + template = applicationContext.getBean(MongoTemplate.class); + template.setWriteConcern(WriteConcern.FSYNC_SAFE); + template.ensureIndex(Venue.class, new GeospatialIndex("location")); + indexCreated(); + addVenues(); + parser = new SpelExpressionParser(); + } - /* - public void geoNear() { - GeoNearResult geoNearResult = template.geoNear(new Query(Criteria.where("type").is("Office")), Venue.class, - GeoNearCriteria.near(2,3).num(10).maxDistance(10).distanceMultiplier(10).spherical(true)); - }*/ + private void addVenues() { - @Test - public void withinCenter() { - - Circle circle = new Circle(-73.99171, 40.738868, 0.01); - List venues = template.find(new Query(Criteria.where("location").withinCenter(circle)), Venue.class); - assertThat(venues.size(), equalTo(7)); - } - - @Test - @Ignore("run only on v 1.7.0 server or greater") - public void withinCenterSphere() { - Circle circle = new Circle(-73.99171, 40.738868, 0.003712240453784); - List venues = template.find(new Query(Criteria.where("location").withinCenterSphere(circle)), Venue.class); - assertThat(venues.size(), equalTo(11)); - } - - - @Test - public void withinBox() { - Box box = new Box(new Point(-73.99756, 40.73083), new Point(-73.988135, 40.741404)); - //Box box = newBox.lowerLeft(x,y).upperRight(x,y); - List venues = template.find(new Query(Criteria.where("location").withinBox(box)), Venue.class); - assertThat(venues.size(), equalTo(4)); - } - - @Test - public void nearPoint() { - Point point = new Point(-73.99171, 40.738868); - List venues = template.find(new Query(Criteria.where("location").near(point).maxDistance(0.01)), Venue.class); - assertThat(venues.size(), equalTo(7)); - } - - @Test - @Ignore("run only on v 1.7.0 server or greater") - public void nearSphere() { - Point point = new Point(-73.99171, 40.738868); - List venues = template.find(new Query(Criteria.where("location").nearSphere(point).maxDistance(0.003712240453784)), Venue.class); - assertThat(venues.size(), equalTo(11)); - } - + template.insert(new Venue("Penn Station", -73.99408, 40.75057)); + template.insert(new Venue("10gen Office", -73.99171, 40.738868)); + template.insert(new Venue("Flatiron Building", -73.988135, 40.741404)); + template.insert(new Venue("Players Club", -73.997812, 40.739128)); + template.insert(new Venue("City Bakery ", -73.992491, 40.738673)); + template.insert(new Venue("Splash Bar", -73.992491, 40.738673)); + template.insert(new Venue("Momofuku Milk Bar", -73.985839, 40.731698)); + template.insert(new Venue("Shake Shack", -73.98820, 40.74164)); + template.insert(new Venue("Penn Station", -73.99408, 40.75057)); + template.insert(new Venue("Empire State Building", -73.98602, 40.74894)); + // template.insert(new Venue("Washington Square Park", -73.99756, 40.73083)); + template.insert(new Venue("Ulaanbaatar, Mongolia", 106.9154, 47.9245)); + template.insert(new Venue("Maplewood, NJ", -74.2713, 40.73137)); + } + /* + public void geoNear() { + GeoNearResult geoNearResult = template.geoNear(new Query(Criteria.where("type").is("Office")), Venue.class, + GeoNearCriteria.near(2,3).num(10).maxDistance(10).distanceMultiplier(10).spherical(true)); + }*/ - @Test - public void searchAllData() { - assertThat(template, notNullValue()); - Venue foundVenue = template.findOne( - new Query(Criteria.where("name").is("Penn Station")), Venue.class); - assertThat(foundVenue, notNullValue()); - List venues = template.getCollection(Venue.class); - assertThat(venues.size(), equalTo(12)); - Collection names = (Collection)parser.parseExpression("![name]").getValue(venues); - assertThat(names.size(), equalTo(12)); - org.springframework.util.Assert.notEmpty(names); - - } - - public void indexCreated() { - List indexInfo = getIndexInfo(Venue.class); - LOGGER.debug(indexInfo); - assertThat(indexInfo.size(), equalTo(2)); - assertThat(indexInfo.get(1).get("name").toString(), equalTo("location_2d")); - assertThat(indexInfo.get(1).get("ns").toString(), - equalTo("geospatial.newyork")); - } + @Test + public void withinCenter() { - // TODO move to MongoAdmin - public List getIndexInfo(Class clazz) { - return template.execute(clazz, new CollectionCallback>() { + Circle circle = new Circle(-73.99171, 40.738868, 0.01); + List venues = template.find(new Query(Criteria.where("location").withinCenter(circle)), Venue.class); + assertThat(venues.size(), equalTo(7)); + } - public List doInCollection(DBCollection collection) - throws MongoException, DataAccessException { - return collection.getIndexInfo(); - } - }); - } - + @Test + @Ignore("run only on v 1.7.0 server or greater") + public void withinCenterSphere() { + Circle circle = new Circle(-73.99171, 40.738868, 0.003712240453784); + List venues = template.find(new Query(Criteria.where("location").withinCenterSphere(circle)), Venue.class); + assertThat(venues.size(), equalTo(11)); + } + + @Test + public void withinBox() { + Box box = new Box(new Point(-73.99756, 40.73083), new Point(-73.988135, 40.741404)); + // Box box = newBox.lowerLeft(x,y).upperRight(x,y); + List venues = template.find(new Query(Criteria.where("location").withinBox(box)), Venue.class); + assertThat(venues.size(), equalTo(4)); + } + + @Test + public void nearPoint() { + Point point = new Point(-73.99171, 40.738868); + List venues = template + .find(new Query(Criteria.where("location").near(point).maxDistance(0.01)), Venue.class); + assertThat(venues.size(), equalTo(7)); + } + + @Test + @Ignore("run only on v 1.7.0 server or greater") + public void nearSphere() { + Point point = new Point(-73.99171, 40.738868); + List venues = template.find( + new Query(Criteria.where("location").nearSphere(point).maxDistance(0.003712240453784)), Venue.class); + assertThat(venues.size(), equalTo(11)); + } + + @Test + public void searchAllData() { + assertThat(template, notNullValue()); + Venue foundVenue = template.findOne(new Query(Criteria.where("name").is("Penn Station")), Venue.class); + assertThat(foundVenue, notNullValue()); + List venues = template.getCollection(Venue.class); + assertThat(venues.size(), equalTo(12)); + Collection names = (Collection) parser.parseExpression("![name]").getValue(venues); + assertThat(names.size(), equalTo(12)); + org.springframework.util.Assert.notEmpty(names); + + } + + public void indexCreated() { + List indexInfo = getIndexInfo(Venue.class); + LOGGER.debug(indexInfo); + assertThat(indexInfo.size(), equalTo(2)); + assertThat(indexInfo.get(1).get("name").toString(), equalTo("location_2d")); + assertThat(indexInfo.get(1).get("ns").toString(), equalTo("geospatial.newyork")); + } + + // TODO move to MongoAdmin + public List getIndexInfo(Class clazz) { + return template.execute(clazz, new CollectionCallback>() { + + public List doInCollection(DBCollection collection) throws MongoException, DataAccessException { + return collection.getIndexInfo(); + } + }); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/JmxServer.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/JmxServer.java index 7cc1795ae..07be413e9 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/JmxServer.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/JmxServer.java @@ -20,17 +20,17 @@ import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Server application than can be run as an app or unit test. - * + * * @author Mark Pollack */ public class JmxServer { - public static void main(String[] args) { - new JmxServer().run(); - } + public static void main(String[] args) { + new JmxServer().run(); + } - public void run() { - new ClassPathXmlApplicationContext(new String[]{"infrastructure.xml", "server-jmx.xml"}); - } + public void run() { + new ClassPathXmlApplicationContext(new String[] { "infrastructure.xml", "server-jmx.xml" }); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Message.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Message.java index 09fdd7583..a2192c173 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Message.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Message.java @@ -21,55 +21,54 @@ import org.bson.types.ObjectId; public class Message { - private ObjectId id; + private ObjectId id; - private String text; + private String text; - private Date timestamp; + private Date timestamp; - public Message() { - } - - public Message(String text) { - super(); - this.text = text; - this.timestamp = new Date(); - } + public Message() { + } - public Message(String text, Date timestamp) { - super(); - this.text = text; - this.timestamp = timestamp; - } + public Message(String text) { + super(); + this.text = text; + this.timestamp = new Date(); + } - public ObjectId getId() { - return id; - } + public Message(String text, Date timestamp) { + super(); + this.text = text; + this.timestamp = timestamp; + } - public void setId(ObjectId id) { - this.id = id; - } + public ObjectId getId() { + return id; + } - public String getText() { - return text; - } + public void setId(ObjectId id) { + this.id = id; + } - public void setText(String text) { - this.text = text; - } + public String getText() { + return text; + } - public Date getTimestamp() { - return timestamp; - } + public void setText(String text) { + this.text = text; + } - public void setTimestamp(Date timestamp) { - this.timestamp = timestamp; - } + public Date getTimestamp() { + return timestamp; + } - @Override - public String toString() { - return "Message [id=" + id + ", text=" + text + ", timestamp=" + timestamp - + "]"; - } + public void setTimestamp(Date timestamp) { + this.timestamp = timestamp; + } + + @Override + public String toString() { + return "Message [id=" + id + ", text=" + text + ", timestamp=" + timestamp + "]"; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoAdminIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoAdminIntegrationTests.java index 97c05146d..41c244af7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoAdminIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoAdminIntegrationTests.java @@ -27,36 +27,35 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - /** * This test class assumes that you are already running the MongoDB server. - * + * * @author Mark Pollack */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:infrastructure.xml") public class MongoAdminIntegrationTests { - private static Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class); + private static Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class); - private MongoAdminOperations mongoAdmin; + private MongoAdminOperations mongoAdmin; - private DB testAdminDb; + private DB testAdminDb; - @Autowired - Mongo mongo; + @Autowired + Mongo mongo; - @Before - public void setUp() { - mongo.getDB("testAdminDb").dropDatabase(); - testAdminDb = mongo.getDB("testAdminDb"); + @Before + public void setUp() { + mongo.getDB("testAdminDb").dropDatabase(); + testAdminDb = mongo.getDB("testAdminDb"); - } + } - @Test - public void serverStats() { - //CommandResult result = testAdminDb.getStats(); - CommandResult result = mongo.getDB("admin").command("serverStatus"); - logger.info("stats = " + result); - } + @Test + public void serverStats() { + // CommandResult result = testAdminDb.getStats(); + CommandResult result = mongo.getDB("admin").command("serverStatus"); + logger.info("stats = " + result); + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoOperationsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoOperationsUnitTests.java index 9e44c8293..27e1bd485 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoOperationsUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoOperationsUnitTests.java @@ -39,7 +39,7 @@ import org.springframework.data.mapping.model.MappingContext; /** * Abstract base class for unit tests to specify behaviour we expect from {@link MongoOperations}. Subclasses return * instances of their implementation and thus can see if it correctly implements the {@link MongoOperations} interface. - * + * * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) @@ -86,20 +86,20 @@ public abstract class MongoOperationsUnitTests { } @Test(expected = IllegalArgumentException.class) - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public void rejectsNullForCollectionCallback() { getOperations().execute("test", (CollectionCallback) null); } @Test(expected = IllegalArgumentException.class) - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public void rejectsNullForCollectionCallback2() { getOperations().execute("collection", (CollectionCallback) null); } @Test(expected = IllegalArgumentException.class) - @SuppressWarnings({"unchecked", "rawtypes"}) + @SuppressWarnings({ "unchecked", "rawtypes" }) public void rejectsNullForDbCallback() { getOperations().execute((DbCallback) null); } @@ -316,14 +316,14 @@ public abstract class MongoOperationsUnitTests { /** * Expects an {@link MongoOperations} instance that will be used to check that invoking methods on it will only cause * {@link DataAccessException}s. - * + * * @return */ protected abstract MongoOperations getOperationsForExceptionHandling(); /** * Returns a plain {@link MongoOperations}. - * + * * @return */ protected abstract MongoOperations getOperations(); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java index 1f3721441..fd00654a7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateMappingTests.java @@ -41,7 +41,7 @@ import com.mongodb.MongoException; /** * Integration test for {@link MongoTemplate}. - * + * * @author Oliver Gierke * @author Thomas Risberg */ @@ -49,59 +49,58 @@ import com.mongodb.MongoException; @ContextConfiguration("classpath:template-mapping.xml") public class MongoTemplateMappingTests { - @Autowired - @Qualifier("mongoTemplate1") - MongoTemplate template1; - - @Autowired - @Qualifier("mongoTemplate2") - MongoTemplate template2; + @Autowired + @Qualifier("mongoTemplate1") + MongoTemplate template1; - @Rule - public ExpectedException thrown = ExpectedException.none(); + @Autowired + @Qualifier("mongoTemplate2") + MongoTemplate template2; -@Before - public void setUp() { - template1.dropCollection(template1.getCollectionName(Person.class)); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); - @Test - public void insertsEntityCorrectly1() throws Exception { + @Before + public void setUp() { + template1.dropCollection(template1.getCollectionName(Person.class)); + } - addAndRetrievePerson(template1); - checkPersonPersisted(template1); + @Test + public void insertsEntityCorrectly1() throws Exception { - } - - @Test - public void insertsEntityCorrectly2() throws Exception { + addAndRetrievePerson(template1); + checkPersonPersisted(template1); - addAndRetrievePerson(template2); - checkPersonPersisted(template2); - - } + } - private void addAndRetrievePerson(MongoTemplate template) { + @Test + public void insertsEntityCorrectly2() throws Exception { + + addAndRetrievePerson(template2); + checkPersonPersisted(template2); + + } + + private void addAndRetrievePerson(MongoTemplate template) { Person person = new Person("Oliver"); - person.setAge(25); - template.insert(person); + person.setAge(25); + template.insert(person); - List result = template.find(new Query(Criteria.where("_id").is(person.getId())), Person.class); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(person)); - assertThat(result.get(0).getFirstName(), is("Oliver")); - assertThat(result.get(0).getAge(), is(25)); - } - - private void checkPersonPersisted(MongoTemplate template) { - template.execute(Person.class, new CollectionCallback() { - public Object doInCollection(DBCollection collection) - throws MongoException, DataAccessException { - DBObject dbo = collection.findOne(); - assertThat((String)dbo.get("name"), is("Oliver")); - return null; - } - }); - } + List result = template.find(new Query(Criteria.where("_id").is(person.getId())), Person.class); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(person)); + assertThat(result.get(0).getFirstName(), is("Oliver")); + assertThat(result.get(0).getAge(), is(25)); + } + + private void checkPersonPersisted(MongoTemplate template) { + template.execute(Person.class, new CollectionCallback() { + public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { + DBObject dbo = collection.findOne(); + assertThat((String) dbo.get("name"), is("Oliver")); + return null; + } + }); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateTests.java index af6b1cacb..1cbec252f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateTests.java @@ -58,7 +58,7 @@ import com.mongodb.WriteResult; /** * Integration test for {@link MongoTemplate}. - * + * * @author Oliver Gierke * @author Thomas Risberg */ @@ -66,440 +66,450 @@ import com.mongodb.WriteResult; @ContextConfiguration("classpath:infrastructure.xml") public class MongoTemplateTests { - @Autowired - MongoTemplate template; - - MongoTemplate mappingTemplate; + @Autowired + MongoTemplate template; - @Rule - public ExpectedException thrown = ExpectedException.none(); + MongoTemplate mappingTemplate; - @Autowired - @SuppressWarnings("unchecked") - public void setMongo(Mongo mongo) throws Exception { - - MongoMappingContext mappingContext = new MongoMappingContext(); - mappingContext.setInitialEntitySet(new HashSet>(Arrays.asList(PersonWith_idPropertyOfTypeObjectId.class, - PersonWith_idPropertyOfTypeString.class, PersonWithIdPropertyOfTypeObjectId.class, - PersonWithIdPropertyOfTypeString.class))); - mappingContext.afterPropertiesSet(); - - MappingMongoConverter converter = new MappingMongoConverter(mappingContext); - converter.afterPropertiesSet(); - - this.mappingTemplate = new MongoTemplate(mongo, "database", converter); - } + @Rule + public ExpectedException thrown = ExpectedException.none(); -@Before - public void setUp() { - template.dropCollection(template.getCollectionName(Person.class)); - template.dropCollection(template.getCollectionName(PersonWith_idPropertyOfTypeObjectId.class)); - template.dropCollection(template.getCollectionName(PersonWith_idPropertyOfTypeString.class)); - template.dropCollection(template.getCollectionName(PersonWithIdPropertyOfTypeObjectId.class)); - template.dropCollection(template.getCollectionName(PersonWithIdPropertyOfTypeString.class)); - } + @Autowired + @SuppressWarnings("unchecked") + public void setMongo(Mongo mongo) throws Exception { - @Test - public void insertsSimpleEntityCorrectly() throws Exception { + MongoMappingContext mappingContext = new MongoMappingContext(); + mappingContext.setInitialEntitySet(new HashSet>(Arrays.asList(PersonWith_idPropertyOfTypeObjectId.class, + PersonWith_idPropertyOfTypeString.class, PersonWithIdPropertyOfTypeObjectId.class, + PersonWithIdPropertyOfTypeString.class))); + mappingContext.afterPropertiesSet(); - Person person = new Person("Oliver"); - person.setAge(25); - template.insert(person); + MappingMongoConverter converter = new MappingMongoConverter(mappingContext); + converter.afterPropertiesSet(); - MongoConverter converter = template.getConverter(); + this.mappingTemplate = new MongoTemplate(mongo, "database", converter); + } - List result = template.find(new Query(Criteria.where("_id").is(converter.convertObjectId(person.getId()))), Person.class); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(person)); - } + @Before + public void setUp() { + template.dropCollection(template.getCollectionName(Person.class)); + template.dropCollection(template.getCollectionName(PersonWith_idPropertyOfTypeObjectId.class)); + template.dropCollection(template.getCollectionName(PersonWith_idPropertyOfTypeString.class)); + template.dropCollection(template.getCollectionName(PersonWithIdPropertyOfTypeObjectId.class)); + template.dropCollection(template.getCollectionName(PersonWithIdPropertyOfTypeString.class)); + } - @Test - public void updateFailure() throws Exception { + @Test + public void insertsSimpleEntityCorrectly() throws Exception { - MongoTemplate mongoTemplate = new MongoTemplate(template.getDb().getMongo(), "test"); - mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION); + Person person = new Person("Oliver"); + person.setAge(25); + template.insert(person); - Person person = new Person("Oliver2"); - person.setAge(25); - mongoTemplate.insert(person); + MongoConverter converter = template.getConverter(); - Query q = new Query(Criteria.where("BOGUS").gt(22)); - Update u = new Update().set("firstName", "Sven"); - thrown.expect(DataIntegrityViolationException.class); - thrown.expectMessage(endsWith("0 documents updated")); - mongoTemplate.updateFirst(Person.class, q, u); + List result = template.find(new Query(Criteria.where("_id").is(converter.convertObjectId(person.getId()))), + Person.class); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(person)); + } - } + @Test + public void updateFailure() throws Exception { - @Test - public void testEnsureIndex() throws Exception { + MongoTemplate mongoTemplate = new MongoTemplate(template.getDb().getMongo(), "test"); + mongoTemplate.setWriteResultChecking(WriteResultChecking.EXCEPTION); - Person p1 = new Person("Oliver"); - p1.setAge(25); - template.insert(p1); - Person p2 = new Person("Sven"); - p2.setAge(40); - template.insert(p2); + Person person = new Person("Oliver2"); + person.setAge(25); + mongoTemplate.insert(person); - template.ensureIndex(Person.class, new Index().on("age", Order.DESCENDING).unique(Duplicates.DROP)); + Query q = new Query(Criteria.where("BOGUS").gt(22)); + Update u = new Update().set("firstName", "Sven"); + thrown.expect(DataIntegrityViolationException.class); + thrown.expectMessage(endsWith("0 documents updated")); + mongoTemplate.updateFirst(Person.class, q, u); - DBCollection coll = template.getCollection(template.getCollectionName(Person.class)); - List indexInfo = coll.getIndexInfo(); + } - assertThat(indexInfo.size(), is(2)); - String indexKey = null; - boolean unique = false; - boolean dropDupes = false; - for (DBObject ix : indexInfo) { - if ("age_-1".equals(ix.get("name"))) { - indexKey = ix.get("key").toString(); - unique = (Boolean) ix.get("unique"); - dropDupes = (Boolean) ix.get("dropDups"); - } - } - assertThat(indexKey, is("{ \"age\" : -1}")); - assertThat(unique, is(true)); - assertThat(dropDupes, is(true)); - } + @Test + public void testEnsureIndex() throws Exception { - @Test - public void testProperHandlingOfDifferentIdTypesWithSimpleMongoConverter() throws Exception { - testProperHandlingOfDifferentIdTypes(this.template); - } + Person p1 = new Person("Oliver"); + p1.setAge(25); + template.insert(p1); + Person p2 = new Person("Sven"); + p2.setAge(40); + template.insert(p2); - @Test - public void testProperHandlingOfDifferentIdTypesWithMappingMongoConverter() throws Exception { - testProperHandlingOfDifferentIdTypes(this.mappingTemplate); - } + template.ensureIndex(Person.class, new Index().on("age", Order.DESCENDING).unique(Duplicates.DROP)); - private void testProperHandlingOfDifferentIdTypes(MongoTemplate mongoTemplate) throws Exception { - PersonWithIdPropertyOfTypeString p1 = new PersonWithIdPropertyOfTypeString(); - p1.setFirstName("Sven_1"); - p1.setAge(22); - // insert - mongoTemplate.insert(p1); - // also try save - mongoTemplate.save(p1); - assertThat(p1.getId(), notNullValue()); - PersonWithIdPropertyOfTypeString p1q = mongoTemplate.findOne(new Query(where("id").is(p1.getId())), PersonWithIdPropertyOfTypeString.class); - assertThat(p1q, notNullValue()); - assertThat(p1q.getId(), is(p1.getId())); + DBCollection coll = template.getCollection(template.getCollectionName(Person.class)); + List indexInfo = coll.getIndexInfo(); - PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString(); - p2.setFirstName("Sven_2"); - p2.setAge(22); - p2.setId("TWO"); - // insert - mongoTemplate.insert(p2); - // also try save - mongoTemplate.save(p2); - assertThat(p2.getId(), notNullValue()); - PersonWithIdPropertyOfTypeString p2q = mongoTemplate.findOne(new Query(where("id").is(p2.getId())), PersonWithIdPropertyOfTypeString.class); - assertThat(p2q, notNullValue()); - assertThat(p2q.getId(), is(p2.getId())); + assertThat(indexInfo.size(), is(2)); + String indexKey = null; + boolean unique = false; + boolean dropDupes = false; + for (DBObject ix : indexInfo) { + if ("age_-1".equals(ix.get("name"))) { + indexKey = ix.get("key").toString(); + unique = (Boolean) ix.get("unique"); + dropDupes = (Boolean) ix.get("dropDups"); + } + } + assertThat(indexKey, is("{ \"age\" : -1}")); + assertThat(unique, is(true)); + assertThat(dropDupes, is(true)); + } - PersonWith_idPropertyOfTypeString p3 = new PersonWith_idPropertyOfTypeString(); - p3.setFirstName("Sven_3"); - p3.setAge(22); - // insert - mongoTemplate.insert(p3); - // also try save - mongoTemplate.save(p3); - assertThat(p3.get_id(), notNullValue()); - PersonWith_idPropertyOfTypeString p3q = mongoTemplate.findOne(new Query(where("_id").is(p3.get_id())), PersonWith_idPropertyOfTypeString.class); - assertThat(p3q, notNullValue()); - assertThat(p3q.get_id(), is(p3.get_id())); + @Test + public void testProperHandlingOfDifferentIdTypesWithSimpleMongoConverter() throws Exception { + testProperHandlingOfDifferentIdTypes(this.template); + } - PersonWith_idPropertyOfTypeString p4 = new PersonWith_idPropertyOfTypeString(); - p4.setFirstName("Sven_4"); - p4.setAge(22); - p4.set_id("FOUR"); - // insert - mongoTemplate.insert(p4); - // also try save - mongoTemplate.save(p4); - assertThat(p4.get_id(), notNullValue()); - PersonWith_idPropertyOfTypeString p4q = mongoTemplate.findOne(new Query(where("_id").is(p4.get_id())), PersonWith_idPropertyOfTypeString.class); - assertThat(p4q, notNullValue()); - assertThat(p4q.get_id(), is(p4.get_id())); + @Test + public void testProperHandlingOfDifferentIdTypesWithMappingMongoConverter() throws Exception { + testProperHandlingOfDifferentIdTypes(this.mappingTemplate); + } - PersonWithIdPropertyOfTypeObjectId p5 = new PersonWithIdPropertyOfTypeObjectId(); - p5.setFirstName("Sven_5"); - p5.setAge(22); - // insert - mongoTemplate.insert(p5); - // also try save - mongoTemplate.save(p5); - assertThat(p5.getId(), notNullValue()); - PersonWithIdPropertyOfTypeObjectId p5q = mongoTemplate.findOne(new Query(where("id").is(p5.getId())), PersonWithIdPropertyOfTypeObjectId.class); - assertThat(p5q, notNullValue()); - assertThat(p5q.getId(), is(p5.getId())); + private void testProperHandlingOfDifferentIdTypes(MongoTemplate mongoTemplate) throws Exception { + PersonWithIdPropertyOfTypeString p1 = new PersonWithIdPropertyOfTypeString(); + p1.setFirstName("Sven_1"); + p1.setAge(22); + // insert + mongoTemplate.insert(p1); + // also try save + mongoTemplate.save(p1); + assertThat(p1.getId(), notNullValue()); + PersonWithIdPropertyOfTypeString p1q = mongoTemplate.findOne(new Query(where("id").is(p1.getId())), + PersonWithIdPropertyOfTypeString.class); + assertThat(p1q, notNullValue()); + assertThat(p1q.getId(), is(p1.getId())); - PersonWithIdPropertyOfTypeObjectId p6 = new PersonWithIdPropertyOfTypeObjectId(); - p6.setFirstName("Sven_6"); - p6.setAge(22); - p6.setId(new ObjectId()); - // insert - mongoTemplate.insert(p6); - // also try save - mongoTemplate.save(p6); - assertThat(p6.getId(), notNullValue()); - PersonWithIdPropertyOfTypeObjectId p6q = mongoTemplate.findOne(new Query(where("id").is(p6.getId())), PersonWithIdPropertyOfTypeObjectId.class); - assertThat(p6q, notNullValue()); - assertThat(p6q.getId(), is(p6.getId())); + PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString(); + p2.setFirstName("Sven_2"); + p2.setAge(22); + p2.setId("TWO"); + // insert + mongoTemplate.insert(p2); + // also try save + mongoTemplate.save(p2); + assertThat(p2.getId(), notNullValue()); + PersonWithIdPropertyOfTypeString p2q = mongoTemplate.findOne(new Query(where("id").is(p2.getId())), + PersonWithIdPropertyOfTypeString.class); + assertThat(p2q, notNullValue()); + assertThat(p2q.getId(), is(p2.getId())); - PersonWith_idPropertyOfTypeObjectId p7 = new PersonWith_idPropertyOfTypeObjectId(); - p7.setFirstName("Sven_7"); - p7.setAge(22); - // insert - mongoTemplate.insert(p7); - // also try save - mongoTemplate.save(p7); - assertThat(p7.get_id(), notNullValue()); - PersonWith_idPropertyOfTypeObjectId p7q = mongoTemplate.findOne(new Query(where("_id").is(p7.get_id())), PersonWith_idPropertyOfTypeObjectId.class); - assertThat(p7q, notNullValue()); - assertThat(p7q.get_id(), is(p7.get_id())); + PersonWith_idPropertyOfTypeString p3 = new PersonWith_idPropertyOfTypeString(); + p3.setFirstName("Sven_3"); + p3.setAge(22); + // insert + mongoTemplate.insert(p3); + // also try save + mongoTemplate.save(p3); + assertThat(p3.get_id(), notNullValue()); + PersonWith_idPropertyOfTypeString p3q = mongoTemplate.findOne(new Query(where("_id").is(p3.get_id())), + PersonWith_idPropertyOfTypeString.class); + assertThat(p3q, notNullValue()); + assertThat(p3q.get_id(), is(p3.get_id())); - PersonWith_idPropertyOfTypeObjectId p8 = new PersonWith_idPropertyOfTypeObjectId(); - p8.setFirstName("Sven_8"); - p8.setAge(22); - p8.set_id(new ObjectId()); - // insert - mongoTemplate.insert(p8); - // also try save - mongoTemplate.save(p8); - assertThat(p8.get_id(), notNullValue()); - PersonWith_idPropertyOfTypeObjectId p8q = mongoTemplate.findOne(new Query(where("_id").is(p8.get_id())), PersonWith_idPropertyOfTypeObjectId.class); - assertThat(p8q, notNullValue()); - assertThat(p8q.get_id(), is(p8.get_id())); - } + PersonWith_idPropertyOfTypeString p4 = new PersonWith_idPropertyOfTypeString(); + p4.setFirstName("Sven_4"); + p4.setAge(22); + p4.set_id("FOUR"); + // insert + mongoTemplate.insert(p4); + // also try save + mongoTemplate.save(p4); + assertThat(p4.get_id(), notNullValue()); + PersonWith_idPropertyOfTypeString p4q = mongoTemplate.findOne(new Query(where("_id").is(p4.get_id())), + PersonWith_idPropertyOfTypeString.class); + assertThat(p4q, notNullValue()); + assertThat(p4q.get_id(), is(p4.get_id())); - @Test - public void testFindAndRemove() throws Exception { + PersonWithIdPropertyOfTypeObjectId p5 = new PersonWithIdPropertyOfTypeObjectId(); + p5.setFirstName("Sven_5"); + p5.setAge(22); + // insert + mongoTemplate.insert(p5); + // also try save + mongoTemplate.save(p5); + assertThat(p5.getId(), notNullValue()); + PersonWithIdPropertyOfTypeObjectId p5q = mongoTemplate.findOne(new Query(where("id").is(p5.getId())), + PersonWithIdPropertyOfTypeObjectId.class); + assertThat(p5q, notNullValue()); + assertThat(p5q.getId(), is(p5.getId())); - Message m1 = new Message("Hello Spring"); - template.insert(m1); - Message m2 = new Message("Hello Mongo"); - template.insert(m2); + PersonWithIdPropertyOfTypeObjectId p6 = new PersonWithIdPropertyOfTypeObjectId(); + p6.setFirstName("Sven_6"); + p6.setAge(22); + p6.setId(new ObjectId()); + // insert + mongoTemplate.insert(p6); + // also try save + mongoTemplate.save(p6); + assertThat(p6.getId(), notNullValue()); + PersonWithIdPropertyOfTypeObjectId p6q = mongoTemplate.findOne(new Query(where("id").is(p6.getId())), + PersonWithIdPropertyOfTypeObjectId.class); + assertThat(p6q, notNullValue()); + assertThat(p6q.getId(), is(p6.getId())); - Query q = new Query(Criteria.where("text").regex("^Hello.*")); - Message found1 = template.findAndRemove(q, Message.class); - Message found2 = template.findAndRemove(q, Message.class); -// Message notFound = template.findAndRemove(q, Message.class); - DBObject notFound = template.getCollection("").findAndRemove(q.getQueryObject()); - assertThat(found1, notNullValue()); - assertThat(found2, notNullValue()); - assertThat(notFound, nullValue()); - } + PersonWith_idPropertyOfTypeObjectId p7 = new PersonWith_idPropertyOfTypeObjectId(); + p7.setFirstName("Sven_7"); + p7.setAge(22); + // insert + mongoTemplate.insert(p7); + // also try save + mongoTemplate.save(p7); + assertThat(p7.get_id(), notNullValue()); + PersonWith_idPropertyOfTypeObjectId p7q = mongoTemplate.findOne(new Query(where("_id").is(p7.get_id())), + PersonWith_idPropertyOfTypeObjectId.class); + assertThat(p7q, notNullValue()); + assertThat(p7q.get_id(), is(p7.get_id())); - @Test - public void testUsingAnInQuery() throws Exception { - - template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); + PersonWith_idPropertyOfTypeObjectId p8 = new PersonWith_idPropertyOfTypeObjectId(); + p8.setFirstName("Sven_8"); + p8.setAge(22); + p8.set_id(new ObjectId()); + // insert + mongoTemplate.insert(p8); + // also try save + mongoTemplate.save(p8); + assertThat(p8.get_id(), notNullValue()); + PersonWith_idPropertyOfTypeObjectId p8q = mongoTemplate.findOne(new Query(where("_id").is(p8.get_id())), + PersonWith_idPropertyOfTypeObjectId.class); + assertThat(p8q, notNullValue()); + assertThat(p8q.get_id(), is(p8.get_id())); + } - PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); - p1.setFirstName("Sven"); - p1.setAge(11); - template.insert(p1); - PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); - p2.setFirstName("Mary"); - p2.setAge(21); - template.insert(p2); - PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); - p3.setFirstName("Ann"); - p3.setAge(31); - template.insert(p3); - PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); - p4.setFirstName("John"); - p4.setAge(41); - template.insert(p4); + @Test + public void testFindAndRemove() throws Exception { - Query q1 = new Query(Criteria.where("age").in(11, 21, 41)); - List results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); - Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary")); - List results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); - Query q3 = new Query(Criteria.where("id").in(p3.getId())); - List results3 = template.find(q3, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(results1.size(), is(3)); - assertThat(results2.size(), is(2)); - assertThat(results3.size(), is(1)); - } + Message m1 = new Message("Hello Spring"); + template.insert(m1); + Message m2 = new Message("Hello Mongo"); + template.insert(m2); - @Test - public void testUsingInQueryWithList() throws Exception { - - template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); + Query q = new Query(Criteria.where("text").regex("^Hello.*")); + Message found1 = template.findAndRemove(q, Message.class); + Message found2 = template.findAndRemove(q, Message.class); + // Message notFound = template.findAndRemove(q, Message.class); + DBObject notFound = template.getCollection("").findAndRemove(q.getQueryObject()); + assertThat(found1, notNullValue()); + assertThat(found2, notNullValue()); + assertThat(notFound, nullValue()); + } - PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); - p1.setFirstName("Sven"); - p1.setAge(11); - template.insert(p1); - PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); - p2.setFirstName("Mary"); - p2.setAge(21); - template.insert(p2); - PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); - p3.setFirstName("Ann"); - p3.setAge(31); - template.insert(p3); - PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); - p4.setFirstName("John"); - p4.setAge(41); - template.insert(p4); + @Test + public void testUsingAnInQuery() throws Exception { - List l1 = new ArrayList(); - l1.add(11); - l1.add(21); - l1.add(41); - Query q1 = new Query(Criteria.where("age").in(l1)); - List results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); - Query q2 = new Query(Criteria.where("age").in(l1.toArray())); - List results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(results1.size(), is(3)); - assertThat(results2.size(), is(3)); - try { - List l2 = new ArrayList(); - l2.add(31); - Query q3 = new Query(Criteria.where("age").in(l1, l2)); - template.find(q3, PersonWithIdPropertyOfTypeObjectId.class); - Assert.fail("Should have trown an InvalidDocumentStoreApiUsageException"); - } catch (InvalidDocumentStoreApiUsageException e) {} - } + template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); - @Test - public void testUsingAnOrQuery() throws Exception { - - template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); + PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); + p1.setFirstName("Sven"); + p1.setAge(11); + template.insert(p1); + PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); + p2.setFirstName("Mary"); + p2.setAge(21); + template.insert(p2); + PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); + p3.setFirstName("Ann"); + p3.setAge(31); + template.insert(p3); + PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); + p4.setFirstName("John"); + p4.setAge(41); + template.insert(p4); - PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); - p1.setFirstName("Sven"); - p1.setAge(11); - template.insert(p1); - PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); - p2.setFirstName("Mary"); - p2.setAge(21); - template.insert(p2); - PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); - p3.setFirstName("Ann"); - p3.setAge(31); - template.insert(p3); - PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); - p4.setFirstName("John"); - p4.setAge(41); - template.insert(p4); + Query q1 = new Query(Criteria.where("age").in(11, 21, 41)); + List results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); + Query q2 = new Query(Criteria.where("firstName").in("Ann", "Mary")); + List results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); + Query q3 = new Query(Criteria.where("id").in(p3.getId())); + List results3 = template.find(q3, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(results1.size(), is(3)); + assertThat(results2.size(), is(2)); + assertThat(results3.size(), is(1)); + } - Query q1 = new Query(Criteria.where("age").in(11, 21)); - Query q2 = new Query(Criteria.where("age").is(31)); - Query orQuery = new Query().or(q1, q2); - List results = template.find(orQuery, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(results.size(), is(3)); - for (PersonWithIdPropertyOfTypeObjectId p : results) { - assertThat(p.getAge(), isOneOf(11, 21, 31)); - } - } + @Test + public void testUsingInQueryWithList() throws Exception { - @Test - public void testUsingUpdateWithMultipleSet() throws Exception { + template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); - template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); + PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); + p1.setFirstName("Sven"); + p1.setAge(11); + template.insert(p1); + PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); + p2.setFirstName("Mary"); + p2.setAge(21); + template.insert(p2); + PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); + p3.setFirstName("Ann"); + p3.setAge(31); + template.insert(p3); + PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); + p4.setFirstName("John"); + p4.setAge(41); + template.insert(p4); - PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); - p1.setFirstName("Sven"); - p1.setAge(11); - template.insert(p1); - PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); - p2.setFirstName("Mary"); - p2.setAge(21); - template.insert(p2); + List l1 = new ArrayList(); + l1.add(11); + l1.add(21); + l1.add(41); + Query q1 = new Query(Criteria.where("age").in(l1)); + List results1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); + Query q2 = new Query(Criteria.where("age").in(l1.toArray())); + List results2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(results1.size(), is(3)); + assertThat(results2.size(), is(3)); + try { + List l2 = new ArrayList(); + l2.add(31); + Query q3 = new Query(Criteria.where("age").in(l1, l2)); + template.find(q3, PersonWithIdPropertyOfTypeObjectId.class); + Assert.fail("Should have trown an InvalidDocumentStoreApiUsageException"); + } catch (InvalidDocumentStoreApiUsageException e) { + } + } - Update u = new Update().set("firstName", "Bob").set("age", 10); - - WriteResult wr = template.updateMulti(PersonWithIdPropertyOfTypeObjectId.class, new Query(), u); - - assertThat(wr.getN(), is(2)); - - Query q1 = new Query(Criteria.where("age").in(11, 21)); - List r1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(r1.size(), is(0)); - Query q2 = new Query(Criteria.where("age").is(10)); - List r2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(r2.size(), is(2)); - for (PersonWithIdPropertyOfTypeObjectId p : r2) { - assertThat(p.getAge(), is(10)); - assertThat(p.getFirstName(), is("Bob")); - } - } + @Test + public void testUsingAnOrQuery() throws Exception { - @Test - public void testRemovingDocument() throws Exception { + template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); - PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); - p1.setFirstName("Sven_to_be_removed"); - p1.setAge(51); - template.insert(p1); + PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); + p1.setFirstName("Sven"); + p1.setAge(11); + template.insert(p1); + PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); + p2.setFirstName("Mary"); + p2.setAge(21); + template.insert(p2); + PersonWithIdPropertyOfTypeObjectId p3 = new PersonWithIdPropertyOfTypeObjectId(); + p3.setFirstName("Ann"); + p3.setAge(31); + template.insert(p3); + PersonWithIdPropertyOfTypeObjectId p4 = new PersonWithIdPropertyOfTypeObjectId(); + p4.setFirstName("John"); + p4.setAge(41); + template.insert(p4); - Query q1 = new Query(Criteria.where("id").is(p1.getId())); - PersonWithIdPropertyOfTypeObjectId found1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(found1, notNullValue()); - Query _q = new Query(Criteria.where("_id").is(p1.getId())); - template.remove(_q, PersonWithIdPropertyOfTypeObjectId.class); - PersonWithIdPropertyOfTypeObjectId notFound1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(notFound1, nullValue()); + Query q1 = new Query(Criteria.where("age").in(11, 21)); + Query q2 = new Query(Criteria.where("age").is(31)); + Query orQuery = new Query().or(q1, q2); + List results = template.find(orQuery, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(results.size(), is(3)); + for (PersonWithIdPropertyOfTypeObjectId p : results) { + assertThat(p.getAge(), isOneOf(11, 21, 31)); + } + } - PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); - p2.setFirstName("Bubba_to_be_removed"); - p2.setAge(51); - template.insert(p2); + @Test + public void testUsingUpdateWithMultipleSet() throws Exception { - Query q2 = new Query(Criteria.where("id").is(p2.getId())); - PersonWithIdPropertyOfTypeObjectId found2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(found2, notNullValue()); - template.remove(q2, PersonWithIdPropertyOfTypeObjectId.class); - PersonWithIdPropertyOfTypeObjectId notFound2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class); - assertThat(notFound2, nullValue()); - } + template.remove(new Query(), PersonWithIdPropertyOfTypeObjectId.class); - @Test - public void testAddingToListWithSimpleConverter() throws Exception { - testAddingToList(this.template); - } + PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); + p1.setFirstName("Sven"); + p1.setAge(11); + template.insert(p1); + PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); + p2.setFirstName("Mary"); + p2.setAge(21); + template.insert(p2); - @Test - public void testAddingToListWithMappingConverter() throws Exception { - testAddingToList(this.mappingTemplate); - } + Update u = new Update().set("firstName", "Bob").set("age", 10); - private void testAddingToList(MongoTemplate template) { - PersonWithAList p = new PersonWithAList(); - p.setFirstName("Sven"); - p.setAge(22); - template.insert(p); + WriteResult wr = template.updateMulti(PersonWithIdPropertyOfTypeObjectId.class, new Query(), u); - Query q1 = new Query(Criteria.where("id").is(p.getId())); - PersonWithAList p2 = template.findOne(q1, PersonWithAList.class); - assertThat(p2, notNullValue()); - assertThat(p2.getWishList().size(), is(0)); - - p2.addToWishList("please work!"); - - template.save(p2); + assertThat(wr.getN(), is(2)); - PersonWithAList p3 = template.findOne(q1, PersonWithAList.class); - assertThat(p3, notNullValue()); - assertThat(p3.getWishList().size(), is(1)); + Query q1 = new Query(Criteria.where("age").in(11, 21)); + List r1 = template.find(q1, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(r1.size(), is(0)); + Query q2 = new Query(Criteria.where("age").is(10)); + List r2 = template.find(q2, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(r2.size(), is(2)); + for (PersonWithIdPropertyOfTypeObjectId p : r2) { + assertThat(p.getAge(), is(10)); + assertThat(p.getFirstName(), is("Bob")); + } + } - Friend f = new Friend(); - p.setFirstName("Erik"); - p.setAge(21); - - p3.addFriend(f); - template.save(p3); + @Test + public void testRemovingDocument() throws Exception { + + PersonWithIdPropertyOfTypeObjectId p1 = new PersonWithIdPropertyOfTypeObjectId(); + p1.setFirstName("Sven_to_be_removed"); + p1.setAge(51); + template.insert(p1); + + Query q1 = new Query(Criteria.where("id").is(p1.getId())); + PersonWithIdPropertyOfTypeObjectId found1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(found1, notNullValue()); + Query _q = new Query(Criteria.where("_id").is(p1.getId())); + template.remove(_q, PersonWithIdPropertyOfTypeObjectId.class); + PersonWithIdPropertyOfTypeObjectId notFound1 = template.findOne(q1, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(notFound1, nullValue()); + + PersonWithIdPropertyOfTypeObjectId p2 = new PersonWithIdPropertyOfTypeObjectId(); + p2.setFirstName("Bubba_to_be_removed"); + p2.setAge(51); + template.insert(p2); + + Query q2 = new Query(Criteria.where("id").is(p2.getId())); + PersonWithIdPropertyOfTypeObjectId found2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(found2, notNullValue()); + template.remove(q2, PersonWithIdPropertyOfTypeObjectId.class); + PersonWithIdPropertyOfTypeObjectId notFound2 = template.findOne(q2, PersonWithIdPropertyOfTypeObjectId.class); + assertThat(notFound2, nullValue()); + } + + @Test + public void testAddingToListWithSimpleConverter() throws Exception { + testAddingToList(this.template); + } + + @Test + public void testAddingToListWithMappingConverter() throws Exception { + testAddingToList(this.mappingTemplate); + } + + private void testAddingToList(MongoTemplate template) { + PersonWithAList p = new PersonWithAList(); + p.setFirstName("Sven"); + p.setAge(22); + template.insert(p); + + Query q1 = new Query(Criteria.where("id").is(p.getId())); + PersonWithAList p2 = template.findOne(q1, PersonWithAList.class); + assertThat(p2, notNullValue()); + assertThat(p2.getWishList().size(), is(0)); + + p2.addToWishList("please work!"); + + template.save(p2); + + PersonWithAList p3 = template.findOne(q1, PersonWithAList.class); + assertThat(p3, notNullValue()); + assertThat(p3.getWishList().size(), is(1)); + + Friend f = new Friend(); + p.setFirstName("Erik"); + p.setAge(21); + + p3.addFriend(f); + template.save(p3); + + PersonWithAList p4 = template.findOne(q1, PersonWithAList.class); + assertThat(p4, notNullValue()); + assertThat(p4.getWishList().size(), is(1)); + assertThat(p4.getFriends().size(), is(1)); + + } - PersonWithAList p4 = template.findOne(q1, PersonWithAList.class); - assertThat(p4, notNullValue()); - assertThat(p4.getWishList().size(), is(1)); - assertThat(p4.getFriends().size(), is(1)); - - } - } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateUnitTests.java index 267efb4d8..3030cc133 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/MongoTemplateUnitTests.java @@ -32,77 +32,77 @@ import org.springframework.test.util.ReflectionTestUtils; /** * Unit tests for {@link MongoTemplate}. - * + * * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) public class MongoTemplateUnitTests extends MongoOperationsUnitTests { - MongoTemplate template; + MongoTemplate template; - @Mock - Mongo mongo; + @Mock + Mongo mongo; - @Mock - DB db; + @Mock + DB db; - @Before - public void setUp() { - this.template = new MongoTemplate(mongo, "database"); - } + @Before + public void setUp() { + this.template = new MongoTemplate(mongo, "database"); + } - @Test(expected = IllegalArgumentException.class) - public void rejectsNullDatabaseName() throws Exception { - new MongoTemplate(mongo, null); - } + @Test(expected = IllegalArgumentException.class) + public void rejectsNullDatabaseName() throws Exception { + new MongoTemplate(mongo, null); + } - @Test(expected = IllegalArgumentException.class) - public void rejectsNullMongo() throws Exception { - new MongoTemplate(null, "database"); - } + @Test(expected = IllegalArgumentException.class) + public void rejectsNullMongo() throws Exception { + new MongoTemplate(null, "database"); + } - @Test(expected = DataAccessException.class) - public void removeHandlesMongoExceptionProperly() throws Exception { - MongoTemplate template = mockOutGetDb(); - when(db.getCollection("collection")).thenThrow(new MongoException("Exception!")); + @Test(expected = DataAccessException.class) + public void removeHandlesMongoExceptionProperly() throws Exception { + MongoTemplate template = mockOutGetDb(); + when(db.getCollection("collection")).thenThrow(new MongoException("Exception!")); - template.remove("collection", null); - } + template.remove("collection", null); + } - @Test - public void defaultsConverterToSimpleMongoConverter() throws Exception { - MongoTemplate template = new MongoTemplate(mongo, "database"); - assertTrue(ReflectionTestUtils.getField(template, "mongoConverter") instanceof SimpleMongoConverter); - } + @Test + public void defaultsConverterToSimpleMongoConverter() throws Exception { + MongoTemplate template = new MongoTemplate(mongo, "database"); + assertTrue(ReflectionTestUtils.getField(template, "mongoConverter") instanceof SimpleMongoConverter); + } - /** - * Mocks out the {@link MongoTemplate#getDb()} method to return the {@link DB} mock instead of executing the actual - * behaviour. - * - * @return - */ - private MongoTemplate mockOutGetDb() { + /** + * Mocks out the {@link MongoTemplate#getDb()} method to return the {@link DB} mock instead of executing the actual + * behaviour. + * + * @return + */ + private MongoTemplate mockOutGetDb() { - MongoTemplate template = spy(this.template); - stub(template.getDb()).toReturn(db); - return template; - } + MongoTemplate template = spy(this.template); + stub(template.getDb()).toReturn(db); + return template; + } - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.MongoOperationsUnitTests#getOperations() - */ - @Override - protected MongoOperations getOperationsForExceptionHandling() { - MongoTemplate template = spy(this.template); - stub(template.getDb()).toThrow(new MongoException("Error!")); - return template; - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.MongoOperationsUnitTests#getOperations() + */ + @Override + protected MongoOperations getOperationsForExceptionHandling() { + MongoTemplate template = spy(this.template); + stub(template.getDb()).toThrow(new MongoException("Error!")); + return template; + } - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.MongoOperationsUnitTests#getOperations() - */ - @Override - protected MongoOperations getOperations() { - return this.template; - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.MongoOperationsUnitTests#getOperations() + */ + @Override + protected MongoOperations getOperations() { + return this.template; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Person.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Person.java index 5fccae20d..7825573b7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Person.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Person.java @@ -19,86 +19,85 @@ import org.bson.types.ObjectId; public class Person { - private final ObjectId id; + private final ObjectId id; - private String firstName; + private String firstName; - private int age; + private int age; - private Person friend; + private Person friend; - public Person() { - this.id = new ObjectId(); - } + public Person() { + this.id = new ObjectId(); + } - public Person(ObjectId id, String firstname) { - this.id = id; - this.firstName = firstname; - } + public Person(ObjectId id, String firstname) { + this.id = id; + this.firstName = firstname; + } - public Person(String firstname) { - this(); - this.firstName = firstname; - } + public Person(String firstname) { + this(); + this.firstName = firstname; + } - public ObjectId getId() { - return id; - } + public ObjectId getId() { + return id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public int getAge() { - return age; - } + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } + public void setAge(int age) { + this.age = age; + } - public Person getFriend() { - return friend; - } + public Person getFriend() { + return friend; + } - public void setFriend(Person friend) { - this.friend = friend; - } + public void setFriend(Person friend) { + this.friend = friend; + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - if (obj == this) { - return true; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } - if (obj == null) { - return false; - } + if (obj == null) { + return false; + } - if (!(getClass().equals(obj.getClass()))) { - return false; - } + if (!(getClass().equals(obj.getClass()))) { + return false; + } - Person that = (Person) obj; + Person that = (Person) obj; - return this.id == null ? false : this.id.equals(that.id); - } + return this.id == null ? false : this.id.equals(that.id); + } - - /* (non-Javadoc) - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - return id.hashCode(); - } + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return id.hashCode(); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java index 6a9413ebf..b728aeef6 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExample.java @@ -32,76 +32,72 @@ import static org.springframework.data.document.mongodb.query.Update.update; public class PersonExample { - private static final Log log = LogFactory.getLog(PersonExample.class); - @Autowired - private MongoOperations mongoOps; - - public static void main(String[] args) { - ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonExampleAppConfig.class); - PersonExample example = applicationContext.getBean(PersonExample.class); - example.doWork(); - } - - public void doWork() { - mongoOps.dropCollection("personexample"); - - PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString(); - p.setFirstName("Sven"); - p.setAge(22); - - mongoOps.save(p); - - - PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString(); - p2.setFirstName("Jon"); - p2.setAge(23); - - mongoOps.save(p2); - - - log.debug("Saved: " + p); - - p = mongoOps.findOne(query(whereId().is(p.getId())), PersonWithIdPropertyOfTypeString.class); - - log.debug("Found: " + p); - - // mongoOps.updateFirst(new Query(where("firstName").is("Sven")), new Update().set("age", 24)); - - // mongoOps.updateFirst(new Query(where("firstName").is("Sven")), update("age", 24)); - - - p = mongoOps.findOne(query(whereId().is(p.getId())), PersonWithIdPropertyOfTypeString.class); - log.debug("Updated: " + p); - - - List folks = mongoOps.getCollection(PersonWithIdPropertyOfTypeString.class); - log.debug("Querying for all people..."); - for (Iterator iterator = folks.iterator(); iterator.hasNext();) { - PersonWithIdPropertyOfTypeString personWithIdPropertyOfTypeString = (PersonWithIdPropertyOfTypeString) iterator - .next(); - log.debug(personWithIdPropertyOfTypeString); - } - - //mongoOps.remove( query(whereId().is(p.getId())), p.getClass()); - - mongoOps.remove(p); - - List people = mongoOps.getCollection(PersonWithIdPropertyOfTypeString.class); - - //PersonWithIdPropertyOfTypeString p2 = mongoOps.findOne(query(whereId().is(p.getId())), PersonWithIdPropertyOfTypeString.class); - - log.debug("Number of people = : " + people.size()); - - } - - public void doWork2() { - mongoOps.dropCollection("personexample"); - - PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString(); - p.setFirstName("Sven"); - p.setAge(22); - - } - - + private static final Log log = LogFactory.getLog(PersonExample.class); + @Autowired + private MongoOperations mongoOps; + + public static void main(String[] args) { + ApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonExampleAppConfig.class); + PersonExample example = applicationContext.getBean(PersonExample.class); + example.doWork(); + } + + public void doWork() { + mongoOps.dropCollection("personexample"); + + PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString(); + p.setFirstName("Sven"); + p.setAge(22); + + mongoOps.save(p); + + PersonWithIdPropertyOfTypeString p2 = new PersonWithIdPropertyOfTypeString(); + p2.setFirstName("Jon"); + p2.setAge(23); + + mongoOps.save(p2); + + log.debug("Saved: " + p); + + p = mongoOps.findOne(query(whereId().is(p.getId())), PersonWithIdPropertyOfTypeString.class); + + log.debug("Found: " + p); + + // mongoOps.updateFirst(new Query(where("firstName").is("Sven")), new Update().set("age", 24)); + + // mongoOps.updateFirst(new Query(where("firstName").is("Sven")), update("age", 24)); + + p = mongoOps.findOne(query(whereId().is(p.getId())), PersonWithIdPropertyOfTypeString.class); + log.debug("Updated: " + p); + + List folks = mongoOps.getCollection(PersonWithIdPropertyOfTypeString.class); + log.debug("Querying for all people..."); + for (Iterator iterator = folks.iterator(); iterator.hasNext();) { + PersonWithIdPropertyOfTypeString personWithIdPropertyOfTypeString = (PersonWithIdPropertyOfTypeString) iterator + .next(); + log.debug(personWithIdPropertyOfTypeString); + } + + // mongoOps.remove( query(whereId().is(p.getId())), p.getClass()); + + mongoOps.remove(p); + + List people = mongoOps.getCollection(PersonWithIdPropertyOfTypeString.class); + + // PersonWithIdPropertyOfTypeString p2 = mongoOps.findOne(query(whereId().is(p.getId())), + // PersonWithIdPropertyOfTypeString.class); + + log.debug("Number of people = : " + people.size()); + + } + + public void doWork2() { + mongoOps.dropCollection("personexample"); + + PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString(); + p.setFirstName("Sven"); + p.setAge(22); + + } + } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExampleAppConfig.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExampleAppConfig.java index e1ac6c94a..86c0c67aa 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExampleAppConfig.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonExampleAppConfig.java @@ -23,19 +23,18 @@ import com.mongodb.Mongo; @Configuration public class PersonExampleAppConfig { - @Bean - public Mongo mongo() throws Exception { - return new Mongo("localhost"); - } + @Bean + public Mongo mongo() throws Exception { + return new Mongo("localhost"); + } - @Bean - public MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), "database"); - } - - @Bean - public PersonExample personExample() - { - return new PersonExample(); - } + @Bean + public MongoTemplate mongoTemplate() throws Exception { + return new MongoTemplate(mongo(), "database"); + } + + @Bean + public PersonExample personExample() { + return new PersonExample(); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonReadConverter.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonReadConverter.java index 235fce457..746e9014a 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonReadConverter.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonReadConverter.java @@ -9,7 +9,7 @@ import com.mongodb.DBObject; public class PersonReadConverter implements Converter { public Person convert(DBObject source) { - Person p = new Person((ObjectId)source.get("_id"), (String)source.get("name")); + Person p = new Person((ObjectId) source.get("_id"), (String) source.get("name")); p.setAge((Integer) source.get("age")); return p; } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithAList.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithAList.java index bb6f8992d..95fd16a35 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithAList.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithAList.java @@ -80,8 +80,7 @@ public class PersonWithAList { @Override public String toString() { - return "PersonWithAList [id=" + id + ", firstName=" + firstName - + ", age=" + age + ", wishList=" + wishList + "]"; + return "PersonWithAList [id=" + id + ", firstName=" + firstName + ", age=" + age + ", wishList=" + wishList + "]"; } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeObjectId.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeObjectId.java index af89dc68e..e8f33564a 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeObjectId.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeObjectId.java @@ -19,34 +19,34 @@ import org.bson.types.ObjectId; public class PersonWithIdPropertyOfTypeObjectId { - private ObjectId id; + private ObjectId id; - private String firstName; + private String firstName; - private int age; + private int age; - public ObjectId getId() { - return id; - } + public ObjectId getId() { + return id; + } - public void setId(ObjectId id) { - this.id = id; - } + public void setId(ObjectId id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public int getAge() { - return age; - } + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } + public void setAge(int age) { + this.age = age; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeString.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeString.java index 952529514..833805824 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeString.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWithIdPropertyOfTypeString.java @@ -15,43 +15,41 @@ */ package org.springframework.data.document.mongodb; - public class PersonWithIdPropertyOfTypeString { - private String id; + private String id; - private String firstName; + private String firstName; - private int age; + private int age; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public int getAge() { - return age; - } + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } - - @Override - public String toString() { - return "PersonWithIdPropertyOfTypeString [id=" + id + ", firstName=" - + firstName + ", age=" + age + "]"; - } + public void setAge(int age) { + this.age = age; + } + + @Override + public String toString() { + return "PersonWithIdPropertyOfTypeString [id=" + id + ", firstName=" + firstName + ", age=" + age + "]"; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeObjectId.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeObjectId.java index 0e72f2e4b..bdadc211e 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeObjectId.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeObjectId.java @@ -19,34 +19,34 @@ import org.bson.types.ObjectId; public class PersonWith_idPropertyOfTypeObjectId { - private ObjectId _id; + private ObjectId _id; - private String firstName; + private String firstName; - private int age; + private int age; - public ObjectId get_id() { - return _id; - } + public ObjectId get_id() { + return _id; + } - public void set_id(ObjectId _id) { - this._id = _id; - } + public void set_id(ObjectId _id) { + this._id = _id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public int getAge() { - return age; - } + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } + public void setAge(int age) { + this.age = age; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeString.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeString.java index b1e2fa6dc..3846bea5c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeString.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/PersonWith_idPropertyOfTypeString.java @@ -15,37 +15,36 @@ */ package org.springframework.data.document.mongodb; - public class PersonWith_idPropertyOfTypeString { - private String _id; + private String _id; - private String firstName; + private String firstName; - private int age; + private int age; - public String get_id() { - return _id; - } + public String get_id() { + return _id; + } - public void set_id(String _id) { - this._id = _id; - } + public void set_id(String _id) { + this._id = _id; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public int getAge() { - return age; - } + public int getAge() { + return age; + } - public void setAge(int age) { - this.age = age; - } + public void setAge(int age) { + this.age = age; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Portfolio.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Portfolio.java index 4d8ec3e43..2d7cd5ad3 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Portfolio.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Portfolio.java @@ -21,53 +21,53 @@ import java.util.Map; public class Portfolio { - private String portfolioName; - private User user; - private List trades; - private Map positions; - private Map portfolioManagers; + private String portfolioName; + private User user; + private List trades; + private Map positions; + private Map portfolioManagers; - public Map getPortfolioManagers() { - return portfolioManagers; - } + public Map getPortfolioManagers() { + return portfolioManagers; + } - public void setPortfolioManagers(Map portfolioManagers) { - this.portfolioManagers = portfolioManagers; - } + public void setPortfolioManagers(Map portfolioManagers) { + this.portfolioManagers = portfolioManagers; + } - public Map getPositions() { - return positions; - } + public Map getPositions() { + return positions; + } - public void setPositions(Map positions) { - this.positions = positions; - } + public void setPositions(Map positions) { + this.positions = positions; + } - public Portfolio() { - trades = new ArrayList(); - } + public Portfolio() { + trades = new ArrayList(); + } - public String getPortfolioName() { - return portfolioName; - } + public String getPortfolioName() { + return portfolioName; + } - public void setPortfolioName(String portfolioName) { - this.portfolioName = portfolioName; - } + public void setPortfolioName(String portfolioName) { + this.portfolioName = portfolioName; + } - public List getTrades() { - return trades; - } + public List getTrades() { + return trades; + } - public void setTrades(List trades) { - this.trades = trades; - } + public void setTrades(List trades) { + this.trades = trades; + } - public User getUser() { - return user; - } + public User getUser() { + return user; + } - public void setUser(User user) { - this.user = user; - } + public void setUser(User user) { + this.user = user; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SimpleMongoConverterTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SimpleMongoConverterTests.java index 9039c7026..4b099d367 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SimpleMongoConverterTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SimpleMongoConverterTests.java @@ -44,390 +44,390 @@ import org.springframework.util.ReflectionUtils; public class SimpleMongoConverterTests { - static final String SIMPLE_JSON = "{ \"map\" : { \"foo\" : 3 , \"bar\" : 4}, \"number\" : 15 }"; - static final String COMPLEX_JSON = "{ \"map\" : { \"trade\" : { \"orderType\" : \"BUY\" , \"price\" : 90.5 , \"quantity\" : 0 , \"ticker\" : \"VMW\"}}}"; - - SimpleMongoConverter converter; - DBObject object; - - @Before - public void setUp() { - converter = new SimpleMongoConverter(); - converter.afterPropertiesSet(); - object = new BasicDBObject(); - } - - @Test - public void notNestedObject() { - User user = new User(); - user.setAccountName("My Account"); - user.setUserName("Mark"); - converter.write(user, object); - assertEquals("My Account", object.get("accountName")); - assertEquals("Mark", object.get("userName")); - - User u = converter.read(User.class, object); - - assertEquals("My Account", u.getAccountName()); - assertEquals("Mark", u.getUserName()); - } - - @Test - public void nestedObject() { - Portfolio p = createPortfolioWithNoTrades(); - converter.write(p, object); - - assertEquals("High Risk Trading Account", object.get("portfolioName")); - assertTrue(object.containsField("user")); - - Portfolio cp = converter.read(Portfolio.class, object); - - assertEquals("High Risk Trading Account", cp.getPortfolioName()); - assertEquals("Joe Trader", cp.getUser().getUserName()); - assertEquals("ACCT-123", cp.getUser().getAccountName()); - - } - - @Test - public void objectWithMap() { - Portfolio p = createPortfolioWithPositions(); - converter.write(p, object); - - Portfolio cp = converter.read(Portfolio.class, object); - assertEquals("High Risk Trading Account", cp.getPortfolioName()); - } - - @Test - public void objectWithMapContainingNonPrimitiveTypeAsValue() { - Portfolio p = createPortfolioWithManagers(); - converter.write(p, object); - - Portfolio cp = converter.read(Portfolio.class, object); - assertEquals("High Risk Trading Account", cp.getPortfolioName()); - } - - protected Portfolio createPortfolioWithPositions() { - - Portfolio portfolio = new Portfolio(); - portfolio.setPortfolioName("High Risk Trading Account"); - Map positions = new HashMap(); - positions.put("CSCO", 1); - portfolio.setPositions(positions); - return portfolio; - } - - protected Portfolio createPortfolioWithManagers() { - - Portfolio portfolio = new Portfolio(); - portfolio.setPortfolioName("High Risk Trading Account"); - Map managers = new HashMap(); - Person p1 = new Person(); - p1.setFirstName("Mark"); - managers.put("CSCO", p1); - portfolio.setPortfolioManagers(managers); - return portfolio; - } - - protected Portfolio createPortfolioWithNoTrades() { - Portfolio portfolio = new Portfolio(); - User user = new User(); - user.setUserName("Joe Trader"); - user.setAccountName("ACCT-123"); - portfolio.setUser(user); - portfolio.setPortfolioName("High Risk Trading Account"); - return portfolio; - } - - @Test - public void objectWithArrayContainingNonPrimitiveType() { - TradeBatch b = createTradeBatch(); - converter.write(b, object); - - TradeBatch b2 = converter.read(TradeBatch.class, object); - assertEquals(b.getBatchId(), b2.getBatchId()); - assertNotNull(b2.getTradeList()); - assertEquals(b.getTradeList().size(), b2.getTradeList().size()); - assertEquals(b.getTradeList().get(1).getTicker(), b2.getTradeList().get(1).getTicker()); - assertEquals(b.getTrades().length, b2.getTrades().length); - assertEquals(b.getTrades()[1].getTicker(), b2.getTrades()[1].getTicker()); - } - - private TradeBatch createTradeBatch() { - TradeBatch tb = new TradeBatch(); - tb.setBatchId("123456"); - Trade t1 = new Trade(); - t1.setOrderType("BUY"); - t1.setTicker("AAPL"); - t1.setQuantity(1000); - t1.setPrice(320.77D); - Trade t2 = new Trade(); - t2.setOrderType("SELL"); - t2.setTicker("MSFT"); - t2.setQuantity(100); - t2.setPrice(27.92D); - tb.setTrades(new Trade[]{t2, t1}); - tb.setTradeList(Arrays.asList(new Trade[]{t1, t2})); - return tb; - } - - @Test - public void objectWithEnumTypes() { - SomeEnumTest test = new SomeEnumTest(); - test.setId("123AAA"); - test.setName("Sven"); - test.setStringEnum(StringEnum.ONE); - test.setNumberEnum(NumberEnum.FIVE); - DBObject dbo = new BasicDBObject(); - converter.write(test, dbo); - - SomeEnumTest results = converter.read(SomeEnumTest.class, dbo); - assertNotNull(results); - assertEquals(test.getId(), results.getId()); - assertEquals(test.getName(), results.getName()); - assertEquals(test.getStringEnum(), results.getStringEnum()); - assertEquals(test.getNumberEnum(), results.getNumberEnum()); - } - - @Test - public void serializesClassWithFinalObjectIdCorrectly() throws Exception { - - BasicDBObject object = new BasicDBObject(); - Person person = new Person("Oliver"); - converter.write(person, object); - - assertThat(object.get("class"), is(nullValue())); - assertThat(object.get("_id"), is((Object) person.getId())); - } - - @Test - public void discoversGenericsForType() throws Exception { - - Field field = ReflectionUtils.findField(Sample.class, "map"); - assertListOfStringAndLong(converter.getGenericParameters(field.getGenericType())); - } - - @Test - public void writesSimpleMapCorrectly() throws Exception { - - Map map = new HashMap(); - map.put("foo", 1L); - map.put("bar", 2L); - - Sample sample = new Sample(); - sample.setMap(map); - sample.setNumber(15L); - - converter.write(sample, object); - - assertThat(object.get("number"), is((Object) 15L)); - - Object result = object.get("map"); - assertTrue(result instanceof Map); - - @SuppressWarnings("unchecked") - Map mapResult = (Map) result; - assertThat(mapResult.size(), is(2)); - assertThat(mapResult.get("foo"), is(1L)); - assertThat(mapResult.get("bar"), is(2L)); - } - - @Test - public void writesComplexMapCorrectly() throws Exception { - - Trade trade = new Trade(); - trade.setOrderType("BUY"); - trade.setTicker("VMW"); - trade.setPrice(90.50d); - - Map map = new HashMap(); - map.put("trade", trade); - - converter.write(new Sample2(map), object); - DBObject tradeDbObject = new BasicDBObject(); - converter.write(trade, tradeDbObject); - - Object result = object.get("map"); - assertTrue(result instanceof Map); - - @SuppressWarnings("unchecked") - Map mapResult = (Map) result; - assertThat(mapResult.size(), is(1)); - assertThat(mapResult.get("trade"), is(tradeDbObject)); - } - - @Test - public void readsMapWithSetterCorrectly() throws Exception { - - DBObject input = (DBObject) JSON.parse(SIMPLE_JSON); - Sample result = converter.read(Sample.class, input); - assertThat(result.getNumber(), is(15L)); - - Map map = result.getMap(); - assertThat(map, is(notNullValue())); - assertThat(map.size(), is(2)); - assertThat(map.get("foo"), is(3L)); - assertThat(map.get("bar"), is(4L)); - } - - @Test - public void readsMapWithFieldOnlyCorrectly() throws Exception { - - DBObject input = (DBObject) JSON.parse(COMPLEX_JSON); - Sample2 result = converter.read(Sample2.class, input); - - Map map = result.getMap(); - - Trade trade = new Trade(); - trade.setOrderType("BUY"); - trade.setTicker("VMW"); - trade.setPrice(90.50d); - - assertThat(map.size(), is(1)); - assertThat(map.get("trade").getTicker(), is("VMW")); - assertThat(map.get("trade").getOrderType(), is("BUY")); - assertThat(map.get("trade").getPrice(), is(90.50d)); - } - - @Test - public void supportsBigIntegerAsIdProperty() throws Exception { - - Sample3 sample3 = new Sample3(); - sample3.id = new BigInteger("4d24809660413b687f5d323e", 16); - converter.write(sample3, object); - assertThat(object.get("_id"), is(notNullValue())); - - Sample3 result = converter.read(Sample3.class, - (DBObject) JSON.parse("{\"_id\" : {\"$oid\" : \"4d24809660413b687f5d323e\" }}")); - assertThat(result.getId().toString(16), is("4d24809660413b687f5d323e")); - } - - @Test - public void convertsAddressCorrectly() { - - Address address = new Address(); - address.city = "New York"; - address.street = "Broadway"; - - DBObject dbObject = new BasicDBObject(); - - converter.write(address, dbObject); - - assertThat(dbObject.get("city").toString(), is("New York")); - assertThat(dbObject.get("street").toString(), is("Broadway")); - - Address result = converter.read(Address.class, dbObject); - assertThat(result.city, is("New York")); - assertThat(result.street, is("Broadway")); - } - - @Test - public void convertsJodaTimeTypesCorrectly() { - - Set> converters = new HashSet>(); - converters.add(new LocalDateToDateConverter()); - converters.add(new DateToLocalDateConverter()); - - converter.setConverters(converters); - - AnotherPerson person = new AnotherPerson(); - person.birthDate = new LocalDate(); - - DBObject dbObject = new BasicDBObject(); - converter.write(person, dbObject); - - assertTrue(dbObject.get("birthDate") instanceof Date); - - AnotherPerson result = converter.read(AnotherPerson.class, dbObject); - assertThat(result.getBirthDate(), is(notNullValue())); - } - - private void assertListOfStringAndLong(List> types) { - - assertThat(types.size(), CoreMatchers.is(2)); - assertEquals(String.class, types.get(0)); - assertEquals(Long.class, types.get(1)); - } - - public static class Sample { - - private Map map; - private Long number; - - public void setMap(Map map) { - this.map = map; - } - - public Map getMap() { - return map; - } - - public void setNumber(Long number) { - this.number = number; - } - - public Long getNumber() { - return number; - } - } - - public static class Sample2 { - - private final Map map; - - protected Sample2() { - this.map = null; - } - - public Sample2(Map map) { - this.map = map; - } - - public Map getMap() { - return map; - } - } - - private static class Sample3 { - - private BigInteger id; - - public BigInteger getId() { - return id; - } - } - - public static class Address { - String street; - String city; - - public String getStreet() { - return street; - } - - public String getCity() { - return city; - } - } - - public static class AnotherPerson { - LocalDate birthDate; - - public LocalDate getBirthDate() { - return birthDate; - } - } - - private class LocalDateToDateConverter implements Converter { - - public Date convert(LocalDate source) { - return source.toDateMidnight().toDate(); - } - } - - private class DateToLocalDateConverter implements Converter { - - public LocalDate convert(Date source) { - return new LocalDate(source.getTime()); - } - } + static final String SIMPLE_JSON = "{ \"map\" : { \"foo\" : 3 , \"bar\" : 4}, \"number\" : 15 }"; + static final String COMPLEX_JSON = "{ \"map\" : { \"trade\" : { \"orderType\" : \"BUY\" , \"price\" : 90.5 , \"quantity\" : 0 , \"ticker\" : \"VMW\"}}}"; + + SimpleMongoConverter converter; + DBObject object; + + @Before + public void setUp() { + converter = new SimpleMongoConverter(); + converter.afterPropertiesSet(); + object = new BasicDBObject(); + } + + @Test + public void notNestedObject() { + User user = new User(); + user.setAccountName("My Account"); + user.setUserName("Mark"); + converter.write(user, object); + assertEquals("My Account", object.get("accountName")); + assertEquals("Mark", object.get("userName")); + + User u = converter.read(User.class, object); + + assertEquals("My Account", u.getAccountName()); + assertEquals("Mark", u.getUserName()); + } + + @Test + public void nestedObject() { + Portfolio p = createPortfolioWithNoTrades(); + converter.write(p, object); + + assertEquals("High Risk Trading Account", object.get("portfolioName")); + assertTrue(object.containsField("user")); + + Portfolio cp = converter.read(Portfolio.class, object); + + assertEquals("High Risk Trading Account", cp.getPortfolioName()); + assertEquals("Joe Trader", cp.getUser().getUserName()); + assertEquals("ACCT-123", cp.getUser().getAccountName()); + + } + + @Test + public void objectWithMap() { + Portfolio p = createPortfolioWithPositions(); + converter.write(p, object); + + Portfolio cp = converter.read(Portfolio.class, object); + assertEquals("High Risk Trading Account", cp.getPortfolioName()); + } + + @Test + public void objectWithMapContainingNonPrimitiveTypeAsValue() { + Portfolio p = createPortfolioWithManagers(); + converter.write(p, object); + + Portfolio cp = converter.read(Portfolio.class, object); + assertEquals("High Risk Trading Account", cp.getPortfolioName()); + } + + protected Portfolio createPortfolioWithPositions() { + + Portfolio portfolio = new Portfolio(); + portfolio.setPortfolioName("High Risk Trading Account"); + Map positions = new HashMap(); + positions.put("CSCO", 1); + portfolio.setPositions(positions); + return portfolio; + } + + protected Portfolio createPortfolioWithManagers() { + + Portfolio portfolio = new Portfolio(); + portfolio.setPortfolioName("High Risk Trading Account"); + Map managers = new HashMap(); + Person p1 = new Person(); + p1.setFirstName("Mark"); + managers.put("CSCO", p1); + portfolio.setPortfolioManagers(managers); + return portfolio; + } + + protected Portfolio createPortfolioWithNoTrades() { + Portfolio portfolio = new Portfolio(); + User user = new User(); + user.setUserName("Joe Trader"); + user.setAccountName("ACCT-123"); + portfolio.setUser(user); + portfolio.setPortfolioName("High Risk Trading Account"); + return portfolio; + } + + @Test + public void objectWithArrayContainingNonPrimitiveType() { + TradeBatch b = createTradeBatch(); + converter.write(b, object); + + TradeBatch b2 = converter.read(TradeBatch.class, object); + assertEquals(b.getBatchId(), b2.getBatchId()); + assertNotNull(b2.getTradeList()); + assertEquals(b.getTradeList().size(), b2.getTradeList().size()); + assertEquals(b.getTradeList().get(1).getTicker(), b2.getTradeList().get(1).getTicker()); + assertEquals(b.getTrades().length, b2.getTrades().length); + assertEquals(b.getTrades()[1].getTicker(), b2.getTrades()[1].getTicker()); + } + + private TradeBatch createTradeBatch() { + TradeBatch tb = new TradeBatch(); + tb.setBatchId("123456"); + Trade t1 = new Trade(); + t1.setOrderType("BUY"); + t1.setTicker("AAPL"); + t1.setQuantity(1000); + t1.setPrice(320.77D); + Trade t2 = new Trade(); + t2.setOrderType("SELL"); + t2.setTicker("MSFT"); + t2.setQuantity(100); + t2.setPrice(27.92D); + tb.setTrades(new Trade[] { t2, t1 }); + tb.setTradeList(Arrays.asList(new Trade[] { t1, t2 })); + return tb; + } + + @Test + public void objectWithEnumTypes() { + SomeEnumTest test = new SomeEnumTest(); + test.setId("123AAA"); + test.setName("Sven"); + test.setStringEnum(StringEnum.ONE); + test.setNumberEnum(NumberEnum.FIVE); + DBObject dbo = new BasicDBObject(); + converter.write(test, dbo); + + SomeEnumTest results = converter.read(SomeEnumTest.class, dbo); + assertNotNull(results); + assertEquals(test.getId(), results.getId()); + assertEquals(test.getName(), results.getName()); + assertEquals(test.getStringEnum(), results.getStringEnum()); + assertEquals(test.getNumberEnum(), results.getNumberEnum()); + } + + @Test + public void serializesClassWithFinalObjectIdCorrectly() throws Exception { + + BasicDBObject object = new BasicDBObject(); + Person person = new Person("Oliver"); + converter.write(person, object); + + assertThat(object.get("class"), is(nullValue())); + assertThat(object.get("_id"), is((Object) person.getId())); + } + + @Test + public void discoversGenericsForType() throws Exception { + + Field field = ReflectionUtils.findField(Sample.class, "map"); + assertListOfStringAndLong(converter.getGenericParameters(field.getGenericType())); + } + + @Test + public void writesSimpleMapCorrectly() throws Exception { + + Map map = new HashMap(); + map.put("foo", 1L); + map.put("bar", 2L); + + Sample sample = new Sample(); + sample.setMap(map); + sample.setNumber(15L); + + converter.write(sample, object); + + assertThat(object.get("number"), is((Object) 15L)); + + Object result = object.get("map"); + assertTrue(result instanceof Map); + + @SuppressWarnings("unchecked") + Map mapResult = (Map) result; + assertThat(mapResult.size(), is(2)); + assertThat(mapResult.get("foo"), is(1L)); + assertThat(mapResult.get("bar"), is(2L)); + } + + @Test + public void writesComplexMapCorrectly() throws Exception { + + Trade trade = new Trade(); + trade.setOrderType("BUY"); + trade.setTicker("VMW"); + trade.setPrice(90.50d); + + Map map = new HashMap(); + map.put("trade", trade); + + converter.write(new Sample2(map), object); + DBObject tradeDbObject = new BasicDBObject(); + converter.write(trade, tradeDbObject); + + Object result = object.get("map"); + assertTrue(result instanceof Map); + + @SuppressWarnings("unchecked") + Map mapResult = (Map) result; + assertThat(mapResult.size(), is(1)); + assertThat(mapResult.get("trade"), is(tradeDbObject)); + } + + @Test + public void readsMapWithSetterCorrectly() throws Exception { + + DBObject input = (DBObject) JSON.parse(SIMPLE_JSON); + Sample result = converter.read(Sample.class, input); + assertThat(result.getNumber(), is(15L)); + + Map map = result.getMap(); + assertThat(map, is(notNullValue())); + assertThat(map.size(), is(2)); + assertThat(map.get("foo"), is(3L)); + assertThat(map.get("bar"), is(4L)); + } + + @Test + public void readsMapWithFieldOnlyCorrectly() throws Exception { + + DBObject input = (DBObject) JSON.parse(COMPLEX_JSON); + Sample2 result = converter.read(Sample2.class, input); + + Map map = result.getMap(); + + Trade trade = new Trade(); + trade.setOrderType("BUY"); + trade.setTicker("VMW"); + trade.setPrice(90.50d); + + assertThat(map.size(), is(1)); + assertThat(map.get("trade").getTicker(), is("VMW")); + assertThat(map.get("trade").getOrderType(), is("BUY")); + assertThat(map.get("trade").getPrice(), is(90.50d)); + } + + @Test + public void supportsBigIntegerAsIdProperty() throws Exception { + + Sample3 sample3 = new Sample3(); + sample3.id = new BigInteger("4d24809660413b687f5d323e", 16); + converter.write(sample3, object); + assertThat(object.get("_id"), is(notNullValue())); + + Sample3 result = converter.read(Sample3.class, + (DBObject) JSON.parse("{\"_id\" : {\"$oid\" : \"4d24809660413b687f5d323e\" }}")); + assertThat(result.getId().toString(16), is("4d24809660413b687f5d323e")); + } + + @Test + public void convertsAddressCorrectly() { + + Address address = new Address(); + address.city = "New York"; + address.street = "Broadway"; + + DBObject dbObject = new BasicDBObject(); + + converter.write(address, dbObject); + + assertThat(dbObject.get("city").toString(), is("New York")); + assertThat(dbObject.get("street").toString(), is("Broadway")); + + Address result = converter.read(Address.class, dbObject); + assertThat(result.city, is("New York")); + assertThat(result.street, is("Broadway")); + } + + @Test + public void convertsJodaTimeTypesCorrectly() { + + Set> converters = new HashSet>(); + converters.add(new LocalDateToDateConverter()); + converters.add(new DateToLocalDateConverter()); + + converter.setConverters(converters); + + AnotherPerson person = new AnotherPerson(); + person.birthDate = new LocalDate(); + + DBObject dbObject = new BasicDBObject(); + converter.write(person, dbObject); + + assertTrue(dbObject.get("birthDate") instanceof Date); + + AnotherPerson result = converter.read(AnotherPerson.class, dbObject); + assertThat(result.getBirthDate(), is(notNullValue())); + } + + private void assertListOfStringAndLong(List> types) { + + assertThat(types.size(), CoreMatchers.is(2)); + assertEquals(String.class, types.get(0)); + assertEquals(Long.class, types.get(1)); + } + + public static class Sample { + + private Map map; + private Long number; + + public void setMap(Map map) { + this.map = map; + } + + public Map getMap() { + return map; + } + + public void setNumber(Long number) { + this.number = number; + } + + public Long getNumber() { + return number; + } + } + + public static class Sample2 { + + private final Map map; + + protected Sample2() { + this.map = null; + } + + public Sample2(Map map) { + this.map = map; + } + + public Map getMap() { + return map; + } + } + + private static class Sample3 { + + private BigInteger id; + + public BigInteger getId() { + return id; + } + } + + public static class Address { + String street; + String city; + + public String getStreet() { + return street; + } + + public String getCity() { + return city; + } + } + + public static class AnotherPerson { + LocalDate birthDate; + + public LocalDate getBirthDate() { + return birthDate; + } + } + + private class LocalDateToDateConverter implements Converter { + + public Date convert(LocalDate source) { + return source.toDateMidnight().toDate(); + } + } + + private class DateToLocalDateConverter implements Converter { + + public LocalDate convert(Date source) { + return new LocalDate(source.getTime()); + } + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SomeEnumTest.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SomeEnumTest.java index 3a9e0a8c5..2f377ec21 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SomeEnumTest.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/SomeEnumTest.java @@ -2,63 +2,63 @@ package org.springframework.data.document.mongodb; public class SomeEnumTest { - public enum StringEnum { - ONE, TWO, FIVE; - } + public enum StringEnum { + ONE, TWO, FIVE; + } - public enum NumberEnum { - ONE(1), TWO(2), FIVE(5); + public enum NumberEnum { + ONE(1), TWO(2), FIVE(5); - private int value; + private int value; - public int value() { - return value; - } + public int value() { + return value; + } - NumberEnum(int value) { - this.value = value; - } + NumberEnum(int value) { + this.value = value; + } - } + } - private StringEnum stringEnum; + private StringEnum stringEnum; - private NumberEnum numberEnum; + private NumberEnum numberEnum; - private String id; + private String id; - private String name; + private String name; - public StringEnum getStringEnum() { - return stringEnum; - } + public StringEnum getStringEnum() { + return stringEnum; + } - public void setStringEnum(StringEnum stringEnum) { - this.stringEnum = stringEnum; - } + public void setStringEnum(StringEnum stringEnum) { + this.stringEnum = stringEnum; + } - public NumberEnum getNumberEnum() { - return numberEnum; - } + public NumberEnum getNumberEnum() { + return numberEnum; + } - public void setNumberEnum(NumberEnum numberEnum) { - this.numberEnum = numberEnum; - } + public void setNumberEnum(NumberEnum numberEnum) { + this.numberEnum = numberEnum; + } - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Trade.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Trade.java index e8ef3a79a..d3f3be876 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Trade.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Trade.java @@ -17,45 +17,44 @@ package org.springframework.data.document.mongodb; public class Trade { - private String ticker; + private String ticker; - private long quantity; + private long quantity; - private double price; + private double price; - private String orderType; + private String orderType; - public String getOrderType() { - return orderType; - } + public String getOrderType() { + return orderType; + } - public void setOrderType(String orderType) { - this.orderType = orderType; - } + public void setOrderType(String orderType) { + this.orderType = orderType; + } - public double getPrice() { - return price; - } + public double getPrice() { + return price; + } - public void setPrice(double price) { - this.price = price; - } + public void setPrice(double price) { + this.price = price; + } - public long getQuantity() { - return quantity; - } + public long getQuantity() { + return quantity; + } - public void setQuantity(long quantity) { - this.quantity = quantity; - } + public void setQuantity(long quantity) { + this.quantity = quantity; + } - public String getTicker() { - return ticker; - } - - public void setTicker(String ticker) { - this.ticker = ticker; - } + public String getTicker() { + return ticker; + } + public void setTicker(String ticker) { + this.ticker = ticker; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/TradeBatch.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/TradeBatch.java index 2cb443bab..acda9411c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/TradeBatch.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/TradeBatch.java @@ -4,35 +4,34 @@ import java.util.List; public class TradeBatch { - private String batchId; + private String batchId; - private Trade[] trades; + private Trade[] trades; - private List tradeList; + private List tradeList; + public String getBatchId() { + return batchId; + } - public String getBatchId() { - return batchId; - } + public void setBatchId(String batchId) { + this.batchId = batchId; + } - public void setBatchId(String batchId) { - this.batchId = batchId; - } + public Trade[] getTrades() { + return trades; + } - public Trade[] getTrades() { - return trades; - } + public void setTrades(Trade[] trades) { + this.trades = trades; + } - public void setTrades(Trade[] trades) { - this.trades = trades; - } + public List getTradeList() { + return tradeList; + } - public List getTradeList() { - return tradeList; - } - - public void setTradeList(List tradeList) { - this.tradeList = tradeList; - } + public void setTradeList(List tradeList) { + this.tradeList = tradeList; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/User.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/User.java index 23d5b1c74..f9d0ecbc7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/User.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/User.java @@ -17,58 +17,55 @@ package org.springframework.data.document.mongodb; public class User { - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result - + ((accountName == null) ? 0 : accountName.hashCode()); - result = prime * result - + ((userName == null) ? 0 : userName.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((accountName == null) ? 0 : accountName.hashCode()); + result = prime * result + ((userName == null) ? 0 : userName.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - User other = (User) obj; - if (accountName == null) { - if (other.accountName != null) - return false; - } else if (!accountName.equals(other.accountName)) - return false; - if (userName == null) { - if (other.userName != null) - return false; - } else if (!userName.equals(other.userName)) - return false; - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + User other = (User) obj; + if (accountName == null) { + if (other.accountName != null) + return false; + } else if (!accountName.equals(other.accountName)) + return false; + if (userName == null) { + if (other.userName != null) + return false; + } else if (!userName.equals(other.userName)) + return false; + return true; + } - private String accountName; + private String accountName; - private String userName; + private String userName; - public String getAccountName() { - return accountName; - } + public String getAccountName() { + return accountName; + } - public void setAccountName(String accountName) { - this.accountName = accountName; - } + public void setAccountName(String accountName) { + this.accountName = accountName; + } - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } + public String getUserName() { + return userName; + } + public void setUserName(String userName) { + this.userName = userName; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Venue.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Venue.java index 02320beec..8cda2487a 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Venue.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/Venue.java @@ -21,38 +21,37 @@ import org.springframework.data.annotation.Id; import org.springframework.data.annotation.PersistenceConstructor; import org.springframework.data.document.mongodb.mapping.Document; -@Document(collection="newyork") +@Document(collection = "newyork") public class Venue { - - @Id - private String id; - private String name; - private double[] location; - - @PersistenceConstructor - Venue(String name, double[] location) { - super(); - this.name = name; - this.location = location; - } - - public Venue(String name, double x, double y) { - super(); - this.name = name; - this.location = new double[] { x, y }; - } - public String getName() { - return name; - } + @Id + private String id; + private String name; + private double[] location; - public double[] getLocation() { - return location; - } + @PersistenceConstructor + Venue(String name, double[] location) { + super(); + this.name = name; + this.location = location; + } - @Override - public String toString() { - return "Venue [id=" + id + ", name=" + name + ", location=" - + Arrays.toString(location) + "]"; - } + public Venue(String name, double x, double y) { + super(); + this.name = name; + this.location = new double[] { x, y }; + } + + public String getName() { + return name; + } + + public double[] getLocation() { + return location; + } + + @Override + public String toString() { + return "Venue [id=" + id + ", name=" + name + ", location=" + Arrays.toString(location) + "]"; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/analytics/MvcAnalyticsTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/analytics/MvcAnalyticsTests.java index 04ffead93..665fcbf3e 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/analytics/MvcAnalyticsTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/analytics/MvcAnalyticsTests.java @@ -25,7 +25,6 @@ import org.springframework.data.document.mongodb.mapping.MongoPersistentProperty import org.springframework.data.document.mongodb.query.BasicQuery; import org.springframework.data.mapping.model.MappingContext; - public class MvcAnalyticsTests { private MongoTemplate mongoTemplate; @@ -35,30 +34,27 @@ public class MvcAnalyticsTests { public void setUp() throws Exception { Mongo m = new Mongo(); mongoTemplate = new MongoTemplate(m, "mvc"); - mongoDummyTemplate = new MongoTemplate( - m, - "mvc", - new AbstractMongoConverter() { - public void write(Object t, DBObject dbo) { - } + mongoDummyTemplate = new MongoTemplate(m, "mvc", new AbstractMongoConverter() { + public void write(Object t, DBObject dbo) { + } - public S read(Class clazz, DBObject dbo) { - return null; - } + public S read(Class clazz, DBObject dbo) { + return null; + } - public T convertObjectId(ObjectId id, Class targetType) { - return null; - } + public T convertObjectId(ObjectId id, Class targetType) { + return null; + } - public ObjectId convertObjectId(Object id) { - return null; - } + public ObjectId convertObjectId(Object id) { + return null; + } - public MappingContext, MongoPersistentProperty> getMappingContext() { - return null; - } + public MappingContext, MongoPersistentProperty> getMappingContext() { + return null; + } - }); + }); } @Test @@ -80,8 +76,7 @@ public class MvcAnalyticsTests { createAndStoreMvcEvent(3, 3); createAndStoreMvcEvent(8, 4); - List mvcEvents = mongoTemplate.getCollection("mvc", - MvcEvent.class); + List mvcEvents = mongoTemplate.getCollection("mvc", MvcEvent.class); Assert.assertEquals(22, mvcEvents.size()); mongoDummyTemplate.getCollection("mvc", MvcEvent.class); @@ -101,7 +96,6 @@ public class MvcAnalyticsTests { storeCounterData("SignUpController", "show"); } - } @Test @@ -110,7 +104,8 @@ public class MvcAnalyticsTests { for (DBObject dbo : mongoTemplate.getCollection("counters").find(query)) { System.out.println(dbo); } - List counters = mongoTemplate.find("counters", new BasicQuery("{ 'name' : 'SignUpController'} "), ControllerCounter.class); + List counters = mongoTemplate.find("counters", + new BasicQuery("{ 'name' : 'SignUpController'} "), ControllerCounter.class); for (ControllerCounter controllerCounter : counters) { System.out.println(controllerCounter); } @@ -126,8 +121,7 @@ public class MvcAnalyticsTests { @Test public void listAllMvcEvents() { - List mvcEvents = mongoTemplate.getCollection("mvc", - MvcEvent.class); + List mvcEvents = mongoTemplate.getCollection("mvc", MvcEvent.class); for (MvcEvent mvcEvent : mvcEvents) { System.out.println(mvcEvent.getDate()); } @@ -136,8 +130,7 @@ public class MvcAnalyticsTests { @Test public void groupQuery() { // This circumvents exception translation - DBCollection collection = mongoTemplate.getDb().getCollection( - "mvc"); + DBCollection collection = mongoTemplate.getDb().getCollection("mvc"); // QueryBuilder qb = new QueryBuilder(); // qb.start("date").greaterThan(object) @@ -157,10 +150,8 @@ public class MvcAnalyticsTests { * ).is("addFavoriteRestaurant").build(); DBObject cond2 = * q.getQueryObject(); */ - DBObject cond = QueryBuilder.start("date") - .greaterThanEquals(startDate.getTime()) - .lessThan(endDate.getTime()).and("action") - .is("addFavoriteRestaurant").get(); + DBObject cond = QueryBuilder.start("date").greaterThanEquals(startDate.getTime()).lessThan(endDate.getTime()) + .and("action").is("addFavoriteRestaurant").get(); DBObject key = new BasicDBObject("parameters.p1", true); /* * DBObject dateQ = new BasicDBObject(); dateQ.put("$gte", @@ -170,8 +161,7 @@ public class MvcAnalyticsTests { */ DBObject intitial = new BasicDBObject("count", 0); - DBObject result = collection.group(key, cond, intitial, - "function(doc, out){ out.count++; }"); + DBObject result = collection.group(key, cond, intitial, "function(doc, out){ out.count++; }"); if (result instanceof BasicDBList) { BasicDBList dbList = (BasicDBList) result; for (Object element : dbList) { @@ -191,15 +181,16 @@ public class MvcAnalyticsTests { changes.put("$set", new BasicDBObject("name", "controller1")); changes.put("$inc", new BasicDBObject("count", 1)); - //mongoTemplate.upsertAndModify(dbo("key","value"), inc("count",1)); - //dbo(set("name","controller"), inc("count", 1)); + // mongoTemplate.upsertAndModify(dbo("key","value"), inc("count",1)); + // dbo(set("name","controller"), inc("count", 1)); - ///mongoTemplate.update(collection("counters") + // /mongoTemplate.update(collection("counters") WriteResult r = mongoTemplate.getCollection("counters").update(query, changes, true, false); - //{ "err" : "Modifiers and non-modifiers cannot be mixed" , "code" : 10154 , "n" : 0 , "ok" : 1.0} - //{ "err" : null , "updatedExisting" : false , "upserted" : { "$oid" : "4cba814a5a4900000000495d"} , "n" : 1 , "ok" : 1.0} - //{ "err" : null , "updatedExisting" : true , "n" : 1 , "ok" : 1.0} + // { "err" : "Modifiers and non-modifiers cannot be mixed" , "code" : 10154 , "n" : 0 , "ok" : 1.0} + // { "err" : null , "updatedExisting" : false , "upserted" : { "$oid" : "4cba814a5a4900000000495d"} , "n" : 1 , "ok" + // : 1.0} + // { "err" : null , "updatedExisting" : true , "n" : 1 , "ok" : 1.0} System.out.println(r); // changes = new BasicDBObject("methods", new BasicDBObject("find", 1)); @@ -214,7 +205,6 @@ public class MvcAnalyticsTests { mongoTemplate.getDb().getCollection("counters").update(query, changes, true, false); } - public void storeCounterData(String controllerName, String methodName) { BasicDBObject query = new BasicDBObject("name", controllerName); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/config/MongoNamespaceTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/config/MongoNamespaceTests.java index aa642b41b..f852d0c8f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/config/MongoNamespaceTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/config/MongoNamespaceTests.java @@ -32,45 +32,43 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration public class MongoNamespaceTests { - @Autowired - private ApplicationContext ctx; + @Autowired + private ApplicationContext ctx; + public void testMongoSingleton() throws Exception { + assertTrue(ctx.containsBean("mongo")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongo"); + assertNull(readField("host", mfb)); + assertNull(readField("port", mfb)); + } - public void testMongoSingleton() throws Exception { - assertTrue(ctx.containsBean("mongo")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongo"); - assertNull(readField("host", mfb)); - assertNull(readField("port", mfb)); - } + @Test + public void testMongoSingletonWithAttributes() throws Exception { + assertTrue(ctx.containsBean("defaultMongo")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&defaultMongo"); + String host = readField("host", mfb); + Integer port = readField("port", mfb); + assertEquals("localhost", host); + assertEquals(new Integer(27017), port); + } - @Test - public void testMongoSingletonWithAttributes() throws Exception { - assertTrue(ctx.containsBean("defaultMongo")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&defaultMongo"); - String host = readField("host", mfb); - Integer port = readField("port", mfb); - assertEquals("localhost", host); - assertEquals(new Integer(27017), port); - } + @SuppressWarnings({ "unchecked" }) + public static T readField(String name, Object target) throws Exception { + Field field = null; + Class clazz = target.getClass(); + do { + try { + field = clazz.getDeclaredField(name); + } catch (Exception ex) { + } + clazz = clazz.getSuperclass(); + } while (field == null && !clazz.equals(Object.class)); - @SuppressWarnings({"unchecked"}) - public static T readField(String name, Object target) throws Exception { - Field field = null; - Class clazz = target.getClass(); - do { - try { - field = clazz.getDeclaredField(name); - } catch (Exception ex) { - } - - clazz = clazz.getSuperclass(); - } while (field == null && !clazz.equals(Object.class)); - - if (field == null) - throw new IllegalArgumentException("Cannot find field '" + name + "' in the class hierarchy of " - + target.getClass()); - field.setAccessible(true); - return (T) field.get(target); - } + if (field == null) + throw new IllegalArgumentException("Cannot find field '" + name + "' in the class hierarchy of " + + target.getClass()); + field.setAccessible(true); + return (T) field.get(target); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/convert/CustomConvertersUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/convert/CustomConvertersUnitTests.java index 2f6b2383d..f0d971aaa 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/convert/CustomConvertersUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/convert/CustomConvertersUnitTests.java @@ -45,91 +45,91 @@ import com.mongodb.DBObject; @RunWith(MockitoJUnitRunner.class) public class CustomConvertersUnitTests { - MappingMongoConverter converter; - - @Mock - BarToDBObjectConverter barToDBObjectConverter; - @Mock - DBObjectToBarConverter dbObjectToBarConverter; - - MongoMappingContext context; - MongoPersistentEntity fooEntity; - MongoPersistentEntity barEntity; + MappingMongoConverter converter; - @Before - @SuppressWarnings("unchecked") - public void setUp() throws Exception { - - context = new MongoMappingContext(); - context.setInitialEntitySet(new HashSet>(Arrays.asList(Foo.class, Bar.class))); - context.afterPropertiesSet(); - - when(barToDBObjectConverter.convert(any(Bar.class))).thenReturn(new BasicDBObject()); - when(dbObjectToBarConverter.convert(any(DBObject.class))).thenReturn(new Bar()); - - converter = new MappingMongoConverter(context); - converter.setConverters(Arrays.asList(barToDBObjectConverter, dbObjectToBarConverter)); - } + @Mock + BarToDBObjectConverter barToDBObjectConverter; + @Mock + DBObjectToBarConverter dbObjectToBarConverter; - @Test - public void nestedToDBObjectConverterGetsInvoked() { - - Foo foo = new Foo(); - foo.bar = new Bar(); - - converter.write(foo, new BasicDBObject()); - verify(barToDBObjectConverter).convert(any(Bar.class)); - } - - @Test - public void nestedFromDBObjectConverterGetsInvoked() { - - BasicDBObject dbObject = new BasicDBObject(); - dbObject.put("bar", new BasicDBObject()); - - converter.read(Foo.class, dbObject); - verify(dbObjectToBarConverter).convert(any(DBObject.class)); - } - - @Test - public void toDBObjectConverterGetsInvoked() { - - converter.write(new Bar(), new BasicDBObject()); - verify(barToDBObjectConverter).convert(any(Bar.class)); - } - - @Test - public void fromDBObjectConverterGetsInvoked() { - - converter.read(Bar.class, new BasicDBObject()); - verify(dbObjectToBarConverter).convert(any(DBObject.class)); - } - - @Test - public void foo() { - DBObject dbObject = new BasicDBObject(); - dbObject.put("foo", null); - - Assert.assertThat(dbObject.containsField("foo"), CoreMatchers.is(true)); - } + MongoMappingContext context; + MongoPersistentEntity fooEntity; + MongoPersistentEntity barEntity; - public static class Foo { - @Id - public String id; - public Bar bar; - } - - public static class Bar { - @Id - public String id; - public String foo; - } - - private interface BarToDBObjectConverter extends Converter { + @Before + @SuppressWarnings("unchecked") + public void setUp() throws Exception { - } + context = new MongoMappingContext(); + context.setInitialEntitySet(new HashSet>(Arrays.asList(Foo.class, Bar.class))); + context.afterPropertiesSet(); - private interface DBObjectToBarConverter extends Converter { + when(barToDBObjectConverter.convert(any(Bar.class))).thenReturn(new BasicDBObject()); + when(dbObjectToBarConverter.convert(any(DBObject.class))).thenReturn(new Bar()); - } + converter = new MappingMongoConverter(context); + converter.setConverters(Arrays.asList(barToDBObjectConverter, dbObjectToBarConverter)); + } + + @Test + public void nestedToDBObjectConverterGetsInvoked() { + + Foo foo = new Foo(); + foo.bar = new Bar(); + + converter.write(foo, new BasicDBObject()); + verify(barToDBObjectConverter).convert(any(Bar.class)); + } + + @Test + public void nestedFromDBObjectConverterGetsInvoked() { + + BasicDBObject dbObject = new BasicDBObject(); + dbObject.put("bar", new BasicDBObject()); + + converter.read(Foo.class, dbObject); + verify(dbObjectToBarConverter).convert(any(DBObject.class)); + } + + @Test + public void toDBObjectConverterGetsInvoked() { + + converter.write(new Bar(), new BasicDBObject()); + verify(barToDBObjectConverter).convert(any(Bar.class)); + } + + @Test + public void fromDBObjectConverterGetsInvoked() { + + converter.read(Bar.class, new BasicDBObject()); + verify(dbObjectToBarConverter).convert(any(DBObject.class)); + } + + @Test + public void foo() { + DBObject dbObject = new BasicDBObject(); + dbObject.put("foo", null); + + Assert.assertThat(dbObject.containsField("foo"), CoreMatchers.is(true)); + } + + public static class Foo { + @Id + public String id; + public Bar bar; + } + + public static class Bar { + @Id + public String id; + public String foo; + } + + private interface BarToDBObjectConverter extends Converter { + + } + + private interface DBObjectToBarConverter extends Converter { + + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Account.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Account.java index 5b2747152..6f367ed82 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Account.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Account.java @@ -16,7 +16,6 @@ package org.springframework.data.document.mongodb.mapping; - import org.springframework.data.annotation.Id; /** @@ -25,23 +24,23 @@ import org.springframework.data.annotation.Id; @Document public class Account { - @Id - private String id; - private Float balance; + @Id + private String id; + private Float balance; - public String getId() { - return id; - } + public String getId() { + return id; + } - public void setId(String id) { - this.id = id; - } + public void setId(String id) { + this.id = id; + } - public Float getBalance() { - return balance; - } + public Float getBalance() { + return balance; + } - public void setBalance(Float balance) { - this.balance = balance; - } + public void setBalance(Float balance) { + this.balance = balance; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/AccountPojo.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/AccountPojo.java index 71b83875f..d00be8d9b 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/AccountPojo.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/AccountPojo.java @@ -21,27 +21,27 @@ package org.springframework.data.document.mongodb.mapping; */ public class AccountPojo { - private String type; - private Float balance; + private String type; + private Float balance; - public AccountPojo(String type, Float balance) { - this.type = type; - this.balance = balance; - } + public AccountPojo(String type, Float balance) { + this.type = type; + this.balance = balance; + } - public String getType() { - return type; - } + public String getType() { + return type; + } - public void setType(String type) { - this.type = type; - } + public void setType(String type) { + this.type = type; + } - public Float getBalance() { - return balance; - } + public Float getBalance() { + return balance; + } - public void setBalance(Float balance) { - this.balance = balance; - } + public void setBalance(Float balance) { + this.balance = balance; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Address.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Address.java index 4c95b30e6..644c82b0b 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Address.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Address.java @@ -21,52 +21,52 @@ package org.springframework.data.document.mongodb.mapping; */ public class Address implements Comparable
                  { - private String id; - private String[] lines; - private String city; - private String provinceOrState; - private Integer postalCode; - private String country; + private String id; + private String[] lines; + private String city; + private String provinceOrState; + private Integer postalCode; + private String country; - public String[] getLines() { - return lines; - } + public String[] getLines() { + return lines; + } - public void setLines(String[] lines) { - this.lines = lines; - } + public void setLines(String[] lines) { + this.lines = lines; + } - public String getCity() { - return city; - } + public String getCity() { + return city; + } - public void setCity(String city) { - this.city = city; - } + public void setCity(String city) { + this.city = city; + } - public String getProvinceOrState() { - return provinceOrState; - } + public String getProvinceOrState() { + return provinceOrState; + } - public void setProvinceOrState(String provinceOrState) { - this.provinceOrState = provinceOrState; - } + public void setProvinceOrState(String provinceOrState) { + this.provinceOrState = provinceOrState; + } - public Integer getPostalCode() { - return postalCode; - } + public Integer getPostalCode() { + return postalCode; + } - public void setPostalCode(Integer postalCode) { - this.postalCode = postalCode; - } + public void setPostalCode(Integer postalCode) { + this.postalCode = postalCode; + } - public String getCountry() { - return country; - } + public String getCountry() { + return country; + } - public void setCountry(String country) { - this.country = country; - } + public void setCountry(String country) { + this.country = country; + } public int compareTo(Address address) { return 0; diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/BasePerson.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/BasePerson.java index 285790a39..f8cb2b529 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/BasePerson.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/BasePerson.java @@ -28,40 +28,40 @@ import com.mysema.query.annotations.QuerySupertype; @QuerySupertype public abstract class BasePerson { - protected Integer ssn; - protected String firstName; - protected String lastName; + protected Integer ssn; + protected String firstName; + protected String lastName; - public BasePerson() { - } + public BasePerson() { + } - public BasePerson(Integer ssn, String firstName, String lastName) { - this.ssn = ssn; - this.firstName = firstName; - this.lastName = lastName; - } + public BasePerson(Integer ssn, String firstName, String lastName) { + this.ssn = ssn; + this.firstName = firstName; + this.lastName = lastName; + } - public Integer getSsn() { - return ssn; - } + public Integer getSsn() { + return ssn; + } - public void setSsn(Integer ssn) { - this.ssn = ssn; - } + public void setSsn(Integer ssn) { + this.ssn = ssn; + } - public String getFirstName() { - return firstName; - } + public String getFirstName() { + return firstName; + } - public void setFirstName(String firstName) { - this.firstName = firstName; - } + public void setFirstName(String firstName) { + this.firstName = firstName; + } - public String getLastName() { - return lastName; - } + public String getLastName() { + return lastName; + } - public void setLastName(String lastName) { - this.lastName = lastName; - } + public void setLastName(String lastName) { + this.lastName = lastName; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GenericMappingTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GenericMappingTests.java index a8de7ed4c..377ddd99c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GenericMappingTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GenericMappingTests.java @@ -31,63 +31,63 @@ import org.springframework.data.document.mongodb.convert.MongoConverter; /** * Unit tests for testing the mapping works with generic types. - * + * * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) public class GenericMappingTests { - MongoMappingContext context; - MongoConverter converter; + MongoMappingContext context; + MongoConverter converter; - @Before - public void setUp() throws Exception { - context = new MongoMappingContext(); - context.setInitialEntitySet(Collections.singleton(StringWrapper.class)); - context.afterPropertiesSet(); - - converter = new MappingMongoConverter(context); - } + @Before + public void setUp() throws Exception { + context = new MongoMappingContext(); + context.setInitialEntitySet(Collections.singleton(StringWrapper.class)); + context.afterPropertiesSet(); - @Test - public void writesGenericTypeCorrectly() { + converter = new MappingMongoConverter(context); + } - StringWrapper wrapper = new StringWrapper(); - wrapper.container = new Container(); - wrapper.container.content = "Foo!"; + @Test + public void writesGenericTypeCorrectly() { - DBObject dbObject = new BasicDBObject(); - converter.write(wrapper, dbObject); + StringWrapper wrapper = new StringWrapper(); + wrapper.container = new Container(); + wrapper.container.content = "Foo!"; - Object container = dbObject.get("container"); - assertThat(container, is(notNullValue())); - assertTrue(container instanceof DBObject); + DBObject dbObject = new BasicDBObject(); + converter.write(wrapper, dbObject); - Object content = ((DBObject) container).get("content"); - assertTrue(content instanceof String); - assertThat((String) content, is("Foo!")); - } + Object container = dbObject.get("container"); + assertThat(container, is(notNullValue())); + assertTrue(container instanceof DBObject); - @Test - public void readsGenericTypeCorrectly() { + Object content = ((DBObject) container).get("content"); + assertTrue(content instanceof String); + assertThat((String) content, is("Foo!")); + } - DBObject content = new BasicDBObject("content", "Foo!"); - BasicDBObject container = new BasicDBObject("container", content); + @Test + public void readsGenericTypeCorrectly() { - StringWrapper result = converter.read(StringWrapper.class, container); - assertThat(result.container, is(notNullValue())); - assertThat(result.container.content, is("Foo!")); - } + DBObject content = new BasicDBObject("content", "Foo!"); + BasicDBObject container = new BasicDBObject("container", content); - public class StringWrapper extends Wrapper { + StringWrapper result = converter.read(StringWrapper.class, container); + assertThat(result.container, is(notNullValue())); + assertThat(result.container.content, is("Foo!")); + } - } + public class StringWrapper extends Wrapper { - public class Wrapper { - Container container; - } + } - public class Container { - T content; - } + public class Wrapper { + Container container; + } + + public class Container { + T content; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedAppConfig.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedAppConfig.java index 815bc6360..a4ea6fe92 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedAppConfig.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedAppConfig.java @@ -8,21 +8,21 @@ import com.mongodb.Mongo; public class GeoIndexedAppConfig extends AbstractMongoConfiguration { - public static String GEO_DB = "geodb"; - public static String GEO_COLLECTION = "geolocation"; - @Bean - public Mongo mongo() throws Exception { - return new Mongo("localhost"); - } - - @Bean - public MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), "geodb", mappingMongoConverter()); - } - + public static String GEO_DB = "geodb"; + public static String GEO_COLLECTION = "geolocation"; - public String getMappingBasePackage() { - return "org.springframework.data.document.mongodb.mapping"; - } + @Bean + public Mongo mongo() throws Exception { + return new Mongo("localhost"); + } + + @Bean + public MongoTemplate mongoTemplate() throws Exception { + return new MongoTemplate(mongo(), "geodb", mappingMongoConverter()); + } + + public String getMappingBasePackage() { + return "org.springframework.data.document.mongodb.mapping"; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedTests.java index 80cda12b8..43dbc965e 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoIndexedTests.java @@ -44,9 +44,7 @@ import org.springframework.data.document.mongodb.mapping.event.MongoMappingEvent */ public class GeoIndexedTests { - private final String[] collectionsToDrop = new String[]{ - GeoIndexedAppConfig.GEO_COLLECTION - }; + private final String[] collectionsToDrop = new String[] { GeoIndexedAppConfig.GEO_COLLECTION }; ApplicationContext applicationContext; MongoTemplate template; @@ -66,7 +64,7 @@ public class GeoIndexedTests { @Test public void testGeoLocation() { - GeoLocation geo = new GeoLocation(new double[]{40.714346, -74.005966}); + GeoLocation geo = new GeoLocation(new double[] { 40.714346, -74.005966 }); template.insert(geo); boolean hasIndex = template.execute("geolocation", new CollectionCallback() { @@ -83,5 +81,5 @@ public class GeoIndexedTests { assertTrue(hasIndex); } - + } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoLocation.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoLocation.java index 653ee975a..b769742d9 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoLocation.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/GeoLocation.java @@ -23,12 +23,12 @@ import org.springframework.data.document.mongodb.index.GeoSpatialIndexed; /** * @author Jon Brisbin */ -@Document(collection="geolocation") +@Document(collection = "geolocation") public class GeoLocation { @Id private ObjectId id; - @GeoSpatialIndexed(collection="geolocation") + @GeoSpatialIndexed(collection = "geolocation") private double[] location; public GeoLocation(double[] location) { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Location.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Location.java index cf71d9575..7ba523e87 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Location.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Location.java @@ -24,42 +24,42 @@ import org.bson.types.ObjectId; @Document(collection = "places") public class Location { - private ObjectId id; - private double[] latlong; - private int[] numbers; - private float[] amounts; + private ObjectId id; + private double[] latlong; + private int[] numbers; + private float[] amounts; - public Location(double[] latlong, int[] numbers, float[] amounts) { - this.latlong = latlong; - this.numbers = numbers; - this.amounts = amounts; - } + public Location(double[] latlong, int[] numbers, float[] amounts) { + this.latlong = latlong; + this.numbers = numbers; + this.amounts = amounts; + } - public ObjectId getId() { - return id; - } + public ObjectId getId() { + return id; + } - public double[] getLatlong() { - return latlong; - } + public double[] getLatlong() { + return latlong; + } - public void setLatlong(double[] latlong) { - this.latlong = latlong; - } + public void setLatlong(double[] latlong) { + this.latlong = latlong; + } - public int[] getNumbers() { - return numbers; - } + public int[] getNumbers() { + return numbers; + } - public void setNumbers(int[] numbers) { - this.numbers = numbers; - } + public void setNumbers(int[] numbers) { + this.numbers = numbers; + } - public float[] getAmounts() { - return amounts; - } + public float[] getAmounts() { + return amounts; + } - public void setAmounts(float[] amounts) { - this.amounts = amounts; - } + public void setAmounts(float[] amounts) { + this.amounts = amounts; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingMongoConverterUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingMongoConverterUnitTests.java index 2d26cd66d..c0a160277 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingMongoConverterUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingMongoConverterUnitTests.java @@ -38,162 +38,161 @@ import com.mongodb.DBObject; /** * Unit tests for {@link MappingMongoConverter}. - * + * * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) public class MappingMongoConverterUnitTests { - MappingMongoConverter converter; - MongoMappingContext mappingContext; - - @Before - public void setUp() { - mappingContext = new MongoMappingContext(); - converter = new MappingMongoConverter(mappingContext); - } - - @Test - public void convertsAddressCorrectly() { - - Address address = new Address(); - address.city = "New York"; - address.street = "Broadway"; - - DBObject dbObject = new BasicDBObject(); - - converter.write(address, dbObject); - - assertThat(dbObject.get("city").toString(), is("New York")); - assertThat(dbObject.get("street").toString(), is("Broadway")); - } - - @Test - public void convertsJodaTimeTypesCorrectly() { - - List> converters = new ArrayList>(); - converters.add(new LocalDateToDateConverter()); - converters.add(new DateToLocalDateConverter()); - - List> customSimpleTypes = new ArrayList>(); - customSimpleTypes.add(LocalDate.class); - mappingContext.setCustomSimpleTypes(customSimpleTypes); - - converter = new MappingMongoConverter(mappingContext); - converter.setConverters(converters); - converter.afterPropertiesSet(); - - Person person = new Person(); - person.birthDate = new LocalDate(); - - DBObject dbObject = new BasicDBObject(); - converter.write(person, dbObject); - - assertTrue(dbObject.get("birthDate") instanceof Date); - - Person result = converter.read(Person.class, dbObject); - assertThat(result.birthDate, is(notNullValue())); - } + MappingMongoConverter converter; + MongoMappingContext mappingContext; - /** - * @see DATADOC-130 - */ - @Test - public void writesMapTypeCorrectly() { - - Map map = Collections.singletonMap(Locale.US, "Foo"); - - BasicDBObject dbObject = new BasicDBObject(); - converter.write(map, dbObject); - - assertThat(dbObject.get(Locale.US.toString()).toString(), is("Foo")); - } - - /** - * @see DATADOC-130 - */ - @Test - public void readsMapWithCustomKeyTypeCorrectly() { - - DBObject mapObject = new BasicDBObject(Locale.US.toString(), "Value"); - DBObject dbObject = new BasicDBObject("map", mapObject); - - ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, dbObject); - assertThat(result.map.get(Locale.US), is("Value")); - } - - /** - * @see DATADOC-128 - */ - @Test - public void usesDocumentsStoredTypeIfSubtypeOfRequest() { - - DBObject dbObject = new BasicDBObject(); - dbObject.put("birthDate", new LocalDate()); - dbObject.put(MappingMongoConverter.CUSTOM_TYPE_KEY, Person.class.getName()); - - assertThat(converter.read(Contact.class, dbObject), is(Person.class)); - } - - /** - * @see DATADOC-128 - */ - @Test - public void ignoresDocumentsStoredTypeIfCompletelyDifferentTypeRequested() { - - DBObject dbObject = new BasicDBObject(); - dbObject.put("birthDate", new LocalDate()); - dbObject.put(MappingMongoConverter.CUSTOM_TYPE_KEY, Person.class.getName()); - - assertThat(converter.read(BirthDateContainer.class, dbObject), is(BirthDateContainer.class)); - } - - @Test - public void writesTypeDiscriminatorIntoRootObject() { - - Person person = new Person(); - person.birthDate = new LocalDate(); - - DBObject result = new BasicDBObject(); - converter.write(person, result); - - assertThat(result.containsField(MappingMongoConverter.CUSTOM_TYPE_KEY), is(true)); - assertThat(result.get(MappingMongoConverter.CUSTOM_TYPE_KEY).toString(), is(Person.class.getName())); - } - - - public static class Address { - String street; - String city; - } - - interface Contact { - - } - - public static class Person implements Contact { - LocalDate birthDate; - } - - static class ClassWithMapProperty { - Map map; - } - - public static class BirthDateContainer { - LocalDate birthDate; - } - - private class LocalDateToDateConverter implements Converter { + @Before + public void setUp() { + mappingContext = new MongoMappingContext(); + converter = new MappingMongoConverter(mappingContext); + } - public Date convert(LocalDate source) { - return source.toDateMidnight().toDate(); - } - } - - private class DateToLocalDateConverter implements Converter { + @Test + public void convertsAddressCorrectly() { - public LocalDate convert(Date source) { - return new LocalDate(source.getTime()); - } - } + Address address = new Address(); + address.city = "New York"; + address.street = "Broadway"; + + DBObject dbObject = new BasicDBObject(); + + converter.write(address, dbObject); + + assertThat(dbObject.get("city").toString(), is("New York")); + assertThat(dbObject.get("street").toString(), is("Broadway")); + } + + @Test + public void convertsJodaTimeTypesCorrectly() { + + List> converters = new ArrayList>(); + converters.add(new LocalDateToDateConverter()); + converters.add(new DateToLocalDateConverter()); + + List> customSimpleTypes = new ArrayList>(); + customSimpleTypes.add(LocalDate.class); + mappingContext.setCustomSimpleTypes(customSimpleTypes); + + converter = new MappingMongoConverter(mappingContext); + converter.setConverters(converters); + converter.afterPropertiesSet(); + + Person person = new Person(); + person.birthDate = new LocalDate(); + + DBObject dbObject = new BasicDBObject(); + converter.write(person, dbObject); + + assertTrue(dbObject.get("birthDate") instanceof Date); + + Person result = converter.read(Person.class, dbObject); + assertThat(result.birthDate, is(notNullValue())); + } + + /** + * @see DATADOC-130 + */ + @Test + public void writesMapTypeCorrectly() { + + Map map = Collections.singletonMap(Locale.US, "Foo"); + + BasicDBObject dbObject = new BasicDBObject(); + converter.write(map, dbObject); + + assertThat(dbObject.get(Locale.US.toString()).toString(), is("Foo")); + } + + /** + * @see DATADOC-130 + */ + @Test + public void readsMapWithCustomKeyTypeCorrectly() { + + DBObject mapObject = new BasicDBObject(Locale.US.toString(), "Value"); + DBObject dbObject = new BasicDBObject("map", mapObject); + + ClassWithMapProperty result = converter.read(ClassWithMapProperty.class, dbObject); + assertThat(result.map.get(Locale.US), is("Value")); + } + + /** + * @see DATADOC-128 + */ + @Test + public void usesDocumentsStoredTypeIfSubtypeOfRequest() { + + DBObject dbObject = new BasicDBObject(); + dbObject.put("birthDate", new LocalDate()); + dbObject.put(MappingMongoConverter.CUSTOM_TYPE_KEY, Person.class.getName()); + + assertThat(converter.read(Contact.class, dbObject), is(Person.class)); + } + + /** + * @see DATADOC-128 + */ + @Test + public void ignoresDocumentsStoredTypeIfCompletelyDifferentTypeRequested() { + + DBObject dbObject = new BasicDBObject(); + dbObject.put("birthDate", new LocalDate()); + dbObject.put(MappingMongoConverter.CUSTOM_TYPE_KEY, Person.class.getName()); + + assertThat(converter.read(BirthDateContainer.class, dbObject), is(BirthDateContainer.class)); + } + + @Test + public void writesTypeDiscriminatorIntoRootObject() { + + Person person = new Person(); + person.birthDate = new LocalDate(); + + DBObject result = new BasicDBObject(); + converter.write(person, result); + + assertThat(result.containsField(MappingMongoConverter.CUSTOM_TYPE_KEY), is(true)); + assertThat(result.get(MappingMongoConverter.CUSTOM_TYPE_KEY).toString(), is(Person.class.getName())); + } + + public static class Address { + String street; + String city; + } + + interface Contact { + + } + + public static class Person implements Contact { + LocalDate birthDate; + } + + static class ClassWithMapProperty { + Map map; + } + + public static class BirthDateContainer { + LocalDate birthDate; + } + + private class LocalDateToDateConverter implements Converter { + + public Date convert(LocalDate source) { + return source.toDateMidnight().toDate(); + } + } + + private class DateToLocalDateConverter implements Converter { + + public LocalDate convert(Date source) { + return new LocalDate(source.getTime()); + } + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingTests.java index 22a20ea0e..dc8ebe433 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/MappingTests.java @@ -51,20 +51,9 @@ import org.springframework.data.document.mongodb.query.Query; public class MappingTests { private static final Log LOGGER = LogFactory.getLog(MongoDbUtils.class); - private final String[] collectionsToDrop = new String[]{ - "foobar", - "person", - "personmapproperty", - "personpojo", - "personcustomidname", - "personmultidimarrays", - "personmulticollection", - "personwithdbref", - "personnullproperties", - "person1", - "person2", - "account" - }; + private final String[] collectionsToDrop = new String[] { "foobar", "person", "personmapproperty", "personpojo", + "personcustomidname", "personmultidimarrays", "personmulticollection", "personwithdbref", "personnullproperties", + "person1", "person2", "account" }; ApplicationContext applicationContext; MongoTemplate template; @@ -111,20 +100,23 @@ public class MappingTests { PersonCustomIdName p = new PersonCustomIdName(123456, "Custom Id", null); template.insert(p); - List result = template.find(new Query(Criteria.where("lastName").is(p.getLastName())), PersonCustomIdName.class); + List result = template.find(new Query(Criteria.where("lastName").is(p.getLastName())), + PersonCustomIdName.class); assertThat(result.size(), is(1)); assertThat(result.get(0).getFirstName(), is("Custom Id")); PersonCustomIdName p2 = new PersonCustomIdName(654321, "Custom Id", "LastName"); template.insert(p2); - List result2 = template.find(new Query(Criteria.where("lastName").is("LastName")), PersonCustomIdName.class); + List result2 = template.find(new Query(Criteria.where("lastName").is("LastName")), + PersonCustomIdName.class); assertThat(result2.size(), is(1)); assertNotNull(result2.get(0).getLastName()); assertThat(result2.get(0).getLastName(), is("LastName")); // Test "in" query - List result3 = template.find(new Query(Criteria.where("lastName").in("LastName")), PersonCustomIdName.class); + List result3 = template.find(new Query(Criteria.where("lastName").in("LastName")), + PersonCustomIdName.class); assertThat(result3.size(), is(1)); assertNotNull(result3.get(0).getLastName()); assertThat(result3.get(0).getLastName(), is("LastName")); @@ -145,19 +137,19 @@ public class MappingTests { template.insert(p); assertNotNull(p.getId()); - List result = template.find(new Query(Criteria.where("ssn").is(1234567)), PersonMapProperty.class); + List result = template.find(new Query(Criteria.where("ssn").is(1234567)), + PersonMapProperty.class); assertThat(result.size(), is(1)); assertThat(result.get(0).getAccounts().size(), is(2)); - assertThat(result.get(0).getAccounts().get("checking").getBalance(), - is(1000.0f)); + assertThat(result.get(0).getAccounts().get("checking").getBalance(), is(1000.0f)); } @Test - @SuppressWarnings({"unchecked"}) + @SuppressWarnings({ "unchecked" }) public void testWriteEntity() { Address addr = new Address(); - addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"}); + addr.setLines(new String[] { "1234 W. 1st Street", "Apt. 12" }); addr.setCity("Anytown"); addr.setPostalCode(12345); addr.setCountry("USA"); @@ -188,11 +180,11 @@ public class MappingTests { assertThat(result.get(0).getAccounts(), notNullValue()); } - @SuppressWarnings({"unchecked"}) + @SuppressWarnings({ "unchecked" }) @Test public void testUniqueIndex() { Address addr = new Address(); - addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"}); + addr.setLines(new String[] { "1234 W. 1st Street", "Apt. 12" }); addr.setCity("Anytown"); addr.setPostalCode(12345); addr.setCountry("USA"); @@ -214,11 +206,9 @@ public class MappingTests { persons.add(new PersonCustomCollection2(66666, "Person", "Two")); template.insertList(persons); - List p1Results = template.find("person1", - new Query(Criteria.where("ssn").is(55555)), + List p1Results = template.find("person1", new Query(Criteria.where("ssn").is(55555)), PersonCustomCollection1.class); - List p2Results = template.find("person2", - new Query(Criteria.where("ssn").is(66666)), + List p2Results = template.find("person2", new Query(Criteria.where("ssn").is(66666)), PersonCustomCollection2.class); assertThat(p1Results.size(), is(1)); assertThat(p2Results.size(), is(1)); @@ -226,11 +216,7 @@ public class MappingTests { @Test public void testPrimitivesAndCustomCollectionName() { - Location loc = new Location( - new double[]{1.0, 2.0}, - new int[]{1, 2, 3, 4}, - new float[]{1.0f, 2.0f} - ); + Location loc = new Location(new double[] { 1.0, 2.0 }, new int[] { 1, 2, 3, 4 }, new float[] { 1.0f, 2.0f }); template.insert(loc); List result = template.find("places", new Query(Criteria.where("_id").is(loc.getId())), Location.class); @@ -257,30 +243,29 @@ public class MappingTests { DetectedCollectionWithIndex dcwi = new DetectedCollectionWithIndex("test"); template.insert(dcwi); - assertTrue(template.execute(DetectedCollectionWithIndex.class.getSimpleName().toLowerCase(), new CollectionCallback() { - public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException { - List indexes = collection.getIndexInfo(); - for (DBObject dbo : indexes) { - if ("name_1".equals(dbo.get("name"))) { - return true; + assertTrue(template.execute(DetectedCollectionWithIndex.class.getSimpleName().toLowerCase(), + new CollectionCallback() { + public Boolean doInCollection(DBCollection collection) throws MongoException, DataAccessException { + List indexes = collection.getIndexInfo(); + for (DBObject dbo : indexes) { + if ("name_1".equals(dbo.get("name"))) { + return true; + } + } + return false; } - } - return false; - } - })); + })); } @Test public void testMultiDimensionalArrayProperties() { - String[][] grid = new String[][]{ - new String[]{"1", "2", "3", "4"}, - new String[]{"5", "6", "7", "8"}, - new String[]{"9", "10", "11", "12"} - }; + String[][] grid = new String[][] { new String[] { "1", "2", "3", "4" }, new String[] { "5", "6", "7", "8" }, + new String[] { "9", "10", "11", "12" } }; PersonMultiDimArrays p = new PersonMultiDimArrays(123, "Multi", "Dimensional", grid); template.insert(p); - List result = template.find(new Query(Criteria.where("ssn").is(123)), PersonMultiDimArrays.class); + List result = template.find(new Query(Criteria.where("ssn").is(123)), + PersonMultiDimArrays.class); assertThat(result.size(), is(1)); assertThat(result.get(0).getGrid().length, is(3)); @@ -299,7 +284,8 @@ public class MappingTests { PersonMultiCollection p = new PersonMultiCollection(321, "Multi Dim", "Collections", grid); template.insert(p); - List result = template.find(new Query(Criteria.where("ssn").is(321)), PersonMultiCollection.class); + List result = template.find(new Query(Criteria.where("ssn").is(321)), + PersonMultiCollection.class); assertThat(result.size(), is(1)); assertThat(result.get(0).getGrid().size(), is(1)); @@ -307,7 +293,7 @@ public class MappingTests { @Test public void testDbRef() { - double[] pos = new double[]{37.0625, -95.677068}; + double[] pos = new double[] { 37.0625, -95.677068 }; GeoLocation geo = new GeoLocation(pos); template.insert(geo); @@ -327,11 +313,11 @@ public class MappingTests { assertNotNull(p.getId()); } - @SuppressWarnings({"unchecked"}) + @SuppressWarnings({ "unchecked" }) @Test public void testQueryUpdate() { Address addr = new Address(); - addr.setLines(new String[]{"1234 W. 1st Street", "Apt. 12"}); + addr.setLines(new String[] { "1234 W. 1st Street", "Apt. 12" }); addr.setCity("Anytown"); addr.setPostalCode(12345); addr.setCountry("USA"); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Person.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Person.java index fdb0dcd7f..42c9db5e0 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Person.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/Person.java @@ -29,9 +29,7 @@ import org.springframework.data.document.mongodb.index.Indexed; * @author Jon Brisbin */ @Document -@CompoundIndexes({ - @CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}") -}) +@CompoundIndexes({ @CompoundIndex(name = "age_idx", def = "{'lastName': 1, 'age': -1}") }) public class Person { @Id @@ -48,11 +46,10 @@ public class Person { private List accounts; private T address; - public Person(Integer ssn) { - this.ssn = ssn; + this.ssn = ssn; } - + @PersistenceConstructor public Person(Integer ssn, String firstName, String lastName, Integer age, T address) { this.ssn = ssn; diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection1.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection1.java index 96b6437d8..f26a3c131 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection1.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection1.java @@ -22,13 +22,13 @@ import org.springframework.data.annotation.Id; * @author Jon Brisbin */ @Document(collection = "person1") -public class PersonCustomCollection1 extends BasePerson{ +public class PersonCustomCollection1 extends BasePerson { + + @Id + private String id; - @Id - private String id; - public PersonCustomCollection1(Integer ssn, String firstName, String lastName) { super(ssn, firstName, lastName); } - + } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection2.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection2.java index 78a27fc16..283ac509c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection2.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomCollection2.java @@ -24,9 +24,9 @@ import org.springframework.data.annotation.Id; @Document(collection = "person2") public class PersonCustomCollection2 extends BasePerson { - @Id - private String id; - + @Id + private String id; + public PersonCustomCollection2(Integer ssn, String firstName, String lastName) { super(ssn, firstName, lastName); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomIdName.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomIdName.java index 7e47360cf..d9fb4e5fa 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomIdName.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonCustomIdName.java @@ -27,7 +27,6 @@ public class PersonCustomIdName extends BasePerson { @Id private String lastName; - public PersonCustomIdName(Integer ssn, String firstName) { this.ssn = ssn; this.firstName = firstName; diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMapProperty.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMapProperty.java index 4987ecdf1..2da930300 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMapProperty.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMapProperty.java @@ -26,27 +26,27 @@ import org.bson.types.ObjectId; @Document public class PersonMapProperty extends BasePerson { - private ObjectId id; - private Map accounts; + private ObjectId id; + private Map accounts; - public PersonMapProperty(Integer ssn, String firstName, String lastName) { - super(ssn, firstName, lastName); - } + public PersonMapProperty(Integer ssn, String firstName, String lastName) { + super(ssn, firstName, lastName); + } - public ObjectId getId() { - return id; - } + public ObjectId getId() { + return id; + } - public void setId(ObjectId id) { - this.id = id; - } + public void setId(ObjectId id) { + this.id = id; + } - public Map getAccounts() { - return accounts; - } + public Map getAccounts() { + return accounts; + } - public void setAccounts(Map accounts) { - this.accounts = accounts; - } + public void setAccounts(Map accounts) { + this.accounts = accounts; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMultiDimArrays.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMultiDimArrays.java index cd2b770c9..ac2b37461 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMultiDimArrays.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonMultiDimArrays.java @@ -24,8 +24,8 @@ import org.springframework.data.annotation.Id; @Document public class PersonMultiDimArrays extends BasePerson { - @Id - private String id; + @Id + private String id; private String[][] grid; public PersonMultiDimArrays(Integer ssn, String firstName, String lastName, String[][] grid) { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonPojo.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonPojo.java index a2b2ebf72..dbf4d6b5f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonPojo.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonPojo.java @@ -23,18 +23,18 @@ import org.bson.types.ObjectId; */ public class PersonPojo extends BasePerson { - private ObjectId id; + private ObjectId id; - public PersonPojo(Integer ssn, String firstName, String lastName) { - super(ssn, firstName, lastName); - } + public PersonPojo(Integer ssn, String firstName, String lastName) { + super(ssn, firstName, lastName); + } - public ObjectId getId() { - return id; - } + public ObjectId getId() { + return id; + } - public void setId(ObjectId id) { - this.id = id; - } + public void setId(ObjectId id) { + this.id = id; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonSimpleList.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonSimpleList.java index 3bcb89b72..b64754b0e 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonSimpleList.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/PersonSimpleList.java @@ -23,18 +23,18 @@ import java.util.List; */ public class PersonSimpleList extends BasePerson { - private List nicknames; + private List nicknames; - public PersonSimpleList(Integer ssn, String firstName, String lastName) { - super(ssn, firstName, lastName); - } + public PersonSimpleList(Integer ssn, String firstName, String lastName) { + super(ssn, firstName, lastName); + } - public List getNicknames() { - return nicknames; - } + public List getNicknames() { + return nicknames; + } - public void setNicknames(List nicknames) { - this.nicknames = nicknames; - } + public void setNicknames(List nicknames) { + this.nicknames = nicknames; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/SimpleMappingContextUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/SimpleMappingContextUnitTests.java index 444402294..2343dfc17 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/SimpleMappingContextUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/mapping/SimpleMappingContextUnitTests.java @@ -8,23 +8,23 @@ import org.springframework.data.document.mongodb.mapping.SimpleMongoMappingConte import org.springframework.data.mapping.model.PersistentProperty; /** - * + * * @author Oliver Gierke */ public class SimpleMappingContextUnitTests { - @Test - public void testname() { - SimpleMongoMappingContext context = new SimpleMongoMappingContext(); - SimpleMongoPersistentEntity entity = context.getPersistentEntity(Person.class); - - assertThat(entity.getPersistentProperties().isEmpty(), is(false)); - - PersistentProperty idProperty = entity.getIdProperty(); - assertThat(idProperty.getName(), is("id")); - } - - static class Person { - String id; - } + @Test + public void testname() { + SimpleMongoMappingContext context = new SimpleMongoMappingContext(); + SimpleMongoPersistentEntity entity = context.getPersistentEntity(Person.class); + + assertThat(entity.getPersistentProperties().isEmpty(), is(false)); + + PersistentProperty idProperty = entity.getIdProperty(); + assertThat(idProperty.getName(), is("id")); + } + + static class Person { + String id; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/monitor/MongoMonitorIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/monitor/MongoMonitorIntegrationTests.java index 63f59b77a..1e9fd9970 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/monitor/MongoMonitorIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/monitor/MongoMonitorIntegrationTests.java @@ -24,29 +24,28 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.util.Assert; import org.springframework.util.StringUtils; - /** * This test class assumes that you are already running the MongoDB server. - * + * * @author Mark Pollack */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class MongoMonitorIntegrationTests { - @Autowired - Mongo mongo; + @Autowired + Mongo mongo; - @Test - public void serverInfo() { - ServerInfo serverInfo = new ServerInfo(mongo); - String version = serverInfo.getVersion(); - Assert.isTrue(StringUtils.hasText("1.")); - } + @Test + public void serverInfo() { + ServerInfo serverInfo = new ServerInfo(mongo); + String version = serverInfo.getVersion(); + Assert.isTrue(StringUtils.hasText("1.")); + } - @Test - public void operationCounters() { - OperationCounters operationCounters = new OperationCounters(mongo); - operationCounters.getInsertCount(); - } + @Test + public void operationCounters() { + OperationCounters operationCounters = new OperationCounters(mongo); + operationCounters.getInsertCount(); + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/CriteriaTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/CriteriaTests.java index 9109e23b3..ca7797962 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/CriteriaTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/CriteriaTests.java @@ -23,30 +23,30 @@ import com.mongodb.DBObject; public class CriteriaTests { - @Test - public void testSimpleCriteria() { - Criteria c = new Criteria("name").is("Bubba"); - assertEquals("{ \"name\" : \"Bubba\"}", c.getCriteriaObject().toString()); - } + @Test + public void testSimpleCriteria() { + Criteria c = new Criteria("name").is("Bubba"); + assertEquals("{ \"name\" : \"Bubba\"}", c.getCriteriaObject().toString()); + } - @Test - public void testNotEqualCriteria() { - Criteria c = new Criteria("name").ne("Bubba"); - assertEquals("{ \"name\" : { \"$ne\" : \"Bubba\"}}", c.getCriteriaObject().toString()); - } - - @Test - public void buildsIsNullCriteriaCorrectly() { - - DBObject reference = new BasicDBObject("name", null); - - Criteria criteria = new Criteria("name").is(null); - assertThat(criteria.getCriteriaObject(), is(reference)); - } + @Test + public void testNotEqualCriteria() { + Criteria c = new Criteria("name").ne("Bubba"); + assertEquals("{ \"name\" : { \"$ne\" : \"Bubba\"}}", c.getCriteriaObject().toString()); + } - @Test - public void testChainedCriteria() { - Criteria c = new Criteria("name").is("Bubba").and("age").lt(21); - assertEquals("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}", c.getCriteriaObject().toString()); - } + @Test + public void buildsIsNullCriteriaCorrectly() { + + DBObject reference = new BasicDBObject("name", null); + + Criteria criteria = new Criteria("name").is(null); + assertThat(criteria.getCriteriaObject(), is(reference)); + } + + @Test + public void testChainedCriteria() { + Criteria c = new Criteria("name").is("Bubba").and("age").lt(21); + assertEquals("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}", c.getCriteriaObject().toString()); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/IndexTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/IndexTests.java index 5d0b9fe2b..3d7b25f5b 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/IndexTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/IndexTests.java @@ -21,47 +21,47 @@ import org.springframework.data.document.mongodb.query.Index.Duplicates; public class IndexTests { - @Test - public void testWithAscendingIndex() { - Index i = new Index().on("name", Order.ASCENDING); - Assert.assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); - } + @Test + public void testWithAscendingIndex() { + Index i = new Index().on("name", Order.ASCENDING); + Assert.assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); + } - @Test - public void testWithDescendingIndex() { - Index i = new Index().on("name", Order.DESCENDING); - Assert.assertEquals("{ \"name\" : -1}", i.getIndexKeys().toString()); - } + @Test + public void testWithDescendingIndex() { + Index i = new Index().on("name", Order.DESCENDING); + Assert.assertEquals("{ \"name\" : -1}", i.getIndexKeys().toString()); + } - @Test - public void testNamedMultiFieldUniqueIndex() { - Index i = new Index().on("name", Order.ASCENDING).on("age", Order.DESCENDING); - i.named("test").unique(); - Assert.assertEquals("{ \"age\" : -1 , \"name\" : 1}", i.getIndexKeys().toString()); - Assert.assertEquals("{ \"name\" : \"test\" , \"unique\" : true}", i.getIndexOptions().toString()); - } + @Test + public void testNamedMultiFieldUniqueIndex() { + Index i = new Index().on("name", Order.ASCENDING).on("age", Order.DESCENDING); + i.named("test").unique(); + Assert.assertEquals("{ \"age\" : -1 , \"name\" : 1}", i.getIndexKeys().toString()); + Assert.assertEquals("{ \"name\" : \"test\" , \"unique\" : true}", i.getIndexOptions().toString()); + } - @Test - public void testWithDropDuplicates() { - Index i = new Index().on("name", Order.ASCENDING); - i.unique(Duplicates.DROP); - Assert.assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); - Assert.assertEquals("{ \"unique\" : true , \"dropDups\" : true}", i.getIndexOptions().toString()); - } - - @Test - public void testWithSparse() { - Index i = new Index().on("name", Order.ASCENDING); - i.sparse().unique(); - Assert.assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); - Assert.assertEquals("{ \"unique\" : true , \"sparse\" : true}", i.getIndexOptions().toString()); - } + @Test + public void testWithDropDuplicates() { + Index i = new Index().on("name", Order.ASCENDING); + i.unique(Duplicates.DROP); + Assert.assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); + Assert.assertEquals("{ \"unique\" : true , \"dropDups\" : true}", i.getIndexOptions().toString()); + } - @Test - public void testGeospatialIndex() { - GeospatialIndex i = new GeospatialIndex("location").withMin(0); - Assert.assertEquals("{ \"location\" : \"2d\"}", i.getIndexKeys().toString()); - Assert.assertEquals("{ \"min\" : 0}", i.getIndexOptions().toString()); - } + @Test + public void testWithSparse() { + Index i = new Index().on("name", Order.ASCENDING); + i.sparse().unique(); + Assert.assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); + Assert.assertEquals("{ \"unique\" : true , \"sparse\" : true}", i.getIndexOptions().toString()); + } + + @Test + public void testGeospatialIndex() { + GeospatialIndex i = new GeospatialIndex("location").withMin(0); + Assert.assertEquals("{ \"location\" : \"2d\"}", i.getIndexKeys().toString()); + Assert.assertEquals("{ \"min\" : 0}", i.getIndexOptions().toString()); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryMapperUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryMapperUnitTests.java index 608da9222..d8585ac22 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryMapperUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryMapperUnitTests.java @@ -38,40 +38,40 @@ import com.mongodb.DBObject; */ @RunWith(MockitoJUnitRunner.class) public class QueryMapperUnitTests { - - QueryMapper mapper; - - @Mock - MongoConverter converter; - @Mock - MongoPersistentEntity entity; - @Mock - MongoPersistentProperty property; - @Before - public void setUp() { - when(entity.getIdProperty()).thenReturn(property); - when(converter.convertObjectId(any())).thenReturn(new ObjectId()); - mapper = new QueryMapper(converter); - } - - @Test - public void translatesIdPropertyIntoIdKey() { - - DBObject query = new BasicDBObject("foo", "value"); - - when(property.getName()).thenReturn("foo"); - - DBObject result = mapper.getMappedObject(query, entity); - assertThat(result.get("_id"), is(notNullValue())); - assertThat(result.get("foo"), is(nullValue())); - } - - @Test - public void convertsStringIntoObjectId() { - - DBObject query = new BasicDBObject("_id", new ObjectId().toString()); - DBObject result = mapper.getMappedObject(query, null); - assertThat(result.get("_id"), is(ObjectId.class)); - } + QueryMapper mapper; + + @Mock + MongoConverter converter; + @Mock + MongoPersistentEntity entity; + @Mock + MongoPersistentProperty property; + + @Before + public void setUp() { + when(entity.getIdProperty()).thenReturn(property); + when(converter.convertObjectId(any())).thenReturn(new ObjectId()); + mapper = new QueryMapper(converter); + } + + @Test + public void translatesIdPropertyIntoIdKey() { + + DBObject query = new BasicDBObject("foo", "value"); + + when(property.getName()).thenReturn("foo"); + + DBObject result = mapper.getMappedObject(query, entity); + assertThat(result.get("_id"), is(notNullValue())); + assertThat(result.get("foo"), is(nullValue())); + } + + @Test + public void convertsStringIntoObjectId() { + + DBObject query = new BasicDBObject("_id", new ObjectId().toString()); + DBObject result = mapper.getMappedObject(query, null); + assertThat(result.get("_id"), is(ObjectId.class)); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryTests.java index e83a618a2..5c6795c0f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/QueryTests.java @@ -32,8 +32,7 @@ public class QueryTests { @Test public void testQueryWithNot() { - Query q = new Query(where("name").is("Thomas").and("age").not() - .mod(10, 0)); + Query q = new Query(where("name").is("Thomas").and("age").not().mod(10, 0)); String expected = "{ \"name\" : \"Thomas\" , \"age\" : { \"$not\" : { \"$mod\" : [ 10 , 0]}}}"; Assert.assertEquals(expected, q.getQueryObject().toString()); } @@ -43,30 +42,29 @@ public class QueryTests { try { new Query(where("name").not().is("Thomas")); Assert.fail("This should have caused an InvalidDocumentStoreApiUsageException"); - } catch (InvalidDocumentStoreApiUsageException e) {} + } catch (InvalidDocumentStoreApiUsageException e) { + } } @Test public void testOrQuery() { - Query q = new OrQuery(new Query(where("name").is("Sven").and("age") - .lt(50)), new Query(where("age").lt(50)), new BasicQuery( - "{'name' : 'Thomas'}")); + Query q = new OrQuery(new Query(where("name").is("Sven").and("age").lt(50)), new Query(where("age").lt(50)), + new BasicQuery("{'name' : 'Thomas'}")); String expected = "{ \"$or\" : [ { \"name\" : \"Sven\" , \"age\" : { \"$lt\" : 50}} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}"; Assert.assertEquals(expected, q.getQueryObject().toString()); } @Test public void testNorQuery() { - Query q = new NorQuery(new Query(where("name").is("Sven")), new Query( - where("age").lt(50)), new BasicQuery("{'name' : 'Thomas'}")); + Query q = new NorQuery(new Query(where("name").is("Sven")), new Query(where("age").lt(50)), new BasicQuery( + "{'name' : 'Thomas'}")); String expected = "{ \"$nor\" : [ { \"name\" : \"Sven\"} , { \"age\" : { \"$lt\" : 50}} , { \"name\" : \"Thomas\"}]}"; Assert.assertEquals(expected, q.getQueryObject().toString()); } @Test public void testQueryWithLimit() { - Query q = new Query(where("name").gte("M").lte("T").and("age").not() - .gt(22)); + Query q = new Query(where("name").gte("M").lte("T").and("age").not().gt(22)); q.limit(50); String expected = "{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"; Assert.assertEquals(expected, q.getQueryObject().toString()); @@ -75,8 +73,7 @@ public class QueryTests { @Test public void testQueryWithFieldsAndSlice() { - Query q = new Query(where("name").gte("M").lte("T").and("age").not() - .gt(22)); + Query q = new Query(where("name").gte("M").lte("T").and("age").not().gt(22)); q.fields().exclude("address").include("name").slice("orders", 10); String expected = "{ \"name\" : { \"$gte\" : \"M\" , \"$lte\" : \"T\"} , \"age\" : { \"$not\" : { \"$gt\" : 22}}}"; @@ -87,8 +84,7 @@ public class QueryTests { @Test public void testBasicQuery() { - Query q = new BasicQuery("{ \"name\" : \"Thomas\"}").addCriteria(where( - "age").lt(80)); + Query q = new BasicQuery("{ \"name\" : \"Thomas\"}").addCriteria(where("age").lt(80)); String expected = "{ \"name\" : \"Thomas\" , \"age\" : { \"$lt\" : 80}}"; Assert.assertEquals(expected, q.getQueryObject().toString()); } @@ -102,8 +98,8 @@ public class QueryTests { @Test public void testComplexQueryWithMultipleChainedCriteria() { - Query q = new Query(where("name").regex("^T.*").and("age").gt(20) - .lt(80).and("city").in("Stockholm", "London", "New York")); + Query q = new Query(where("name").regex("^T.*").and("age").gt(20).lt(80).and("city") + .in("Stockholm", "London", "New York")); String expected = "{ \"name\" : { \"$regex\" : \"^T.*\"} , \"age\" : { \"$gt\" : 20 , \"$lt\" : 80} , " + "\"city\" : { \"$in\" : [ \"Stockholm\" , \"London\" , \"New York\"]}}"; Assert.assertEquals(expected, q.getQueryObject().toString()); @@ -111,24 +107,19 @@ public class QueryTests { @Test public void testAddCriteriaWithComplexQueryWithMultipleChainedCriteria() { - Query q1 = new Query(where("name").regex("^T.*").and("age").gt(20) - .lt(80).and("city").in("Stockholm", "London", "New York")); - Query q2 = new Query(where("name").regex("^T.*").and("age").gt(20) - .lt(80)).addCriteria(where("city").in("Stockholm", "London", - "New York")); - Assert.assertEquals(q1.getQueryObject().toString(), q2.getQueryObject() - .toString()); - Query q3 = new Query(where("name").regex("^T.*")).addCriteria( - where("age").gt(20).lt(80)).addCriteria( + Query q1 = new Query(where("name").regex("^T.*").and("age").gt(20).lt(80).and("city") + .in("Stockholm", "London", "New York")); + Query q2 = new Query(where("name").regex("^T.*").and("age").gt(20).lt(80)).addCriteria(where("city").in( + "Stockholm", "London", "New York")); + Assert.assertEquals(q1.getQueryObject().toString(), q2.getQueryObject().toString()); + Query q3 = new Query(where("name").regex("^T.*")).addCriteria(where("age").gt(20).lt(80)).addCriteria( where("city").in("Stockholm", "London", "New York")); - Assert.assertEquals(q1.getQueryObject().toString(), q3.getQueryObject() - .toString()); + Assert.assertEquals(q1.getQueryObject().toString(), q3.getQueryObject().toString()); } @Test public void testQueryWithElemMatch() { - Query q = new Query(where("openingHours").elemMatch( - where("dayOfWeek").is("Monday").and("open").lte("1800"))); + Query q = new Query(where("openingHours").elemMatch(where("dayOfWeek").is("Monday").and("open").lte("1800"))); String expected = "{ \"openingHours\" : { \"$elemMatch\" : { \"dayOfWeek\" : \"Monday\" , \"open\" : { \"$lte\" : \"1800\"}}}}"; Assert.assertEquals(expected, q.getQueryObject().toString()); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/SortTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/SortTests.java index eb257cb39..50970d04b 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/SortTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/SortTests.java @@ -20,16 +20,16 @@ import org.junit.Test; public class SortTests { - @Test - public void testWithSortAscending() { - Sort s = new Sort().on("name", Order.ASCENDING); - Assert.assertEquals("{ \"name\" : 1}", s.getSortObject().toString()); - } + @Test + public void testWithSortAscending() { + Sort s = new Sort().on("name", Order.ASCENDING); + Assert.assertEquals("{ \"name\" : 1}", s.getSortObject().toString()); + } - @Test - public void testWithSortDescending() { - Sort s = new Sort().on("name", Order.DESCENDING); - Assert.assertEquals("{ \"name\" : -1}", s.getSortObject().toString()); - } + @Test + public void testWithSortDescending() { + Sort s = new Sort().on("name", Order.DESCENDING); + Assert.assertEquals("{ \"name\" : -1}", s.getSortObject().toString()); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/UpdateTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/UpdateTests.java index 5b3f60391..5a6bb552f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/UpdateTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/query/UpdateTests.java @@ -23,114 +23,101 @@ import org.junit.Test; public class UpdateTests { - @Test - public void testSet() { - Update u = new Update() - .set("directory", "/Users/Test/Desktop"); - Assert.assertEquals("{ \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}", u.getUpdateObject().toString()); - } + @Test + public void testSet() { + Update u = new Update().set("directory", "/Users/Test/Desktop"); + Assert.assertEquals("{ \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}", u.getUpdateObject().toString()); + } - @Test - public void testInc() { - Update u = new Update() - .inc("size", 1); - Assert.assertEquals("{ \"$inc\" : { \"size\" : 1}}", u.getUpdateObject().toString()); - } + @Test + public void testInc() { + Update u = new Update().inc("size", 1); + Assert.assertEquals("{ \"$inc\" : { \"size\" : 1}}", u.getUpdateObject().toString()); + } - @Test - public void testIncAndSet() { - Update u = new Update() - .inc("size", 1) - .set("directory", "/Users/Test/Desktop"); - Assert.assertEquals("{ \"$inc\" : { \"size\" : 1} , \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}", - u.getUpdateObject().toString()); - } + @Test + public void testIncAndSet() { + Update u = new Update().inc("size", 1).set("directory", "/Users/Test/Desktop"); + Assert.assertEquals("{ \"$inc\" : { \"size\" : 1} , \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}", u + .getUpdateObject().toString()); + } - @Test - public void testUnset() { - Update u = new Update() - .unset("directory"); - Assert.assertEquals("{ \"$unset\" : { \"directory\" : 1}}", u.getUpdateObject().toString()); - } + @Test + public void testUnset() { + Update u = new Update().unset("directory"); + Assert.assertEquals("{ \"$unset\" : { \"directory\" : 1}}", u.getUpdateObject().toString()); + } - @Test - public void testPush() { - Map m = new HashMap(); - m.put("name", "Sven"); - Update u = new Update() - .push("authors", m); - Assert.assertEquals("{ \"$push\" : { \"authors\" : { \"name\" : \"Sven\"}}}", u.getUpdateObject().toString()); - } + @Test + public void testPush() { + Map m = new HashMap(); + m.put("name", "Sven"); + Update u = new Update().push("authors", m); + Assert.assertEquals("{ \"$push\" : { \"authors\" : { \"name\" : \"Sven\"}}}", u.getUpdateObject().toString()); + } - @Test - public void testPushAll() { - Map m1 = new HashMap(); - m1.put("name", "Sven"); - Map m2 = new HashMap(); - m2.put("name", "Maria"); - Update u = new Update() - .pushAll("authors", new Object[]{m1, m2}); - Assert.assertEquals("{ \"$pushAll\" : { \"authors\" : [ { \"name\" : \"Sven\"} , { \"name\" : \"Maria\"}]}}", u.getUpdateObject().toString()); - } + @Test + public void testPushAll() { + Map m1 = new HashMap(); + m1.put("name", "Sven"); + Map m2 = new HashMap(); + m2.put("name", "Maria"); + Update u = new Update().pushAll("authors", new Object[] { m1, m2 }); + Assert.assertEquals("{ \"$pushAll\" : { \"authors\" : [ { \"name\" : \"Sven\"} , { \"name\" : \"Maria\"}]}}", u + .getUpdateObject().toString()); + } - @Test - public void testAddToSet() { - Map m = new HashMap(); - m.put("name", "Sven"); - Update u = new Update() - .addToSet("authors", m); - Assert.assertEquals("{ \"$addToSet\" : { \"authors\" : { \"name\" : \"Sven\"}}}", u.getUpdateObject().toString()); - } + @Test + public void testAddToSet() { + Map m = new HashMap(); + m.put("name", "Sven"); + Update u = new Update().addToSet("authors", m); + Assert.assertEquals("{ \"$addToSet\" : { \"authors\" : { \"name\" : \"Sven\"}}}", u.getUpdateObject().toString()); + } - @Test - public void testPop() { - Update u = new Update() - .pop("authors", Update.Position.FIRST); - Assert.assertEquals("{ \"$pop\" : { \"authors\" : -1}}", u.getUpdateObject().toString()); - u = new Update() - .pop("authors", Update.Position.LAST); - Assert.assertEquals("{ \"$pop\" : { \"authors\" : 1}}", u.getUpdateObject().toString()); - } + @Test + public void testPop() { + Update u = new Update().pop("authors", Update.Position.FIRST); + Assert.assertEquals("{ \"$pop\" : { \"authors\" : -1}}", u.getUpdateObject().toString()); + u = new Update().pop("authors", Update.Position.LAST); + Assert.assertEquals("{ \"$pop\" : { \"authors\" : 1}}", u.getUpdateObject().toString()); + } - @Test - public void testPull() { - Map m = new HashMap(); - m.put("name", "Sven"); - Update u = new Update() - .pull("authors", m); - Assert.assertEquals("{ \"$pull\" : { \"authors\" : { \"name\" : \"Sven\"}}}", u.getUpdateObject().toString()); - } + @Test + public void testPull() { + Map m = new HashMap(); + m.put("name", "Sven"); + Update u = new Update().pull("authors", m); + Assert.assertEquals("{ \"$pull\" : { \"authors\" : { \"name\" : \"Sven\"}}}", u.getUpdateObject().toString()); + } - @Test - public void testPullAll() { - Map m1 = new HashMap(); - m1.put("name", "Sven"); - Map m2 = new HashMap(); - m2.put("name", "Maria"); - Update u = new Update() - .pullAll("authors", new Object[]{m1, m2}); - Assert.assertEquals("{ \"$pullAll\" : { \"authors\" : [ { \"name\" : \"Sven\"} , { \"name\" : \"Maria\"}]}}", u.getUpdateObject().toString()); - } + @Test + public void testPullAll() { + Map m1 = new HashMap(); + m1.put("name", "Sven"); + Map m2 = new HashMap(); + m2.put("name", "Maria"); + Update u = new Update().pullAll("authors", new Object[] { m1, m2 }); + Assert.assertEquals("{ \"$pullAll\" : { \"authors\" : [ { \"name\" : \"Sven\"} , { \"name\" : \"Maria\"}]}}", u + .getUpdateObject().toString()); + } - @Test - public void testRename() { - Update u = new Update() - .rename("directory", "folder"); - Assert.assertEquals("{ \"$rename\" : { \"directory\" : \"folder\"}}", u.getUpdateObject().toString()); - } + @Test + public void testRename() { + Update u = new Update().rename("directory", "folder"); + Assert.assertEquals("{ \"$rename\" : { \"directory\" : \"folder\"}}", u.getUpdateObject().toString()); + } - @Test - public void testBasicUpdateInc() { - Update u = new Update() - .inc("size", 1); - Assert.assertEquals("{ \"$inc\" : { \"size\" : 1}}", u.getUpdateObject().toString()); - } + @Test + public void testBasicUpdateInc() { + Update u = new Update().inc("size", 1); + Assert.assertEquals("{ \"$inc\" : { \"size\" : 1}}", u.getUpdateObject().toString()); + } - @Test - public void testBasicUpdateIncAndSet() { - Update u = new BasicUpdate("{ \"$inc\" : { \"size\" : 1}}") - .set("directory", "/Users/Test/Desktop"); - Assert.assertEquals("{ \"$inc\" : { \"size\" : 1} , \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}", - u.getUpdateObject().toString()); - } + @Test + public void testBasicUpdateIncAndSet() { + Update u = new BasicUpdate("{ \"$inc\" : { \"size\" : 1}}").set("directory", "/Users/Test/Desktop"); + Assert.assertEquals("{ \"$inc\" : { \"size\" : 1} , \"$set\" : { \"directory\" : \"/Users/Test/Desktop\"}}", u + .getUpdateObject().toString()); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java index 6c79779e9..3f08bc2b9 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/AbstractPersonRepositoryIntegrationTests.java @@ -29,212 +29,212 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) public abstract class AbstractPersonRepositoryIntegrationTests { - @Autowired - protected PersonRepository repository; - Person dave, carter, boyd, stefan, leroi; - QPerson person; + @Autowired + protected PersonRepository repository; + Person dave, carter, boyd, stefan, leroi; + QPerson person; - @Before - public void setUp() { + @Before + public void setUp() { - repository.deleteAll(); + repository.deleteAll(); - dave = new Person("Dave", "Matthews", 42); - carter = new Person("Carter", "Beauford", 49); - boyd = new Person("Boyd", "Tinsley", 45); - stefan = new Person("Stefan", "Lessard", 34); - leroi = new Person("Leroi", "Moore", 41); + dave = new Person("Dave", "Matthews", 42); + carter = new Person("Carter", "Beauford", 49); + boyd = new Person("Boyd", "Tinsley", 45); + stefan = new Person("Stefan", "Lessard", 34); + leroi = new Person("Leroi", "Moore", 41); - person = new QPerson("person"); + person = new QPerson("person"); - repository.save(Arrays.asList(dave, carter, boyd, stefan, leroi)); - } + repository.save(Arrays.asList(dave, carter, boyd, stefan, leroi)); + } - @Test - public void findsPersonById() throws Exception { + @Test + public void findsPersonById() throws Exception { - assertThat(repository.findOne(dave.getId()), is(dave)); - } + assertThat(repository.findOne(dave.getId()), is(dave)); + } - @Test - public void findsAllMusicians() throws Exception { - List result = repository.findAll(); - assertThat(result, hasItems(dave, carter, boyd, stefan, leroi)); - assertThat(result.size(), is(5)); - } + @Test + public void findsAllMusicians() throws Exception { + List result = repository.findAll(); + assertThat(result, hasItems(dave, carter, boyd, stefan, leroi)); + assertThat(result.size(), is(5)); + } - @Test - public void deletesPersonCorrectly() throws Exception { + @Test + public void deletesPersonCorrectly() throws Exception { - repository.delete(dave); + repository.delete(dave); - List result = repository.findAll(); + List result = repository.findAll(); - assertThat(result.size(), is(4)); - assertThat(result, not(hasItem(dave))); - } - - @Test - public void deletesPersonByIdCorrectly() { - - repository.delete(dave.getId()); + assertThat(result.size(), is(4)); + assertThat(result, not(hasItem(dave))); + } - List result = repository.findAll(); + @Test + public void deletesPersonByIdCorrectly() { - assertThat(result.size(), is(4)); - assertThat(result, not(hasItem(dave))); - } + repository.delete(dave.getId()); - @Test - public void findsPersonsByLastname() throws Exception { + List result = repository.findAll(); - List result = repository.findByLastname("Beauford"); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(carter)); - } + assertThat(result.size(), is(4)); + assertThat(result, not(hasItem(dave))); + } - @Test - public void findsPersonsByFirstname() { + @Test + public void findsPersonsByLastname() throws Exception { - List result = repository.findByThePersonsFirstname("Leroi"); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(leroi)); - assertThat(result.get(0).getAge(),is(nullValue())); - } + List result = repository.findByLastname("Beauford"); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(carter)); + } - @Test - public void findsPersonsByFirstnameLike() throws Exception { + @Test + public void findsPersonsByFirstname() { - List result = repository.findByFirstnameLike("Bo*"); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(boyd)); - } + List result = repository.findByThePersonsFirstname("Leroi"); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(leroi)); + assertThat(result.get(0).getAge(), is(nullValue())); + } - @Test - public void findsPagedPersons() throws Exception { + @Test + public void findsPersonsByFirstnameLike() throws Exception { - Page result = repository.findAll(new PageRequest(1, 2, Direction.ASC, "lastname")); - assertThat(result.isFirstPage(), is(false)); - assertThat(result.isLastPage(), is(false)); - assertThat(result, hasItems(dave, leroi)); - } + List result = repository.findByFirstnameLike("Bo*"); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(boyd)); + } - @Test - public void executesPagedFinderCorrectly() throws Exception { + @Test + public void findsPagedPersons() throws Exception { - Page page = repository.findByLastnameLike("*a*", new PageRequest(0, 2, Direction.ASC, "lastname")); - assertThat(page.isFirstPage(), is(true)); - assertThat(page.isLastPage(), is(false)); - assertThat(page.getNumberOfElements(), is(2)); - assertThat(page, hasItems(carter, stefan)); - } + Page result = repository.findAll(new PageRequest(1, 2, Direction.ASC, "lastname")); + assertThat(result.isFirstPage(), is(false)); + assertThat(result.isLastPage(), is(false)); + assertThat(result, hasItems(dave, leroi)); + } - @Test - public void findsPersonInAgeRangeCorrectly() throws Exception { + @Test + public void executesPagedFinderCorrectly() throws Exception { - List result = repository.findByAgeBetween(40, 45); - assertThat(result.size(), is(2)); - assertThat(result, hasItems(dave, leroi)); - } + Page page = repository.findByLastnameLike("*a*", new PageRequest(0, 2, Direction.ASC, "lastname")); + assertThat(page.isFirstPage(), is(true)); + assertThat(page.isLastPage(), is(false)); + assertThat(page.getNumberOfElements(), is(2)); + assertThat(page, hasItems(carter, stefan)); + } - @Test - public void findsPersonByShippingAddressesCorrectly() throws Exception { + @Test + public void findsPersonInAgeRangeCorrectly() throws Exception { - Address address = new Address("Foo Street 1", "C0123", "Bar"); - dave.setShippingAddresses(new HashSet
                  (asList(address))); + List result = repository.findByAgeBetween(40, 45); + assertThat(result.size(), is(2)); + assertThat(result, hasItems(dave, leroi)); + } - repository.save(dave); - assertThat(repository.findByShippingAddresses(address), is(dave)); - } + @Test + public void findsPersonByShippingAddressesCorrectly() throws Exception { - @Test - public void findsPersonByAddressCorrectly() throws Exception { + Address address = new Address("Foo Street 1", "C0123", "Bar"); + dave.setShippingAddresses(new HashSet
                  (asList(address))); - Address address = new Address("Foo Street 1", "C0123", "Bar"); - dave.setAddress(address); - repository.save(dave); + repository.save(dave); + assertThat(repository.findByShippingAddresses(address), is(dave)); + } - List result = repository.findByAddress(address); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(dave)); - } + @Test + public void findsPersonByAddressCorrectly() throws Exception { - @Test - public void findsPeopleByZipCode() throws Exception { + Address address = new Address("Foo Street 1", "C0123", "Bar"); + dave.setAddress(address); + repository.save(dave); - Address address = new Address("Foo Street 1", "C0123", "Bar"); - dave.setAddress(address); - repository.save(dave); + List result = repository.findByAddress(address); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(dave)); + } - List result = repository.findByAddressZipCode(address.getZipCode()); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(dave)); - } + @Test + public void findsPeopleByZipCode() throws Exception { - @Test - public void findsPeopleByQueryDslLastnameSpec() throws Exception { + Address address = new Address("Foo Street 1", "C0123", "Bar"); + dave.setAddress(address); + repository.save(dave); - List result = repository.findAll(person.lastname.eq("Matthews")); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(dave)); - } + List result = repository.findByAddressZipCode(address.getZipCode()); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(dave)); + } - @Test - public void findsPeopleByzipCodePredicate() throws Exception { + @Test + public void findsPeopleByQueryDslLastnameSpec() throws Exception { - Address address = new Address("Foo Street 1", "C0123", "Bar"); - dave.setAddress(address); - repository.save(dave); + List result = repository.findAll(person.lastname.eq("Matthews")); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(dave)); + } - List result = repository.findAll(person.address.zipCode.eq("C0123")); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(dave)); - } - - @Test - public void findsPeopleByLocationNear() { - Point point = new Point(-73.99171, 40.738868); - dave.setLocation(point); - repository.save(dave); - - List result = repository.findByLocationNear(point); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(dave)); - } - - @Test - public void findsPeopleByLocationWithinCircle() { - Point point = new Point(-73.99171, 40.738868); - dave.setLocation(point); - repository.save(dave); - - List result = repository.findByLocationWithin(new Circle(-78.99171, 45.738868, 170)); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(dave)); - } - - @Test - @Ignore - public void findsPeopleByLocationWithinBox() { - Point point = new Point(-73.99171, 40.738868); - dave.setLocation(point); - repository.save(dave); - - Box box = new Box(new Point(-78.99171, 35.738868), new Point(-68.99171, 45.738868)); - - List result = repository.findByLocationWithin(box); - assertThat(result.size(), is(1)); - assertThat(result, hasItem(dave)); - } + @Test + public void findsPeopleByzipCodePredicate() throws Exception { - @Test - public void findsPagedPeopleByPredicate() throws Exception { + Address address = new Address("Foo Street 1", "C0123", "Bar"); + dave.setAddress(address); + repository.save(dave); - Page page = repository.findAll(person.lastname.contains("a"), new PageRequest(0, 2, Direction.ASC, - "lastname")); - assertThat(page.isFirstPage(), is(true)); - assertThat(page.isLastPage(), is(false)); - assertThat(page.getNumberOfElements(), is(2)); - assertThat(page, hasItems(carter, stefan)); - } + List result = repository.findAll(person.address.zipCode.eq("C0123")); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(dave)); + } + + @Test + public void findsPeopleByLocationNear() { + Point point = new Point(-73.99171, 40.738868); + dave.setLocation(point); + repository.save(dave); + + List result = repository.findByLocationNear(point); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(dave)); + } + + @Test + public void findsPeopleByLocationWithinCircle() { + Point point = new Point(-73.99171, 40.738868); + dave.setLocation(point); + repository.save(dave); + + List result = repository.findByLocationWithin(new Circle(-78.99171, 45.738868, 170)); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(dave)); + } + + @Test + @Ignore + public void findsPeopleByLocationWithinBox() { + Point point = new Point(-73.99171, 40.738868); + dave.setLocation(point); + repository.save(dave); + + Box box = new Box(new Point(-78.99171, 35.738868), new Point(-68.99171, 45.738868)); + + List result = repository.findByLocationWithin(box); + assertThat(result.size(), is(1)); + assertThat(result, hasItem(dave)); + } + + @Test + public void findsPagedPeopleByPredicate() throws Exception { + + Page page = repository.findAll(person.lastname.contains("a"), new PageRequest(0, 2, Direction.ASC, + "lastname")); + assertThat(page.isFirstPage(), is(true)); + assertThat(page.isLastPage(), is(false)); + assertThat(page.getNumberOfElements(), is(2)); + assertThat(page, hasItems(carter, stefan)); + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Address.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Address.java index 770725da0..e65c762c0 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Address.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Address.java @@ -23,64 +23,67 @@ import com.mysema.query.annotations.QueryEmbeddable; @QueryEmbeddable public class Address { - private String street; - private String zipCode; - private String city; + private String street; + private String zipCode; + private String city; - protected Address() { + protected Address() { - } + } - /** - * @param string - * @param string2 - * @param string3 - */ - public Address(String street, String zipcode, String city) { - this.street = street; - this.zipCode = zipcode; - this.city = city; - } + /** + * @param string + * @param string2 + * @param string3 + */ + public Address(String street, String zipcode, String city) { + this.street = street; + this.zipCode = zipcode; + this.city = city; + } - /** - * @return the street - */ - public String getStreet() { - return street; - } + /** + * @return the street + */ + public String getStreet() { + return street; + } - /** - * @param street the street to set - */ - public void setStreet(String street) { - this.street = street; - } + /** + * @param street + * the street to set + */ + public void setStreet(String street) { + this.street = street; + } - /** - * @return the zipCode - */ - public String getZipCode() { - return zipCode; - } + /** + * @return the zipCode + */ + public String getZipCode() { + return zipCode; + } - /** - * @param zipCode the zipCode to set - */ - public void setZipCode(String zipCode) { - this.zipCode = zipCode; - } + /** + * @param zipCode + * the zipCode to set + */ + public void setZipCode(String zipCode) { + this.zipCode = zipCode; + } - /** - * @return the city - */ - public String getCity() { - return city; - } + /** + * @return the city + */ + public String getCity() { + return city; + } - /** - * @param city the city to set - */ - public void setCity(String city) { - this.city = city; - } + /** + * @param city + * the city to set + */ + public void setCity(String city) { + this.city = city; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Contact.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Contact.java index a644fa5e3..2f1601e10 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Contact.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Contact.java @@ -26,15 +26,15 @@ import org.springframework.data.document.mongodb.mapping.Document; */ @Document abstract class Contact { - - @Id - protected final String id; - - public Contact() { - this.id = new ObjectId().toString(); - } - public String getId() { - return id; - } + @Id + protected final String id; + + public Contact() { + this.id = new ObjectId().toString(); + } + + public String getId() { + return id; + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepository.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepository.java index f5e1b5ec1..08d26b06a 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepository.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepository.java @@ -17,7 +17,7 @@ package org.springframework.data.document.mongodb.repository; /** * Simple repository interface managing {@link Contact}s. - * + * * @author Oliver Gierke */ public interface ContactRepository extends MongoRepository { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepositoryIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepositoryIntegrationTests.java index 099d972bb..511070d20 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepositoryIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/ContactRepositoryIntegrationTests.java @@ -31,16 +31,16 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("config/MongoNamespaceIntegrationTests-context.xml") public class ContactRepositoryIntegrationTests { - - @Autowired - ContactRepository repository; - @Test - public void readsAndWritesContactCorrectly() { - - Person person = new Person("Oliver", "Gierke"); - Contact result = repository.save(person); - - assertTrue(repository.findOne(result.getId()) instanceof Person); - } + @Autowired + ContactRepository repository; + + @Test + public void readsAndWritesContactCorrectly() { + + Person person = new Person("Oliver", "Gierke"); + Contact result = repository.save(person); + + assertTrue(repository.findOne(result.getId()) instanceof Person); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoQueryCreatorUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoQueryCreatorUnitTests.java index ad4753d02..88d806f76 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoQueryCreatorUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoQueryCreatorUnitTests.java @@ -38,66 +38,61 @@ import org.springframework.data.repository.query.parser.PartTree; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; - /** * Unit test for {@link MongoQueryCreator}. - * + * * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) public class MongoQueryCreatorUnitTests { - Method findByFirstname, findByFirstnameAndFriend, findByFirstnameNotNull; + Method findByFirstname, findByFirstnameAndFriend, findByFirstnameNotNull; - @Mock - MongoConverter converter; + @Mock + MongoConverter converter; + @Before + public void setUp() throws SecurityException, NoSuchMethodException { - @Before - public void setUp() throws SecurityException, NoSuchMethodException { - - doAnswer(new Answer() { - public Void answer(InvocationOnMock invocation) throws Throwable { - DBObject dbObject = (DBObject) invocation.getArguments()[1]; - dbObject.put("value", new BasicDBObject("value", "value")); - return null; - } - }).when(converter).write(any(), Mockito.any(DBObject.class)); + doAnswer(new Answer() { + public Void answer(InvocationOnMock invocation) throws Throwable { + DBObject dbObject = (DBObject) invocation.getArguments()[1]; + dbObject.put("value", new BasicDBObject("value", "value")); + return null; + } + }).when(converter).write(any(), Mockito.any(DBObject.class)); - } + } + @Test + public void createsQueryCorrectly() throws Exception { - @Test - public void createsQueryCorrectly() throws Exception { + PartTree tree = new PartTree("findByFirstName", Person.class); - PartTree tree = new PartTree("findByFirstName", Person.class); + MongoQueryCreator creator = new MongoQueryCreator(tree, getAccessor(converter, "Oliver")); - MongoQueryCreator creator = - new MongoQueryCreator(tree, getAccessor(converter, "Oliver")); + creator.createQuery(); - creator.createQuery(); + creator = new MongoQueryCreator(new PartTree("findByFirstNameAndFriend", Person.class), getAccessor(converter, + "Oliver", new Person())); + creator.createQuery(); + } - creator = - new MongoQueryCreator(new PartTree("findByFirstNameAndFriend", - Person.class), getAccessor(converter, "Oliver", new Person())); - creator.createQuery(); - } - - @Test - public void createsNotNullQueryCorrectly() { - - PartTree tree = new PartTree("findByFirstNameNotNull", Person.class); - Query query = new MongoQueryCreator(tree, getAccessor(converter)).createQuery(); - - assertThat(query.getQueryObject(), is(new Query(Criteria.where("firstName").ne(null)).getQueryObject())); - } - - @Test - public void createsIsNullQueryCorrectly() { - - PartTree tree = new PartTree("findByFirstNameIsNull", Person.class); - Query query = new MongoQueryCreator(tree, getAccessor(converter)).createQuery(); - - assertThat(query.getQueryObject(), is(new Query(Criteria.where("firstName").is(null)).getQueryObject())); - } + @Test + public void createsNotNullQueryCorrectly() { + + PartTree tree = new PartTree("findByFirstNameNotNull", Person.class); + Query query = new MongoQueryCreator(tree, getAccessor(converter)).createQuery(); + + assertThat(query.getQueryObject(), is(new Query(Criteria.where("firstName").ne(null)).getQueryObject())); + } + + @Test + public void createsIsNullQueryCorrectly() { + + PartTree tree = new PartTree("findByFirstNameIsNull", Person.class); + Query query = new MongoQueryCreator(tree, getAccessor(converter)).createQuery(); + + assertThat(query.getQueryObject(), is(new Query(Criteria.where("firstName").is(null)).getQueryObject())); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryUnitTests.java index 656a2b6e8..fef2b7276 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/MongoRepositoryFactoryUnitTests.java @@ -32,42 +32,41 @@ import org.springframework.data.mapping.model.MappingContext; /** * Unit test for {@link MongoRepositoryFactory}. - * + * * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) public class MongoRepositoryFactoryUnitTests { - @Mock - MongoTemplate template; + @Mock + MongoTemplate template; - @Mock - MappingContext, MongoPersistentProperty> mappingContext; - - @Mock - @SuppressWarnings("rawtypes") - MongoPersistentEntity entity; - - - @Test(expected = IllegalArgumentException.class) - public void rejectsInvalidIdType() throws Exception { - MongoRepositoryFactory factory = new MongoRepositoryFactory(template, null); - factory.getRepository(SampleRepository.class); - } - - @Test - @SuppressWarnings("unchecked") - public void usesMappingMongoEntityInformationIfMappingContextSet() { - - when(mappingContext.getPersistentEntity(Person.class)).thenReturn(entity); - when(entity.getType()).thenReturn(Person.class); - - MongoRepositoryFactory factory = new MongoRepositoryFactory(template, mappingContext); - MongoEntityInformation entityInformation = factory.getEntityInformation(Person.class); - assertTrue(entityInformation instanceof MappingMongoEntityInformation); - } + @Mock + MappingContext, MongoPersistentProperty> mappingContext; - private interface SampleRepository extends MongoRepository { + @Mock + @SuppressWarnings("rawtypes") + MongoPersistentEntity entity; - } + @Test(expected = IllegalArgumentException.class) + public void rejectsInvalidIdType() throws Exception { + MongoRepositoryFactory factory = new MongoRepositoryFactory(template, null); + factory.getRepository(SampleRepository.class); + } + + @Test + @SuppressWarnings("unchecked") + public void usesMappingMongoEntityInformationIfMappingContextSet() { + + when(mappingContext.getPersistentEntity(Person.class)).thenReturn(entity); + when(entity.getType()).thenReturn(Person.class); + + MongoRepositoryFactory factory = new MongoRepositoryFactory(template, mappingContext); + MongoEntityInformation entityInformation = factory.getEntityInformation(Person.class); + assertTrue(entityInformation instanceof MappingMongoEntityInformation); + } + + private interface SampleRepository extends MongoRepository { + + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Person.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Person.java index 4f9cd5e05..c59fa9c0c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Person.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/Person.java @@ -21,190 +21,182 @@ import org.springframework.data.document.mongodb.geo.Point; import org.springframework.data.document.mongodb.index.GeoSpatialIndexed; import org.springframework.data.document.mongodb.mapping.Document; - /** * Sample domain class. - * + * * @author Oliver Gierke */ @Document public class Person extends Contact { - private String firstname; - private String lastname; - private Integer age; - - @GeoSpatialIndexed - private Point location; + private String firstname; + private String lastname; + private Integer age; - private Address address; - private Set
                  shippingAddresses; + @GeoSpatialIndexed + private Point location; + private Address address; + private Set
                  shippingAddresses; - public Person() { + public Person() { - this(null, null); - } + this(null, null); + } + public Person(String firstname, String lastname) { - public Person(String firstname, String lastname) { + this(firstname, lastname, null); + } - this(firstname, lastname, null); - } + public Person(String firstname, String lastname, Integer age) { + super(); + this.firstname = firstname; + this.lastname = lastname; + this.age = age; + } - public Person(String firstname, String lastname, Integer age) { + /** + * @return the firstname + */ + public String getFirstname() { - super(); - this.firstname = firstname; - this.lastname = lastname; - this.age = age; - } + return firstname; + } - /** - * @return the firstname - */ - public String getFirstname() { + /** + * @param firstname + * the firstname to set + */ + public void setFirstname(String firstname) { - return firstname; - } + this.firstname = firstname; + } + /** + * @return the lastname + */ + public String getLastname() { - /** - * @param firstname the firstname to set - */ - public void setFirstname(String firstname) { + return lastname; + } - this.firstname = firstname; - } + /** + * @param lastname + * the lastname to set + */ + public void setLastname(String lastname) { + this.lastname = lastname; + } - /** - * @return the lastname - */ - public String getLastname() { + /** + * @return the age + */ + public Integer getAge() { - return lastname; - } + return age; + } + /** + * @param age + * the age to set + */ + public void setAge(Integer age) { - /** - * @param lastname the lastname to set - */ - public void setLastname(String lastname) { + this.age = age; + } - this.lastname = lastname; - } + /** + * @return the location + */ + public Point getLocation() { + return location; + } + /** + * @param location + * the location to set + */ + public void setLocation(Point location) { + this.location = location; + } - /** - * @return the age - */ - public Integer getAge() { + /** + * @return the address + */ + public Address getAddress() { + return address; + } - return age; - } + /** + * @param address + * the address to set + */ + public void setAddress(Address address) { + this.address = address; + } + /** + * @return the addresses + */ + public Set
                  getShippingAddresses() { + return shippingAddresses; + } - /** - * @param age the age to set - */ - public void setAge(Integer age) { + /** + * @param addresses + * the addresses to set + */ + public void setShippingAddresses(Set
                  addresses) { + this.shippingAddresses = addresses; + } - this.age = age; - } + /* (non-Javadoc) + * @see org.springframework.data.document.mongodb.repository.Contact#getName() + */ + public String getName() { + return String.format("%s %s", firstname, lastname); + } - - /** - * @return the location - */ - public Point getLocation() { - return location; - } - - /** - * @param location the location to set - */ - public void setLocation(Point location) { - this.location = location; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { - /** - * @return the address - */ - public Address getAddress() { - return address; - } + if (this == obj) { + return true; + } + if (obj == null || !getClass().equals(obj.getClass())) { + return false; + } - /** - * @param address the address to set - */ - public void setAddress(Address address) { - this.address = address; - } + Person that = (Person) obj; - /** - * @return the addresses - */ - public Set
                  getShippingAddresses() { - return shippingAddresses; - } + return this.getId().equals(that.getId()); + } + /* + * (non-Javadoc) + * + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { - /** - * @param addresses the addresses to set - */ - public void setShippingAddresses(Set
                  addresses) { - this.shippingAddresses = addresses; - } + return getId().hashCode(); + } - - /* (non-Javadoc) - * @see org.springframework.data.document.mongodb.repository.Contact#getName() - */ - public String getName() { - return String.format("%s %s", firstname, lastname); - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ - @Override - public boolean equals(Object obj) { - - if (this == obj) { - return true; - } - - if (obj == null || !getClass().equals(obj.getClass())) { - return false; - } - - Person that = (Person) obj; - - return this.getId().equals(that.getId()); - } - - - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ - @Override - public int hashCode() { - - return getId().hashCode(); - } - - /* (non-Javadoc) - * @see java.lang.Object#toString() - */ - @Override - public String toString() { - return String.format("%s %s", firstname, lastname); - } + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return String.format("%s %s", firstname, lastname); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java index f0e47c53d..3946564be 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepository.java @@ -24,106 +24,98 @@ import org.springframework.data.document.mongodb.geo.Point; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; - /** * Sample repository managing {@link Person} entities. - * + * * @author Oliver Gierke */ public interface PersonRepository extends MongoRepository, QueryDslPredicateExecutor { - /** - * Returns all {@link Person}s with the given lastname. - * - * @param lastname - * @return - */ - List findByLastname(String lastname); + /** + * Returns all {@link Person}s with the given lastname. + * + * @param lastname + * @return + */ + List findByLastname(String lastname); - /** - * Returns the {@link Person}s with the given firstname. Uses {@link Query} annotation to define the query to be - * executed. - * - * @param firstname - * @return - */ - @Query(value="{ 'firstname' : ?0 }", fields="{ 'firstname': 1, 'lastname': 1}") - List findByThePersonsFirstname(String firstname); + /** + * Returns the {@link Person}s with the given firstname. Uses {@link Query} annotation to define the query to be + * executed. + * + * @param firstname + * @return + */ + @Query(value = "{ 'firstname' : ?0 }", fields = "{ 'firstname': 1, 'lastname': 1}") + List findByThePersonsFirstname(String firstname); + /** + * Returns all {@link Person}s with a firstname matching the given one (*-wildcard supported). + * + * @param firstname + * @return + */ + List findByFirstnameLike(String firstname); - /** - * Returns all {@link Person}s with a firstname matching the given one - * (*-wildcard supported). - * - * @param firstname - * @return - */ - List findByFirstnameLike(String firstname); + /** + * Returns a page of {@link Person}s with a lastname mathing the given one (*-wildcards supported). + * + * @param lastname + * @param pageable + * @return + */ + Page findByLastnameLike(String lastname, Pageable pageable); + /** + * Returns all {@link Person}s with a firstname contained in the given varargs. + * + * @param firstnames + * @return + */ + List findByFirstnameIn(String... firstnames); - /** - * Returns a page of {@link Person}s with a lastname mathing the given one - * (*-wildcards supported). - * - * @param lastname - * @param pageable - * @return - */ - Page findByLastnameLike(String lastname, Pageable pageable); + /** + * Returns all {@link Person}s with a firstname not contained in the given collection. + * + * @param firstnames + * @return + */ + List findByFirstnameNotIn(Collection firstnames); - /** - * Returns all {@link Person}s with a firstname contained in the given varargs. - * - * @param firstnames - * @return - */ - List findByFirstnameIn(String... firstnames); + /** + * Returns all {@link Person}s with an age between the two given values. + * + * @param from + * @param to + * @return + */ + List findByAgeBetween(int from, int to); - /** - * Returns all {@link Person}s with a firstname not contained in the given collection. - * - * @param firstnames - * @return - */ - List findByFirstnameNotIn(Collection firstnames); + /** + * Returns the {@link Person} with the given {@link Address} as shipping address. + * + * @param address + * @return + */ + Person findByShippingAddresses(Address address); - /** - * Returns all {@link Person}s with an age between the two given values. - * - * @param from - * @param to - * @return - */ - List findByAgeBetween(int from, int to); + /** + * Returns all {@link Person}s with the given {@link Address}. + * + * @param address + * @return + */ + List findByAddress(Address address); + List findByAddressZipCode(String zipCode); - /** - * Returns the {@link Person} with the given {@link Address} as shipping address. - * - * @param address - * @return - */ - Person findByShippingAddresses(Address address); + List findByLastnameLikeAndAgeBetween(String lastname, int from, int to); + List findByAgeOrLastnameLikeAndFirstnameLike(int age, String lastname, String firstname); - /** - * Returns all {@link Person}s with the given {@link Address}. - * - * @param address - * @return - */ - List findByAddress(Address address); + List findByLocationNear(Point point); + List findByLocationWithin(Circle circle); - List findByAddressZipCode(String zipCode); - - List findByLastnameLikeAndAgeBetween(String lastname, int from, int to); - - List findByAgeOrLastnameLikeAndFirstnameLike(int age, String lastname, String firstname); - - List findByLocationNear(Point point); - - List findByLocationWithin(Circle circle); - - List findByLocationWithin(Box box); + List findByLocationWithin(Box box); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepositoryIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepositoryIntegrationTests.java index 1c7461171..860951383 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepositoryIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/PersonRepositoryIntegrationTests.java @@ -17,13 +17,11 @@ package org.springframework.data.document.mongodb.repository; import org.springframework.test.context.ContextConfiguration; - /** * Integration test for {@link PersonRepository}. - * + * * @author Oliver Gierke */ @ContextConfiguration -public class PersonRepositoryIntegrationTests extends - AbstractPersonRepositoryIntegrationTests { +public class PersonRepositoryIntegrationTests extends AbstractPersonRepositoryIntegrationTests { } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQueryUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQueryUnitTests.java index f60845145..e701686f2 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQueryUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StringBasedMongoQueryUnitTests.java @@ -38,65 +38,66 @@ import com.mongodb.DBObject; /** * Unit tests for {@link StringBasedMongoQuery}. - * + * * @author Oliver Gierke */ @RunWith(MockitoJUnitRunner.class) public class StringBasedMongoQueryUnitTests { - @Mock - MongoTemplate template; - @Mock - RepositoryMetadata metadata; - @Mock - EntityInformationCreator creator; - - MongoConverter converter = new SimpleMongoConverter(); + @Mock + MongoTemplate template; + @Mock + RepositoryMetadata metadata; + @Mock + EntityInformationCreator creator; - @Before - public void setUp() { - when(template.getConverter()).thenReturn(converter); - } + MongoConverter converter = new SimpleMongoConverter(); - @Test - public void bindsSimplePropertyCorrectly() throws Exception { + @Before + public void setUp() { + when(template.getConverter()).thenReturn(converter); + } - Method method = SampleRepository.class.getMethod("findByLastname", String.class); - MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, creator); - StringBasedMongoQuery mongoQuery = new StringBasedMongoQuery(queryMethod, template); - ConvertingParameterAccessor accesor = StubParameterAccessor.getAccessor(converter, "Matthews"); + @Test + public void bindsSimplePropertyCorrectly() throws Exception { - org.springframework.data.document.mongodb.query.Query query = mongoQuery.createQuery(accesor); - org.springframework.data.document.mongodb.query.Query reference = new BasicQuery("{'lastname' : 'Matthews'}"); + Method method = SampleRepository.class.getMethod("findByLastname", String.class); + MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, creator); + StringBasedMongoQuery mongoQuery = new StringBasedMongoQuery(queryMethod, template); + ConvertingParameterAccessor accesor = StubParameterAccessor.getAccessor(converter, "Matthews"); - assertThat(query.getQueryObject(), is(reference.getQueryObject())); - } - - @Test - public void bindsComplexPropertyCorrectly() throws Exception { + org.springframework.data.document.mongodb.query.Query query = mongoQuery.createQuery(accesor); + org.springframework.data.document.mongodb.query.Query reference = new BasicQuery("{'lastname' : 'Matthews'}"); - Method method = SampleRepository.class.getMethod("findByAddress", Address.class); - MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, creator); - StringBasedMongoQuery mongoQuery = new StringBasedMongoQuery(queryMethod, template); - - Address address = new Address("Foo", "0123", "Bar"); - ConvertingParameterAccessor accesor = StubParameterAccessor.getAccessor(converter, address); - - DBObject dbObject = new BasicDBObject(); - converter.write(address, dbObject); - - org.springframework.data.document.mongodb.query.Query query = mongoQuery.createQuery(accesor); - org.springframework.data.document.mongodb.query.Query reference = new BasicQuery(new BasicDBObject("address", dbObject)); + assertThat(query.getQueryObject(), is(reference.getQueryObject())); + } - assertThat(query.getQueryObject(), is(reference.getQueryObject())); - } + @Test + public void bindsComplexPropertyCorrectly() throws Exception { - private interface SampleRepository { + Method method = SampleRepository.class.getMethod("findByAddress", Address.class); + MongoQueryMethod queryMethod = new MongoQueryMethod(method, metadata, creator); + StringBasedMongoQuery mongoQuery = new StringBasedMongoQuery(queryMethod, template); - @Query("{ 'lastname' : ?0 }") - Person findByLastname(String lastname); - - @Query("{ 'address' : ?0 }") - Person findByAddress(Address address); - } + Address address = new Address("Foo", "0123", "Bar"); + ConvertingParameterAccessor accesor = StubParameterAccessor.getAccessor(converter, address); + + DBObject dbObject = new BasicDBObject(); + converter.write(address, dbObject); + + org.springframework.data.document.mongodb.query.Query query = mongoQuery.createQuery(accesor); + org.springframework.data.document.mongodb.query.Query reference = new BasicQuery(new BasicDBObject("address", + dbObject)); + + assertThat(query.getQueryObject(), is(reference.getQueryObject())); + } + + private interface SampleRepository { + + @Query("{ 'lastname' : ?0 }") + Person findByLastname(String lastname); + + @Query("{ 'address' : ?0 }") + Person findByAddress(Address address); + } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StubParameterAccessor.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StubParameterAccessor.java index 19dd6017f..996777d94 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StubParameterAccessor.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/StubParameterAccessor.java @@ -25,62 +25,61 @@ import org.springframework.data.repository.query.ParameterAccessor; /** * Simple {@link ParameterAccessor} that returns the given parameters unfiltered. - * + * * @author Oliver Gierke */ class StubParameterAccessor implements ParameterAccessor { - private final Object[] values; + private final Object[] values; - /** - * Creates a new {@link ConvertingParameterAccessor} backed by a {@link StubParameterAccessor} simply returning the - * given parameters converted but unfiltered. - * - * @param converter - * @param parameters - * @return - */ - public static ConvertingParameterAccessor getAccessor(MongoWriter converter, Object... parameters) { + /** + * Creates a new {@link ConvertingParameterAccessor} backed by a {@link StubParameterAccessor} simply returning the + * given parameters converted but unfiltered. + * + * @param converter + * @param parameters + * @return + */ + public static ConvertingParameterAccessor getAccessor(MongoWriter converter, Object... parameters) { - return new ConvertingParameterAccessor(converter, new StubParameterAccessor(parameters)); - } + return new ConvertingParameterAccessor(converter, new StubParameterAccessor(parameters)); + } + public StubParameterAccessor(Object... values) { + this.values = values; + } - public StubParameterAccessor(Object... values) { - this.values = values; - } + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.query.ParameterAccessor#getPageable() + */ + public Pageable getPageable() { + return null; + } - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.query.ParameterAccessor#getPageable() - */ - public Pageable getPageable() { - return null; - } + /* (non-Javadoc) + * @see org.springframework.data.repository.query.ParameterAccessor#getBindableParameter(int) + */ + public Object getBindableValue(int index) { + return values[index]; + } - /* (non-Javadoc) - * @see org.springframework.data.repository.query.ParameterAccessor#getBindableParameter(int) - */ - public Object getBindableValue(int index) { - return values[index]; - } + /* + * (non-Javadoc) + * + * @see org.springframework.data.repository.query.ParameterAccessor#getSort() + */ + public Sort getSort() { + return null; + } - /* - * (non-Javadoc) - * - * @see org.springframework.data.repository.query.ParameterAccessor#getSort() - */ - public Sort getSort() { - return null; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Iterable#iterator() - */ - public Iterator iterator() { - return Arrays.asList(values).iterator(); - } + /* + * (non-Javadoc) + * + * @see java.lang.Iterable#iterator() + */ + public Iterator iterator() { + return Arrays.asList(values).iterator(); + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/config/MongoNamespaceIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/config/MongoNamespaceIntegrationTests.java index 5bfbb8d7c..2870d6ad7 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/config/MongoNamespaceIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/document/mongodb/repository/config/MongoNamespaceIntegrationTests.java @@ -10,24 +10,21 @@ import org.springframework.core.io.ClassPathResource; import org.springframework.data.document.mongodb.repository.AbstractPersonRepositoryIntegrationTests; import org.springframework.test.context.ContextConfiguration; - /** - * Test class using the namespace configuration to set up the repository - * instance. - * + * Test class using the namespace configuration to set up the repository instance. + * * @author Oliver Gierke */ @ContextConfiguration -public class MongoNamespaceIntegrationTests extends - AbstractPersonRepositoryIntegrationTests { +public class MongoNamespaceIntegrationTests extends AbstractPersonRepositoryIntegrationTests { - - @Test - public void assertDefaultMappingContextIsWired() { - - XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("MongoNamespaceIntegrationTests-context.xml", getClass())); - BeanDefinition definition = factory.getBeanDefinition("personRepository"); - assertThat(definition, is(notNullValue())); - assertThat(definition.getPropertyValues().getPropertyValue("mappingContext"), is(notNullValue())); - } + @Test + public void assertDefaultMappingContextIsWired() { + + XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("MongoNamespaceIntegrationTests-context.xml", + getClass())); + BeanDefinition definition = factory.getBeanDefinition("personRepository"); + assertThat(definition, is(notNullValue())); + assertThat(definition.getPropertyValues().getPropertyValue("mappingContext"), is(notNullValue())); + } }