From 72f461ae30fffca7db314e4f7bc253ddc9eb04f6 Mon Sep 17 00:00:00 2001 From: Mark Paluch Date: Wed, 24 Jan 2018 12:57:54 +0100 Subject: [PATCH] DATAMONGO-1858 - Fix line endings to LF. --- .../crossstore/MongoChangeSetPersister.java | 394 ++++++------ .../config/AbstractMongoConfiguration.java | 594 +++++++++--------- .../data/mongodb/config/MongoJmxParser.java | 138 ++-- .../mongodb/config/MongoParsingUtils.java | 414 ++++++------ .../data/mongodb/core/CollectionCallback.java | 52 +- .../data/mongodb/core/CollectionOptions.java | 140 ++--- .../data/mongodb/core/DbCallback.java | 50 +- .../data/mongodb/core/MongoAdmin.java | 202 +++--- .../mongodb/core/MongoAdminOperations.java | 68 +- .../mongodb/core/SimpleMongoDbFactory.java | 470 +++++++------- .../mongodb/core/convert/MongoConverter.java | 86 +-- .../mongodb/core/convert/MongoWriter.java | 126 ++-- .../data/mongodb/monitor/AbstractMonitor.java | 144 ++--- .../data/mongodb/monitor/AssertMetrics.java | 134 ++-- .../monitor/BackgroundFlushingMetrics.java | 150 ++--- .../mongodb/monitor/BtreeIndexCounters.java | 148 ++--- .../mongodb/monitor/ConnectionMetrics.java | 106 ++-- .../mongodb/monitor/GlobalLockMetrics.java | 154 ++--- .../data/mongodb/monitor/MemoryMetrics.java | 136 ++-- .../mongodb/monitor/OperationCounters.java | 140 ++--- .../data/mongodb/monitor/ServerInfo.java | 152 ++--- .../config/MongoNamespaceReplicaSetTests.java | 212 +++---- .../mongodb/config/MongoNamespaceTests.java | 506 +++++++-------- .../core/MongoAdminIntegrationTests.java | 116 ++-- .../data/mongodb/core/PersonExample.java | 192 +++--- .../mongodb/core/PersonExampleAppConfig.java | 82 +-- .../data/mongodb/core/Portfolio.java | 146 ++--- .../data/mongodb/core/Trade.java | 120 ++-- .../data/mongodb/core/User.java | 142 ++--- .../data/mongodb/core/Venue.java | 132 ++-- .../core/geo/GeoSpatial2DSphereTests.java | 178 +++--- .../mongodb/core/geo/GeoSpatial2DTests.java | 158 ++--- .../core/mapping/GeoIndexedAppConfig.java | 100 +-- .../mongodb/core/query/CriteriaTests.java | 438 ++++++------- .../mongodb/core/query/IndexUnitTests.java | 204 +++--- .../data/mongodb/core/query/SortTests.java | 100 +-- .../monitor/MongoMonitorIntegrationTests.java | 142 ++--- .../src/test/resources/META-INF/beans.xml | 12 +- 38 files changed, 3489 insertions(+), 3489 deletions(-) diff --git a/spring-data-mongodb-cross-store/src/main/java/org/springframework/data/mongodb/crossstore/MongoChangeSetPersister.java b/spring-data-mongodb-cross-store/src/main/java/org/springframework/data/mongodb/crossstore/MongoChangeSetPersister.java index e1c0c358d..bb0e6bcd2 100644 --- a/spring-data-mongodb-cross-store/src/main/java/org/springframework/data/mongodb/crossstore/MongoChangeSetPersister.java +++ b/spring-data-mongodb-cross-store/src/main/java/org/springframework/data/mongodb/crossstore/MongoChangeSetPersister.java @@ -1,197 +1,197 @@ -/* - * Copyright 2011-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.crossstore; - -import javax.persistence.EntityManagerFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.DataAccessResourceFailureException; -import org.springframework.dao.DataIntegrityViolationException; -import org.springframework.data.crossstore.ChangeSet; -import org.springframework.data.crossstore.ChangeSetBacked; -import org.springframework.data.crossstore.ChangeSetPersister; -import org.springframework.data.mongodb.core.CollectionCallback; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.util.ClassUtils; - -import com.mongodb.BasicDBObject; -import com.mongodb.DBCollection; -import com.mongodb.DBObject; -import com.mongodb.MongoException; - -/** - * @author Thomas Risberg - * @author Oliver Gierke - * @author Alex Vengrovsk - * @author Mark Paluch - */ -public class MongoChangeSetPersister implements ChangeSetPersister { - - private static final String ENTITY_CLASS = "_entity_class"; - private static final String ENTITY_ID = "_entity_id"; - private static final String ENTITY_FIELD_NAME = "_entity_field_name"; - private static final String ENTITY_FIELD_CLASS = "_entity_field_class"; - - private final Logger log = LoggerFactory.getLogger(getClass()); - - private MongoTemplate mongoTemplate; - private EntityManagerFactory entityManagerFactory; - - public void setMongoTemplate(MongoTemplate mongoTemplate) { - this.mongoTemplate = mongoTemplate; - } - - public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { - this.entityManagerFactory = entityManagerFactory; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentState(java.lang.Class, java.lang.Object, org.springframework.data.crossstore.ChangeSet) - */ - public void getPersistentState(Class entityClass, Object id, final ChangeSet changeSet) - throws DataAccessException, NotFoundException { - - if (id == null) { - log.debug("Unable to load MongoDB data for null id"); - return; - } - - String collName = getCollectionNameForEntity(entityClass); - - final DBObject dbk = new BasicDBObject(); - dbk.put(ENTITY_ID, id); - dbk.put(ENTITY_CLASS, entityClass.getName()); - if (log.isDebugEnabled()) { - log.debug("Loading MongoDB data for {}", dbk); - } - mongoTemplate.execute(collName, new CollectionCallback() { - public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { - for (DBObject dbo : collection.find(dbk)) { - String key = (String) dbo.get(ENTITY_FIELD_NAME); - if (log.isDebugEnabled()) { - log.debug("Processing key: {}", key); - } - if (!changeSet.getValues().containsKey(key)) { - String className = (String) dbo.get(ENTITY_FIELD_CLASS); - if (className == null) { - throw new DataIntegrityViolationException( - "Unble to convert property " + key + ": Invalid metadata, " + ENTITY_FIELD_CLASS + " not available"); - } - Class clazz = ClassUtils.resolveClassName(className, ClassUtils.getDefaultClassLoader()); - Object value = mongoTemplate.getConverter().read(clazz, dbo); - if (log.isDebugEnabled()) { - log.debug("Adding to ChangeSet: {}", key); - } - changeSet.set(key, value); - } - } - return null; - } - }); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentId(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet) - */ - public Object getPersistentId(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException { - if (log.isDebugEnabled()) { - log.debug("getPersistentId called on {}", entity); - } - if (entityManagerFactory == null) { - throw new DataAccessResourceFailureException("EntityManagerFactory cannot be null"); - } - - return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.crossstore.ChangeSetPersister#persistState(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet) - */ - public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException { - if (cs == null) { - log.debug("Flush: changeset was null, nothing to flush."); - return 0L; - } - - if (log.isDebugEnabled()) { - log.debug("Flush: changeset: {}", cs.getValues()); - } - - String collName = getCollectionNameForEntity(entity.getClass()); - if (mongoTemplate.getCollection(collName) == null) { - mongoTemplate.createCollection(collName); - } - - for (String key : cs.getValues().keySet()) { - if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) { - Object value = cs.getValues().get(key); - final DBObject dbQuery = new BasicDBObject(); - dbQuery.put(ENTITY_ID, getPersistentId(entity, cs)); - dbQuery.put(ENTITY_CLASS, entity.getClass().getName()); - dbQuery.put(ENTITY_FIELD_NAME, key); - DBObject dbId = mongoTemplate.execute(collName, new CollectionCallback() { - public DBObject doInCollection(DBCollection collection) throws MongoException, DataAccessException { - return collection.findOne(dbQuery); - } - }); - if (value == null) { - if (log.isDebugEnabled()) { - log.debug("Flush: removing: {}", dbQuery); - } - mongoTemplate.execute(collName, new CollectionCallback() { - public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { - collection.remove(dbQuery); - return null; - } - }); - } else { - final DBObject dbDoc = new BasicDBObject(); - dbDoc.putAll(dbQuery); - if (log.isDebugEnabled()) { - log.debug("Flush: saving: {}", dbQuery); - } - mongoTemplate.getConverter().write(value, dbDoc); - dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName()); - if (dbId != null) { - dbDoc.put("_id", dbId.get("_id")); - } - mongoTemplate.execute(collName, new CollectionCallback() { - public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { - collection.save(dbDoc); - return null; - } - }); - } - } - } - return 0L; - } - - /** - * Returns the collection the given entity type shall be persisted to. - * - * @param entityClass must not be {@literal null}. - * @return - */ - private String getCollectionNameForEntity(Class entityClass) { - return mongoTemplate.getCollectionName(entityClass); - } -} +/* + * Copyright 2011-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.crossstore; + +import javax.persistence.EntityManagerFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.DataAccessResourceFailureException; +import org.springframework.dao.DataIntegrityViolationException; +import org.springframework.data.crossstore.ChangeSet; +import org.springframework.data.crossstore.ChangeSetBacked; +import org.springframework.data.crossstore.ChangeSetPersister; +import org.springframework.data.mongodb.core.CollectionCallback; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.util.ClassUtils; + +import com.mongodb.BasicDBObject; +import com.mongodb.DBCollection; +import com.mongodb.DBObject; +import com.mongodb.MongoException; + +/** + * @author Thomas Risberg + * @author Oliver Gierke + * @author Alex Vengrovsk + * @author Mark Paluch + */ +public class MongoChangeSetPersister implements ChangeSetPersister { + + private static final String ENTITY_CLASS = "_entity_class"; + private static final String ENTITY_ID = "_entity_id"; + private static final String ENTITY_FIELD_NAME = "_entity_field_name"; + private static final String ENTITY_FIELD_CLASS = "_entity_field_class"; + + private final Logger log = LoggerFactory.getLogger(getClass()); + + private MongoTemplate mongoTemplate; + private EntityManagerFactory entityManagerFactory; + + public void setMongoTemplate(MongoTemplate mongoTemplate) { + this.mongoTemplate = mongoTemplate; + } + + public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) { + this.entityManagerFactory = entityManagerFactory; + } + + /* + * (non-Javadoc) + * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentState(java.lang.Class, java.lang.Object, org.springframework.data.crossstore.ChangeSet) + */ + public void getPersistentState(Class entityClass, Object id, final ChangeSet changeSet) + throws DataAccessException, NotFoundException { + + if (id == null) { + log.debug("Unable to load MongoDB data for null id"); + return; + } + + String collName = getCollectionNameForEntity(entityClass); + + final DBObject dbk = new BasicDBObject(); + dbk.put(ENTITY_ID, id); + dbk.put(ENTITY_CLASS, entityClass.getName()); + if (log.isDebugEnabled()) { + log.debug("Loading MongoDB data for {}", dbk); + } + mongoTemplate.execute(collName, new CollectionCallback() { + public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { + for (DBObject dbo : collection.find(dbk)) { + String key = (String) dbo.get(ENTITY_FIELD_NAME); + if (log.isDebugEnabled()) { + log.debug("Processing key: {}", key); + } + if (!changeSet.getValues().containsKey(key)) { + String className = (String) dbo.get(ENTITY_FIELD_CLASS); + if (className == null) { + throw new DataIntegrityViolationException( + "Unble to convert property " + key + ": Invalid metadata, " + ENTITY_FIELD_CLASS + " not available"); + } + Class clazz = ClassUtils.resolveClassName(className, ClassUtils.getDefaultClassLoader()); + Object value = mongoTemplate.getConverter().read(clazz, dbo); + if (log.isDebugEnabled()) { + log.debug("Adding to ChangeSet: {}", key); + } + changeSet.set(key, value); + } + } + return null; + } + }); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.crossstore.ChangeSetPersister#getPersistentId(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet) + */ + public Object getPersistentId(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException { + if (log.isDebugEnabled()) { + log.debug("getPersistentId called on {}", entity); + } + if (entityManagerFactory == null) { + throw new DataAccessResourceFailureException("EntityManagerFactory cannot be null"); + } + + return entityManagerFactory.getPersistenceUnitUtil().getIdentifier(entity); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.crossstore.ChangeSetPersister#persistState(org.springframework.data.crossstore.ChangeSetBacked, org.springframework.data.crossstore.ChangeSet) + */ + public Object persistState(ChangeSetBacked entity, ChangeSet cs) throws DataAccessException { + if (cs == null) { + log.debug("Flush: changeset was null, nothing to flush."); + return 0L; + } + + if (log.isDebugEnabled()) { + log.debug("Flush: changeset: {}", cs.getValues()); + } + + String collName = getCollectionNameForEntity(entity.getClass()); + if (mongoTemplate.getCollection(collName) == null) { + mongoTemplate.createCollection(collName); + } + + for (String key : cs.getValues().keySet()) { + if (key != null && !key.startsWith("_") && !key.equals(ChangeSetPersister.ID_KEY)) { + Object value = cs.getValues().get(key); + final DBObject dbQuery = new BasicDBObject(); + dbQuery.put(ENTITY_ID, getPersistentId(entity, cs)); + dbQuery.put(ENTITY_CLASS, entity.getClass().getName()); + dbQuery.put(ENTITY_FIELD_NAME, key); + DBObject dbId = mongoTemplate.execute(collName, new CollectionCallback() { + public DBObject doInCollection(DBCollection collection) throws MongoException, DataAccessException { + return collection.findOne(dbQuery); + } + }); + if (value == null) { + if (log.isDebugEnabled()) { + log.debug("Flush: removing: {}", dbQuery); + } + mongoTemplate.execute(collName, new CollectionCallback() { + public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { + collection.remove(dbQuery); + return null; + } + }); + } else { + final DBObject dbDoc = new BasicDBObject(); + dbDoc.putAll(dbQuery); + if (log.isDebugEnabled()) { + log.debug("Flush: saving: {}", dbQuery); + } + mongoTemplate.getConverter().write(value, dbDoc); + dbDoc.put(ENTITY_FIELD_CLASS, value.getClass().getName()); + if (dbId != null) { + dbDoc.put("_id", dbId.get("_id")); + } + mongoTemplate.execute(collName, new CollectionCallback() { + public Object doInCollection(DBCollection collection) throws MongoException, DataAccessException { + collection.save(dbDoc); + return null; + } + }); + } + } + } + return 0L; + } + + /** + * Returns the collection the given entity type shall be persisted to. + * + * @param entityClass must not be {@literal null}. + * @return + */ + private String getCollectionNameForEntity(Class entityClass) { + return mongoTemplate.getCollectionName(entityClass); + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java index e1e92eee5..ec77d61c6 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/AbstractMongoConfiguration.java @@ -1,297 +1,297 @@ -/* - * Copyright 2011-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.config; - -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.convert.converter.Converter; -import org.springframework.core.type.filter.AnnotationTypeFilter; -import org.springframework.data.annotation.Persistent; -import org.springframework.data.authentication.UserCredentials; -import org.springframework.data.mapping.context.MappingContextIsNewStrategyFactory; -import org.springframework.data.mapping.model.CamelCaseAbbreviatingFieldNamingStrategy; -import org.springframework.data.mapping.model.FieldNamingStrategy; -import org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy; -import org.springframework.data.mongodb.MongoDbFactory; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.core.SimpleMongoDbFactory; -import org.springframework.data.mongodb.core.convert.CustomConversions; -import org.springframework.data.mongodb.core.convert.DbRefResolver; -import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; -import org.springframework.data.mongodb.core.convert.MappingMongoConverter; -import org.springframework.data.mongodb.core.mapping.Document; -import org.springframework.data.mongodb.core.mapping.MongoMappingContext; -import org.springframework.data.support.CachingIsNewStrategyFactory; -import org.springframework.data.support.IsNewStrategyFactory; -import org.springframework.util.ClassUtils; -import org.springframework.util.StringUtils; - -import com.mongodb.Mongo; -import com.mongodb.MongoClient; - -/** - * Base class for Spring Data MongoDB configuration using JavaConfig. - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Thomas Darimont - * @author Ryan Tenney - * @author Christoph Strobl - */ -@Configuration -public abstract class AbstractMongoConfiguration { - - /** - * Return the name of the database to connect to. - * - * @return must not be {@literal null}. - */ - protected abstract String getDatabaseName(); - - /** - * Return the name of the authentication database to use. Defaults to {@literal null} and will turn into the value - * returned by {@link #getDatabaseName()} later on effectively. - * - * @return - * @deprecated since 1.7. {@link MongoClient} should hold authentication data within - * {@link MongoClient#getCredentialsList()} - */ - @Deprecated - protected String getAuthenticationDatabaseName() { - return null; - } - - /** - * Return the {@link Mongo} instance to connect to. Annotate with {@link Bean} in case you want to expose a - * {@link Mongo} instance to the {@link org.springframework.context.ApplicationContext}. - * - * @return - * @throws Exception - */ - public abstract Mongo mongo() throws Exception; - - /** - * Creates a {@link MongoTemplate}. - * - * @return - * @throws Exception - */ - @Bean - public MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()); - } - - /** - * Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link Mongo} instance - * configured in {@link #mongo()}. - * - * @see #mongo() - * @see #mongoTemplate() - * @return - * @throws Exception - */ - @Bean - public MongoDbFactory mongoDbFactory() throws Exception { - return new SimpleMongoDbFactory(mongo(), getDatabaseName(), getUserCredentials(), getAuthenticationDatabaseName()); - } - - /** - * Return the base package to scan for mapped {@link Document}s. Will return the package name of the configuration - * class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending - * {@link AbstractMongoConfiguration} the base package will be considered {@code com.acme} unless the method is - * overridden to implement alternate behavior. - * - * @return the base package to scan for mapped {@link Document} classes or {@literal null} to not enable scanning for - * entities. - * @deprecated use {@link #getMappingBasePackages()} instead. - */ - @Deprecated - protected String getMappingBasePackage() { - - Package mappingBasePackage = getClass().getPackage(); - return mappingBasePackage == null ? null : mappingBasePackage.getName(); - } - - /** - * Returns the base packages to scan for MongoDB mapped entities at startup. Will return the package name of the - * configuration class' (the concrete class, not this one here) by default. So if you have a - * {@code com.acme.AppConfig} extending {@link AbstractMongoConfiguration} the base package will be considered - * {@code com.acme} unless the method is overridden to implement alternate behavior. - * - * @return the base packages to scan for mapped {@link Document} classes or an empty collection to not enable scanning - * for entities. - * @since 1.10 - */ - protected Collection getMappingBasePackages() { - return Collections.singleton(getMappingBasePackage()); - } - - /** - * Return {@link UserCredentials} to be used when connecting to the MongoDB instance or {@literal null} if none shall - * be used. - * - * @return - * @deprecated since 1.7. {@link MongoClient} should hold authentication data within - * {@link MongoClient#getCredentialsList()} - */ - @Deprecated - protected UserCredentials getUserCredentials() { - return null; - } - - /** - * Creates a {@link MongoMappingContext} equipped with entity classes scanned from the mapping base package. - * - * @see #getMappingBasePackage() - * @return - * @throws ClassNotFoundException - */ - @Bean - public MongoMappingContext mongoMappingContext() throws ClassNotFoundException { - - MongoMappingContext mappingContext = new MongoMappingContext(); - mappingContext.setInitialEntitySet(getInitialEntitySet()); - mappingContext.setSimpleTypeHolder(customConversions().getSimpleTypeHolder()); - mappingContext.setFieldNamingStrategy(fieldNamingStrategy()); - - return mappingContext; - } - - /** - * Returns a {@link MappingContextIsNewStrategyFactory} wrapped into a {@link CachingIsNewStrategyFactory}. - * - * @return - * @throws ClassNotFoundException - */ - @Bean - public IsNewStrategyFactory isNewStrategyFactory() throws ClassNotFoundException { - return new CachingIsNewStrategyFactory(new MappingContextIsNewStrategyFactory(mongoMappingContext())); - } - - /** - * Register custom {@link Converter}s in a {@link CustomConversions} object if required. These - * {@link CustomConversions} will be registered with the {@link #mappingMongoConverter()} and - * {@link #mongoMappingContext()}. Returns an empty {@link CustomConversions} instance by default. - * - * @return must not be {@literal null}. - */ - @Bean - public CustomConversions customConversions() { - return new CustomConversions(Collections.emptyList()); - } - - /** - * Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and - * {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied. - * - * @see #customConversions() - * @see #mongoMappingContext() - * @see #mongoDbFactory() - * @return - * @throws Exception - */ - @Bean - public MappingMongoConverter mappingMongoConverter() throws Exception { - - DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory()); - MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext()); - converter.setCustomConversions(customConversions()); - - return converter; - } - - /** - * Scans the mapping base package for classes annotated with {@link Document}. By default, it scans for entities in - * all packages returned by {@link #getMappingBasePackages()}. - * - * @see #getMappingBasePackages() - * @return - * @throws ClassNotFoundException - */ - protected Set> getInitialEntitySet() throws ClassNotFoundException { - - Set> initialEntitySet = new HashSet>(); - - for (String basePackage : getMappingBasePackages()) { - initialEntitySet.addAll(scanForEntities(basePackage)); - } - - return initialEntitySet; - } - - /** - * Scans the given base package for entities, i.e. MongoDB specific types annotated with {@link Document} and - * {@link Persistent}. - * - * @param basePackage must not be {@literal null}. - * @return - * @throws ClassNotFoundException - * @since 1.10 - */ - protected Set> scanForEntities(String basePackage) throws ClassNotFoundException { - - if (!StringUtils.hasText(basePackage)) { - return Collections.emptySet(); - } - - Set> initialEntitySet = new HashSet>(); - - if (StringUtils.hasText(basePackage)) { - - ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( - false); - componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class)); - componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class)); - - for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) { - - initialEntitySet - .add(ClassUtils.forName(candidate.getBeanClassName(), AbstractMongoConfiguration.class.getClassLoader())); - } - } - - return initialEntitySet; - } - - /** - * Configures whether to abbreviate field names for domain objects by configuring a - * {@link CamelCaseAbbreviatingFieldNamingStrategy} on the {@link MongoMappingContext} instance created. For advanced - * customization needs, consider overriding {@link #mappingMongoConverter()}. - * - * @return - */ - protected boolean abbreviateFieldNames() { - return false; - } - - /** - * Configures a {@link FieldNamingStrategy} on the {@link MongoMappingContext} instance created. - * - * @return - * @since 1.5 - */ - protected FieldNamingStrategy fieldNamingStrategy() { - return abbreviateFieldNames() ? new CamelCaseAbbreviatingFieldNamingStrategy() - : PropertyNameFieldNamingStrategy.INSTANCE; - } -} +/* + * Copyright 2011-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.config; + +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.convert.converter.Converter; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.data.annotation.Persistent; +import org.springframework.data.authentication.UserCredentials; +import org.springframework.data.mapping.context.MappingContextIsNewStrategyFactory; +import org.springframework.data.mapping.model.CamelCaseAbbreviatingFieldNamingStrategy; +import org.springframework.data.mapping.model.FieldNamingStrategy; +import org.springframework.data.mapping.model.PropertyNameFieldNamingStrategy; +import org.springframework.data.mongodb.MongoDbFactory; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.SimpleMongoDbFactory; +import org.springframework.data.mongodb.core.convert.CustomConversions; +import org.springframework.data.mongodb.core.convert.DbRefResolver; +import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver; +import org.springframework.data.mongodb.core.convert.MappingMongoConverter; +import org.springframework.data.mongodb.core.mapping.Document; +import org.springframework.data.mongodb.core.mapping.MongoMappingContext; +import org.springframework.data.support.CachingIsNewStrategyFactory; +import org.springframework.data.support.IsNewStrategyFactory; +import org.springframework.util.ClassUtils; +import org.springframework.util.StringUtils; + +import com.mongodb.Mongo; +import com.mongodb.MongoClient; + +/** + * Base class for Spring Data MongoDB configuration using JavaConfig. + * + * @author Mark Pollack + * @author Oliver Gierke + * @author Thomas Darimont + * @author Ryan Tenney + * @author Christoph Strobl + */ +@Configuration +public abstract class AbstractMongoConfiguration { + + /** + * Return the name of the database to connect to. + * + * @return must not be {@literal null}. + */ + protected abstract String getDatabaseName(); + + /** + * Return the name of the authentication database to use. Defaults to {@literal null} and will turn into the value + * returned by {@link #getDatabaseName()} later on effectively. + * + * @return + * @deprecated since 1.7. {@link MongoClient} should hold authentication data within + * {@link MongoClient#getCredentialsList()} + */ + @Deprecated + protected String getAuthenticationDatabaseName() { + return null; + } + + /** + * Return the {@link Mongo} instance to connect to. Annotate with {@link Bean} in case you want to expose a + * {@link Mongo} instance to the {@link org.springframework.context.ApplicationContext}. + * + * @return + * @throws Exception + */ + public abstract Mongo mongo() throws Exception; + + /** + * Creates a {@link MongoTemplate}. + * + * @return + * @throws Exception + */ + @Bean + public MongoTemplate mongoTemplate() throws Exception { + return new MongoTemplate(mongoDbFactory(), mappingMongoConverter()); + } + + /** + * Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link Mongo} instance + * configured in {@link #mongo()}. + * + * @see #mongo() + * @see #mongoTemplate() + * @return + * @throws Exception + */ + @Bean + public MongoDbFactory mongoDbFactory() throws Exception { + return new SimpleMongoDbFactory(mongo(), getDatabaseName(), getUserCredentials(), getAuthenticationDatabaseName()); + } + + /** + * Return the base package to scan for mapped {@link Document}s. Will return the package name of the configuration + * class' (the concrete class, not this one here) by default. So if you have a {@code com.acme.AppConfig} extending + * {@link AbstractMongoConfiguration} the base package will be considered {@code com.acme} unless the method is + * overridden to implement alternate behavior. + * + * @return the base package to scan for mapped {@link Document} classes or {@literal null} to not enable scanning for + * entities. + * @deprecated use {@link #getMappingBasePackages()} instead. + */ + @Deprecated + protected String getMappingBasePackage() { + + Package mappingBasePackage = getClass().getPackage(); + return mappingBasePackage == null ? null : mappingBasePackage.getName(); + } + + /** + * Returns the base packages to scan for MongoDB mapped entities at startup. Will return the package name of the + * configuration class' (the concrete class, not this one here) by default. So if you have a + * {@code com.acme.AppConfig} extending {@link AbstractMongoConfiguration} the base package will be considered + * {@code com.acme} unless the method is overridden to implement alternate behavior. + * + * @return the base packages to scan for mapped {@link Document} classes or an empty collection to not enable scanning + * for entities. + * @since 1.10 + */ + protected Collection getMappingBasePackages() { + return Collections.singleton(getMappingBasePackage()); + } + + /** + * Return {@link UserCredentials} to be used when connecting to the MongoDB instance or {@literal null} if none shall + * be used. + * + * @return + * @deprecated since 1.7. {@link MongoClient} should hold authentication data within + * {@link MongoClient#getCredentialsList()} + */ + @Deprecated + protected UserCredentials getUserCredentials() { + return null; + } + + /** + * Creates a {@link MongoMappingContext} equipped with entity classes scanned from the mapping base package. + * + * @see #getMappingBasePackage() + * @return + * @throws ClassNotFoundException + */ + @Bean + public MongoMappingContext mongoMappingContext() throws ClassNotFoundException { + + MongoMappingContext mappingContext = new MongoMappingContext(); + mappingContext.setInitialEntitySet(getInitialEntitySet()); + mappingContext.setSimpleTypeHolder(customConversions().getSimpleTypeHolder()); + mappingContext.setFieldNamingStrategy(fieldNamingStrategy()); + + return mappingContext; + } + + /** + * Returns a {@link MappingContextIsNewStrategyFactory} wrapped into a {@link CachingIsNewStrategyFactory}. + * + * @return + * @throws ClassNotFoundException + */ + @Bean + public IsNewStrategyFactory isNewStrategyFactory() throws ClassNotFoundException { + return new CachingIsNewStrategyFactory(new MappingContextIsNewStrategyFactory(mongoMappingContext())); + } + + /** + * Register custom {@link Converter}s in a {@link CustomConversions} object if required. These + * {@link CustomConversions} will be registered with the {@link #mappingMongoConverter()} and + * {@link #mongoMappingContext()}. Returns an empty {@link CustomConversions} instance by default. + * + * @return must not be {@literal null}. + */ + @Bean + public CustomConversions customConversions() { + return new CustomConversions(Collections.emptyList()); + } + + /** + * Creates a {@link MappingMongoConverter} using the configured {@link #mongoDbFactory()} and + * {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied. + * + * @see #customConversions() + * @see #mongoMappingContext() + * @see #mongoDbFactory() + * @return + * @throws Exception + */ + @Bean + public MappingMongoConverter mappingMongoConverter() throws Exception { + + DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory()); + MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, mongoMappingContext()); + converter.setCustomConversions(customConversions()); + + return converter; + } + + /** + * Scans the mapping base package for classes annotated with {@link Document}. By default, it scans for entities in + * all packages returned by {@link #getMappingBasePackages()}. + * + * @see #getMappingBasePackages() + * @return + * @throws ClassNotFoundException + */ + protected Set> getInitialEntitySet() throws ClassNotFoundException { + + Set> initialEntitySet = new HashSet>(); + + for (String basePackage : getMappingBasePackages()) { + initialEntitySet.addAll(scanForEntities(basePackage)); + } + + return initialEntitySet; + } + + /** + * Scans the given base package for entities, i.e. MongoDB specific types annotated with {@link Document} and + * {@link Persistent}. + * + * @param basePackage must not be {@literal null}. + * @return + * @throws ClassNotFoundException + * @since 1.10 + */ + protected Set> scanForEntities(String basePackage) throws ClassNotFoundException { + + if (!StringUtils.hasText(basePackage)) { + return Collections.emptySet(); + } + + Set> initialEntitySet = new HashSet>(); + + if (StringUtils.hasText(basePackage)) { + + ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider( + false); + componentProvider.addIncludeFilter(new AnnotationTypeFilter(Document.class)); + componentProvider.addIncludeFilter(new AnnotationTypeFilter(Persistent.class)); + + for (BeanDefinition candidate : componentProvider.findCandidateComponents(basePackage)) { + + initialEntitySet + .add(ClassUtils.forName(candidate.getBeanClassName(), AbstractMongoConfiguration.class.getClassLoader())); + } + } + + return initialEntitySet; + } + + /** + * Configures whether to abbreviate field names for domain objects by configuring a + * {@link CamelCaseAbbreviatingFieldNamingStrategy} on the {@link MongoMappingContext} instance created. For advanced + * customization needs, consider overriding {@link #mappingMongoConverter()}. + * + * @return + */ + protected boolean abbreviateFieldNames() { + return false; + } + + /** + * Configures a {@link FieldNamingStrategy} on the {@link MongoMappingContext} instance created. + * + * @return + * @since 1.5 + */ + protected FieldNamingStrategy fieldNamingStrategy() { + return abbreviateFieldNames() ? new CamelCaseAbbreviatingFieldNamingStrategy() + : PropertyNameFieldNamingStrategy.INSTANCE; + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoJmxParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoJmxParser.java index f32a16d54..da8ef90d4 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoJmxParser.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoJmxParser.java @@ -1,69 +1,69 @@ -/* - * Copyright 2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.config; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.parsing.BeanComponentDefinition; -import org.springframework.beans.factory.parsing.CompositeComponentDefinition; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.xml.BeanDefinitionParser; -import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.data.mongodb.core.MongoAdmin; -import org.springframework.data.mongodb.monitor.*; -import org.springframework.util.StringUtils; -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; - } - - protected void registerJmxComponents(String mongoRefName, Element element, ParserContext parserContext) { - Object eleSource = parserContext.extractSource(element); - - 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); - - 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)); - } - -} +/* + * Copyright 2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.config; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.parsing.BeanComponentDefinition; +import org.springframework.beans.factory.parsing.CompositeComponentDefinition; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.beans.factory.xml.ParserContext; +import org.springframework.data.mongodb.core.MongoAdmin; +import org.springframework.data.mongodb.monitor.*; +import org.springframework.util.StringUtils; +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; + } + + protected void registerJmxComponents(String mongoRefName, Element element, ParserContext parserContext) { + Object eleSource = parserContext.extractSource(element); + + 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); + + 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)); + } + +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java index f794fd901..7d8fcf5d8 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParsingUtils.java @@ -1,207 +1,207 @@ -/* - * Copyright 2011-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.config; - -import static org.springframework.data.config.ParsingUtils.*; - -import java.util.Map; - -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.CustomEditorConfigurer; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.ManagedMap; -import org.springframework.beans.factory.xml.BeanDefinitionParser; -import org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean; -import org.springframework.data.mongodb.core.MongoOptionsFactoryBean; -import org.springframework.util.xml.DomUtils; -import org.w3c.dom.Element; - -/** - * Utility methods for {@link BeanDefinitionParser} implementations for MongoDB. - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Thomas Darimont - * @author Christoph Strobl - */ -@SuppressWarnings("deprecation") -abstract class MongoParsingUtils { - - private MongoParsingUtils() {} - - /** - * Parses the mongo replica-set element. - * - * @param parserContext the parser context - * @param element the mongo element - * @param mongoBuilder the bean definition builder to populate - * @return - */ - static void parseReplicaSet(Element element, BeanDefinitionBuilder mongoBuilder) { - setPropertyValue(mongoBuilder, element, "replica-set", "replicaSetSeeds"); - } - - /** - * Parses the {@code mongo:options} sub-element. Populates the given attribute factory with the proper attributes. - * - * @return true if parsing actually occured, {@literal false} otherwise - */ - static boolean parseMongoOptions(Element element, BeanDefinitionBuilder mongoBuilder) { - - Element optionsElement = DomUtils.getChildElementByTagName(element, "options"); - - if (optionsElement == null) { - return false; - } - - BeanDefinitionBuilder optionsDefBuilder = BeanDefinitionBuilder - .genericBeanDefinition(MongoOptionsFactoryBean.class); - - setPropertyValue(optionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost"); - setPropertyValue(optionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier", - "threadsAllowedToBlockForConnectionMultiplier"); - setPropertyValue(optionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime"); - setPropertyValue(optionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout"); - setPropertyValue(optionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout"); - setPropertyValue(optionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive"); - setPropertyValue(optionsDefBuilder, optionsElement, "auto-connect-retry", "autoConnectRetry"); - setPropertyValue(optionsDefBuilder, optionsElement, "max-auto-connect-retry-time", "maxAutoConnectRetryTime"); - setPropertyValue(optionsDefBuilder, optionsElement, "write-number", "writeNumber"); - setPropertyValue(optionsDefBuilder, optionsElement, "write-timeout", "writeTimeout"); - setPropertyValue(optionsDefBuilder, optionsElement, "write-fsync", "writeFsync"); - setPropertyValue(optionsDefBuilder, optionsElement, "slave-ok", "slaveOk"); - setPropertyValue(optionsDefBuilder, optionsElement, "ssl", "ssl"); - setPropertyReference(optionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory"); - - mongoBuilder.addPropertyValue("mongoOptions", optionsDefBuilder.getBeanDefinition()); - return true; - } - - /** - * Parses the {@code mongo:client-options} sub-element. Populates the given attribute factory with the proper - * attributes. - * - * @param element must not be {@literal null}. - * @param mongoClientBuilder must not be {@literal null}. - * @return - * @since 1.7 - */ - public static boolean parseMongoClientOptions(Element element, BeanDefinitionBuilder mongoClientBuilder) { - - Element optionsElement = DomUtils.getChildElementByTagName(element, "client-options"); - - if (optionsElement == null) { - return false; - } - - BeanDefinitionBuilder clientOptionsDefBuilder = BeanDefinitionBuilder - .genericBeanDefinition(MongoClientOptionsFactoryBean.class); - - setPropertyValue(clientOptionsDefBuilder, optionsElement, "description", "description"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-connections-per-host", "minConnectionsPerHost"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier", - "threadsAllowedToBlockForConnectionMultiplier"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-idle-time", "maxConnectionIdleTime"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-life-time", "maxConnectionLifeTime"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "read-preference", "readPreference"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "write-concern", "writeConcern"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-frequency", "heartbeatFrequency"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-heartbeat-frequency", "minHeartbeatFrequency"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-connect-timeout", "heartbeatConnectTimeout"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-socket-timeout", "heartbeatSocketTimeout"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "ssl", "ssl"); - setPropertyReference(clientOptionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory"); - setPropertyValue(clientOptionsDefBuilder, optionsElement, "server-selection-timeout", "serverSelectionTimeout"); - - mongoClientBuilder.addPropertyValue("mongoClientOptions", clientOptionsDefBuilder.getBeanDefinition()); - - return true; - } - - /** - * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a - * {@link WriteConcernPropertyEditor}. - * - * @return - */ - static BeanDefinitionBuilder getWriteConcernPropertyEditorBuilder() { - - Map> customEditors = new ManagedMap>(); - customEditors.put("com.mongodb.WriteConcern", WriteConcernPropertyEditor.class); - - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); - builder.addPropertyValue("customEditors", customEditors); - - return builder; - } - - /** - * One should only register one bean definition but want to have the convenience of using - * AbstractSingleBeanDefinitionParser but have the side effect of registering a 'default' property editor with the - * container. - */ - static BeanDefinitionBuilder getServerAddressPropertyEditorBuilder() { - - Map customEditors = new ManagedMap(); - customEditors.put("com.mongodb.ServerAddress[]", - "org.springframework.data.mongodb.config.ServerAddressPropertyEditor"); - - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); - builder.addPropertyValue("customEditors", customEditors); - return builder; - } - - /** - * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a - * {@link ReadPreferencePropertyEditor}. - * - * @return - * @since 1.7 - */ - static BeanDefinitionBuilder getReadPreferencePropertyEditorBuilder() { - - Map> customEditors = new ManagedMap>(); - customEditors.put("com.mongodb.ReadPreference", ReadPreferencePropertyEditor.class); - - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); - builder.addPropertyValue("customEditors", customEditors); - - return builder; - } - - /** - * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a - * {@link MongoCredentialPropertyEditor}. - * - * @return - * @since 1.7 - */ - static BeanDefinitionBuilder getMongoCredentialPropertyEditor() { - - Map> customEditors = new ManagedMap>(); - customEditors.put("com.mongodb.MongoCredential[]", MongoCredentialPropertyEditor.class); - - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); - builder.addPropertyValue("customEditors", customEditors); - - return builder; - } -} +/* + * Copyright 2011-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.config; + +import static org.springframework.data.config.ParsingUtils.*; + +import java.util.Map; + +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.CustomEditorConfigurer; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.ManagedMap; +import org.springframework.beans.factory.xml.BeanDefinitionParser; +import org.springframework.data.mongodb.core.MongoClientOptionsFactoryBean; +import org.springframework.data.mongodb.core.MongoOptionsFactoryBean; +import org.springframework.util.xml.DomUtils; +import org.w3c.dom.Element; + +/** + * Utility methods for {@link BeanDefinitionParser} implementations for MongoDB. + * + * @author Mark Pollack + * @author Oliver Gierke + * @author Thomas Darimont + * @author Christoph Strobl + */ +@SuppressWarnings("deprecation") +abstract class MongoParsingUtils { + + private MongoParsingUtils() {} + + /** + * Parses the mongo replica-set element. + * + * @param parserContext the parser context + * @param element the mongo element + * @param mongoBuilder the bean definition builder to populate + * @return + */ + static void parseReplicaSet(Element element, BeanDefinitionBuilder mongoBuilder) { + setPropertyValue(mongoBuilder, element, "replica-set", "replicaSetSeeds"); + } + + /** + * Parses the {@code mongo:options} sub-element. Populates the given attribute factory with the proper attributes. + * + * @return true if parsing actually occured, {@literal false} otherwise + */ + static boolean parseMongoOptions(Element element, BeanDefinitionBuilder mongoBuilder) { + + Element optionsElement = DomUtils.getChildElementByTagName(element, "options"); + + if (optionsElement == null) { + return false; + } + + BeanDefinitionBuilder optionsDefBuilder = BeanDefinitionBuilder + .genericBeanDefinition(MongoOptionsFactoryBean.class); + + setPropertyValue(optionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost"); + setPropertyValue(optionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier", + "threadsAllowedToBlockForConnectionMultiplier"); + setPropertyValue(optionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime"); + setPropertyValue(optionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout"); + setPropertyValue(optionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout"); + setPropertyValue(optionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive"); + setPropertyValue(optionsDefBuilder, optionsElement, "auto-connect-retry", "autoConnectRetry"); + setPropertyValue(optionsDefBuilder, optionsElement, "max-auto-connect-retry-time", "maxAutoConnectRetryTime"); + setPropertyValue(optionsDefBuilder, optionsElement, "write-number", "writeNumber"); + setPropertyValue(optionsDefBuilder, optionsElement, "write-timeout", "writeTimeout"); + setPropertyValue(optionsDefBuilder, optionsElement, "write-fsync", "writeFsync"); + setPropertyValue(optionsDefBuilder, optionsElement, "slave-ok", "slaveOk"); + setPropertyValue(optionsDefBuilder, optionsElement, "ssl", "ssl"); + setPropertyReference(optionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory"); + + mongoBuilder.addPropertyValue("mongoOptions", optionsDefBuilder.getBeanDefinition()); + return true; + } + + /** + * Parses the {@code mongo:client-options} sub-element. Populates the given attribute factory with the proper + * attributes. + * + * @param element must not be {@literal null}. + * @param mongoClientBuilder must not be {@literal null}. + * @return + * @since 1.7 + */ + public static boolean parseMongoClientOptions(Element element, BeanDefinitionBuilder mongoClientBuilder) { + + Element optionsElement = DomUtils.getChildElementByTagName(element, "client-options"); + + if (optionsElement == null) { + return false; + } + + BeanDefinitionBuilder clientOptionsDefBuilder = BeanDefinitionBuilder + .genericBeanDefinition(MongoClientOptionsFactoryBean.class); + + setPropertyValue(clientOptionsDefBuilder, optionsElement, "description", "description"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-connections-per-host", "minConnectionsPerHost"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "connections-per-host", "connectionsPerHost"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "threads-allowed-to-block-for-connection-multiplier", + "threadsAllowedToBlockForConnectionMultiplier"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-wait-time", "maxWaitTime"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-idle-time", "maxConnectionIdleTime"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "max-connection-life-time", "maxConnectionLifeTime"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "connect-timeout", "connectTimeout"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-timeout", "socketTimeout"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "socket-keep-alive", "socketKeepAlive"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "read-preference", "readPreference"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "write-concern", "writeConcern"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-frequency", "heartbeatFrequency"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "min-heartbeat-frequency", "minHeartbeatFrequency"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-connect-timeout", "heartbeatConnectTimeout"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "heartbeat-socket-timeout", "heartbeatSocketTimeout"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "ssl", "ssl"); + setPropertyReference(clientOptionsDefBuilder, optionsElement, "ssl-socket-factory-ref", "sslSocketFactory"); + setPropertyValue(clientOptionsDefBuilder, optionsElement, "server-selection-timeout", "serverSelectionTimeout"); + + mongoClientBuilder.addPropertyValue("mongoClientOptions", clientOptionsDefBuilder.getBeanDefinition()); + + return true; + } + + /** + * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a + * {@link WriteConcernPropertyEditor}. + * + * @return + */ + static BeanDefinitionBuilder getWriteConcernPropertyEditorBuilder() { + + Map> customEditors = new ManagedMap>(); + customEditors.put("com.mongodb.WriteConcern", WriteConcernPropertyEditor.class); + + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); + builder.addPropertyValue("customEditors", customEditors); + + return builder; + } + + /** + * One should only register one bean definition but want to have the convenience of using + * AbstractSingleBeanDefinitionParser but have the side effect of registering a 'default' property editor with the + * container. + */ + static BeanDefinitionBuilder getServerAddressPropertyEditorBuilder() { + + Map customEditors = new ManagedMap(); + customEditors.put("com.mongodb.ServerAddress[]", + "org.springframework.data.mongodb.config.ServerAddressPropertyEditor"); + + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); + builder.addPropertyValue("customEditors", customEditors); + return builder; + } + + /** + * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a + * {@link ReadPreferencePropertyEditor}. + * + * @return + * @since 1.7 + */ + static BeanDefinitionBuilder getReadPreferencePropertyEditorBuilder() { + + Map> customEditors = new ManagedMap>(); + customEditors.put("com.mongodb.ReadPreference", ReadPreferencePropertyEditor.class); + + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); + builder.addPropertyValue("customEditors", customEditors); + + return builder; + } + + /** + * Returns the {@link BeanDefinitionBuilder} to build a {@link BeanDefinition} for a + * {@link MongoCredentialPropertyEditor}. + * + * @return + * @since 1.7 + */ + static BeanDefinitionBuilder getMongoCredentialPropertyEditor() { + + Map> customEditors = new ManagedMap>(); + customEditors.put("com.mongodb.MongoCredential[]", MongoCredentialPropertyEditor.class); + + BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(CustomEditorConfigurer.class); + builder.addPropertyValue("customEditors", customEditors); + + return builder; + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionCallback.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionCallback.java index 97b32f611..d28916e0f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionCallback.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionCallback.java @@ -1,26 +1,26 @@ -/* - * Copyright 2010-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import com.mongodb.DBCollection; -import com.mongodb.MongoException; -import org.springframework.dao.DataAccessException; - -public interface CollectionCallback { - - T doInCollection(DBCollection collection) throws MongoException, DataAccessException; - -} +/* + * Copyright 2010-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import com.mongodb.DBCollection; +import com.mongodb.MongoException; +import org.springframework.dao.DataAccessException; + +public interface CollectionCallback { + + T doInCollection(DBCollection collection) throws MongoException, DataAccessException; + +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java index 756e2863e..079bdc49d 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/CollectionOptions.java @@ -1,70 +1,70 @@ -/* - * Copyright 2010-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -/** - * 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 size; - - 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; - } - - public Integer getMaxDocuments() { - return maxDocuments; - } - - public void setMaxDocuments(Integer maxDocuments) { - this.maxDocuments = maxDocuments; - } - - public Integer getSize() { - return size; - } - - public void setSize(Integer size) { - this.size = size; - } - - public Boolean getCapped() { - return capped; - } - - public void setCapped(Boolean capped) { - this.capped = capped; - } - -} +/* + * Copyright 2010-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +/** + * 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 size; + + 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; + } + + public Integer getMaxDocuments() { + return maxDocuments; + } + + public void setMaxDocuments(Integer maxDocuments) { + this.maxDocuments = maxDocuments; + } + + public Integer getSize() { + return size; + } + + public void setSize(Integer size) { + this.size = size; + } + + 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/mongodb/core/DbCallback.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DbCallback.java index 4b72c6271..7aaaa670b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DbCallback.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/DbCallback.java @@ -1,25 +1,25 @@ -/* - * Copyright 2010-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import com.mongodb.DB; -import com.mongodb.MongoException; -import org.springframework.dao.DataAccessException; - -public interface DbCallback { - - T doInDB(DB db) throws MongoException, DataAccessException; -} +/* + * Copyright 2010-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import com.mongodb.DB; +import com.mongodb.MongoException; +import org.springframework.dao.DataAccessException; + +public interface DbCallback { + + T doInDB(DB db) throws MongoException, DataAccessException; +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdmin.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdmin.java index aaa64ff27..17b74c7e5 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdmin.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdmin.java @@ -1,101 +1,101 @@ -/* - * Copyright 2011-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import org.springframework.data.authentication.UserCredentials; -import org.springframework.jmx.export.annotation.ManagedOperation; -import org.springframework.jmx.export.annotation.ManagedResource; -import org.springframework.util.Assert; - -import com.mongodb.DB; -import com.mongodb.Mongo; - -/** - * Mongo server administration exposed via JMX annotations - * - * @author Mark Pollack - * @author Thomas Darimont - * @author Mark Paluch - */ -@ManagedResource(description = "Mongo Admin Operations") -public class MongoAdmin implements MongoAdminOperations { - - private final Mongo mongo; - private String username; - private String password; - private String authenticationDatabaseName; - - public MongoAdmin(Mongo mongo) { - - Assert.notNull(mongo, "Mongo must not be null!"); - this.mongo = mongo; - } - - /* (non-Javadoc) - * @see org.springframework.data.mongodb.core.core.MongoAdminOperations#dropDatabase(java.lang.String) - */ - @ManagedOperation - public void dropDatabase(String databaseName) { - getDB(databaseName).dropDatabase(); - } - - /* (non-Javadoc) - * @see org.springframework.data.mongodb.core.core.MongoAdminOperations#createDatabase(java.lang.String) - */ - @ManagedOperation - public void createDatabase(String databaseName) { - getDB(databaseName); - } - - /* (non-Javadoc) - * @see org.springframework.data.mongodb.core.core.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 password to use to authenticate with the Mongo database. - * - * @param password The password to use - */ - public void setPassword(String password) { - this.password = password; - } - - /** - * Sets the authenticationDatabaseName to use to authenticate with the Mongo database. - * - * @param authenticationDatabaseName The authenticationDatabaseName to use. - */ - public void setAuthenticationDatabaseName(String authenticationDatabaseName) { - this.authenticationDatabaseName = authenticationDatabaseName; - } - - DB getDB(String databaseName) { - return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password), authenticationDatabaseName); - } -} +/* + * Copyright 2011-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import org.springframework.data.authentication.UserCredentials; +import org.springframework.jmx.export.annotation.ManagedOperation; +import org.springframework.jmx.export.annotation.ManagedResource; +import org.springframework.util.Assert; + +import com.mongodb.DB; +import com.mongodb.Mongo; + +/** + * Mongo server administration exposed via JMX annotations + * + * @author Mark Pollack + * @author Thomas Darimont + * @author Mark Paluch + */ +@ManagedResource(description = "Mongo Admin Operations") +public class MongoAdmin implements MongoAdminOperations { + + private final Mongo mongo; + private String username; + private String password; + private String authenticationDatabaseName; + + public MongoAdmin(Mongo mongo) { + + Assert.notNull(mongo, "Mongo must not be null!"); + this.mongo = mongo; + } + + /* (non-Javadoc) + * @see org.springframework.data.mongodb.core.core.MongoAdminOperations#dropDatabase(java.lang.String) + */ + @ManagedOperation + public void dropDatabase(String databaseName) { + getDB(databaseName).dropDatabase(); + } + + /* (non-Javadoc) + * @see org.springframework.data.mongodb.core.core.MongoAdminOperations#createDatabase(java.lang.String) + */ + @ManagedOperation + public void createDatabase(String databaseName) { + getDB(databaseName); + } + + /* (non-Javadoc) + * @see org.springframework.data.mongodb.core.core.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 password to use to authenticate with the Mongo database. + * + * @param password The password to use + */ + public void setPassword(String password) { + this.password = password; + } + + /** + * Sets the authenticationDatabaseName to use to authenticate with the Mongo database. + * + * @param authenticationDatabaseName The authenticationDatabaseName to use. + */ + public void setAuthenticationDatabaseName(String authenticationDatabaseName) { + this.authenticationDatabaseName = authenticationDatabaseName; + } + + DB getDB(String databaseName) { + return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password), authenticationDatabaseName); + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdminOperations.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdminOperations.java index 293ef14c5..cceae298b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdminOperations.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoAdminOperations.java @@ -1,34 +1,34 @@ -/* - * Copyright 2011-2014 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import org.springframework.jmx.export.annotation.ManagedOperation; - -/** - * @author Mark Pollack - * @author Oliver Gierke - */ -public interface MongoAdminOperations { - - @ManagedOperation - void dropDatabase(String databaseName); - - @ManagedOperation - void createDatabase(String databaseName); - - @ManagedOperation - String getDatabaseStats(String databaseName); -} +/* + * Copyright 2011-2014 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import org.springframework.jmx.export.annotation.ManagedOperation; + +/** + * @author Mark Pollack + * @author Oliver Gierke + */ +public interface MongoAdminOperations { + + @ManagedOperation + void dropDatabase(String databaseName); + + @ManagedOperation + void createDatabase(String databaseName); + + @ManagedOperation + String getDatabaseStats(String databaseName); +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/SimpleMongoDbFactory.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/SimpleMongoDbFactory.java index 572dea038..fbb570a87 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/SimpleMongoDbFactory.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/SimpleMongoDbFactory.java @@ -1,235 +1,235 @@ -/* - * Copyright 2011-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import java.net.UnknownHostException; - -import org.springframework.beans.factory.DisposableBean; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.InvalidDataAccessApiUsageException; -import org.springframework.dao.support.PersistenceExceptionTranslator; -import org.springframework.data.authentication.UserCredentials; -import org.springframework.data.mongodb.MongoDbFactory; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -import com.mongodb.DB; -import com.mongodb.Mongo; -import com.mongodb.MongoClient; -import com.mongodb.MongoClientURI; -import com.mongodb.MongoException; -import com.mongodb.MongoURI; -import com.mongodb.WriteConcern; - -/** - * Factory to create {@link DB} instances from a {@link Mongo} instance. - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Thomas Darimont - * @author Christoph Strobl - */ -public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { - - private final Mongo mongo; - private final String databaseName; - private final boolean mongoInstanceCreated; - private final UserCredentials credentials; - private final PersistenceExceptionTranslator exceptionTranslator; - private final String authenticationDatabaseName; - - private WriteConcern writeConcern; - - /** - * Create an instance of {@link SimpleMongoDbFactory} given the {@link Mongo} instance and database name. - * - * @param mongo Mongo instance, must not be {@literal null}. - * @param databaseName database name, not be {@literal null} or empty. - * @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClient, String)}. - */ - @Deprecated - public SimpleMongoDbFactory(Mongo mongo, String databaseName) { - this(mongo, databaseName, null); - } - - /** - * Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password - * - * @param mongo Mongo instance, must not be {@literal null}. - * @param databaseName Database name, must not be {@literal null} or empty. - * @param credentials username and password. - * @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}. - */ - @Deprecated - public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials) { - this(mongo, databaseName, credentials, false, null); - } - - /** - * Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password - * - * @param mongo Mongo instance, must not be {@literal null}. - * @param databaseName Database name, must not be {@literal null} or empty. - * @param credentials username and password. - * @param authenticationDatabaseName the database name to use for authentication - * @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}. - */ - @Deprecated - public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials, - String authenticationDatabaseName) { - this(mongo, databaseName, credentials, false, authenticationDatabaseName); - } - - /** - * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoURI}. - * - * @param uri must not be {@literal null}. - * @throws MongoException - * @throws UnknownHostException - * @see MongoURI - * @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClientURI)} instead. - */ - @Deprecated - public SimpleMongoDbFactory(MongoURI uri) throws MongoException, UnknownHostException { - this(new Mongo(uri), uri.getDatabase(), new UserCredentials(uri.getUsername(), parseChars(uri.getPassword())), true, - uri.getDatabase()); - } - - /** - * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClientURI}. - * - * @param uri must not be {@literal null}. - * @throws UnknownHostException - * @since 1.7 - */ - public SimpleMongoDbFactory(MongoClientURI uri) throws UnknownHostException { - this(new MongoClient(uri), uri.getDatabase(), true); - } - - /** - * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClient}. - * - * @param mongoClient must not be {@literal null}. - * @param databaseName must not be {@literal null}. - * @since 1.7 - */ - public SimpleMongoDbFactory(MongoClient mongoClient, String databaseName) { - this(mongoClient, databaseName, false); - } - - private SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials, - boolean mongoInstanceCreated, String authenticationDatabaseName) { - - if (mongo instanceof MongoClient && (credentials != null && !UserCredentials.NO_CREDENTIALS.equals(credentials))) { - throw new InvalidDataAccessApiUsageException( - "Usage of 'UserCredentials' with 'MongoClient' is no longer supported. Please use 'MongoCredential' for 'MongoClient' or just 'Mongo'."); - } - - Assert.notNull(mongo, "Mongo must not be null"); - Assert.hasText(databaseName, "Database name must not be empty"); - Assert.isTrue(databaseName.matches("[\\w-]+"), - "Database name must only contain letters, numbers, underscores and dashes!"); - - this.mongo = mongo; - this.databaseName = databaseName; - this.mongoInstanceCreated = mongoInstanceCreated; - this.credentials = credentials == null ? UserCredentials.NO_CREDENTIALS : credentials; - this.exceptionTranslator = new MongoExceptionTranslator(); - this.authenticationDatabaseName = StringUtils.hasText(authenticationDatabaseName) ? authenticationDatabaseName - : databaseName; - - Assert.isTrue(this.authenticationDatabaseName.matches("[\\w-]+"), - "Authentication database name must only contain letters, numbers, underscores and dashes!"); - } - - /** - * @param client - * @param databaseName - * @param mongoInstanceCreated - * @since 1.7 - */ - private SimpleMongoDbFactory(MongoClient client, String databaseName, boolean mongoInstanceCreated) { - - Assert.notNull(client, "MongoClient must not be null!"); - Assert.hasText(databaseName, "Database name must not be empty!"); - - this.mongo = client; - this.databaseName = databaseName; - this.mongoInstanceCreated = mongoInstanceCreated; - this.exceptionTranslator = new MongoExceptionTranslator(); - this.credentials = UserCredentials.NO_CREDENTIALS; - this.authenticationDatabaseName = databaseName; - } - - /** - * Configures the {@link WriteConcern} to be used on the {@link DB} instance being created. - * - * @param writeConcern the writeConcern to set - */ - public void setWriteConcern(WriteConcern writeConcern) { - this.writeConcern = writeConcern; - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.MongoDbFactory#getDb() - */ - public DB getDb() throws DataAccessException { - return getDb(databaseName); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.MongoDbFactory#getDb(java.lang.String) - */ - @SuppressWarnings("deprecation") - public DB getDb(String dbName) throws DataAccessException { - - Assert.hasText(dbName, "Database name must not be empty."); - - DB db = MongoDbUtils.getDB(mongo, dbName, credentials, authenticationDatabaseName); - - if (writeConcern != null) { - db.setWriteConcern(writeConcern); - } - - return db; - } - - /** - * Clean up the Mongo instance if it was created by the factory itself. - * - * @see DisposableBean#destroy() - */ - public void destroy() throws Exception { - if (mongoInstanceCreated) { - mongo.close(); - } - } - - private static String parseChars(char[] chars) { - return chars == null ? null : String.valueOf(chars); - } - - /* - * (non-Javadoc) - * @see org.springframework.data.mongodb.MongoDbFactory#getExceptionTranslator() - */ - @Override - public PersistenceExceptionTranslator getExceptionTranslator() { - return this.exceptionTranslator; - } -} +/* + * Copyright 2011-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import java.net.UnknownHostException; + +import org.springframework.beans.factory.DisposableBean; +import org.springframework.dao.DataAccessException; +import org.springframework.dao.InvalidDataAccessApiUsageException; +import org.springframework.dao.support.PersistenceExceptionTranslator; +import org.springframework.data.authentication.UserCredentials; +import org.springframework.data.mongodb.MongoDbFactory; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + +import com.mongodb.DB; +import com.mongodb.Mongo; +import com.mongodb.MongoClient; +import com.mongodb.MongoClientURI; +import com.mongodb.MongoException; +import com.mongodb.MongoURI; +import com.mongodb.WriteConcern; + +/** + * Factory to create {@link DB} instances from a {@link Mongo} instance. + * + * @author Mark Pollack + * @author Oliver Gierke + * @author Thomas Darimont + * @author Christoph Strobl + */ +public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { + + private final Mongo mongo; + private final String databaseName; + private final boolean mongoInstanceCreated; + private final UserCredentials credentials; + private final PersistenceExceptionTranslator exceptionTranslator; + private final String authenticationDatabaseName; + + private WriteConcern writeConcern; + + /** + * Create an instance of {@link SimpleMongoDbFactory} given the {@link Mongo} instance and database name. + * + * @param mongo Mongo instance, must not be {@literal null}. + * @param databaseName database name, not be {@literal null} or empty. + * @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClient, String)}. + */ + @Deprecated + public SimpleMongoDbFactory(Mongo mongo, String databaseName) { + this(mongo, databaseName, null); + } + + /** + * Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password + * + * @param mongo Mongo instance, must not be {@literal null}. + * @param databaseName Database name, must not be {@literal null} or empty. + * @param credentials username and password. + * @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}. + */ + @Deprecated + public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials) { + this(mongo, databaseName, credentials, false, null); + } + + /** + * Create an instance of SimpleMongoDbFactory given the Mongo instance, database name, and username/password + * + * @param mongo Mongo instance, must not be {@literal null}. + * @param databaseName Database name, must not be {@literal null} or empty. + * @param credentials username and password. + * @param authenticationDatabaseName the database name to use for authentication + * @deprecated since 1.7. The credentials used should be provided by {@link MongoClient#getCredentialsList()}. + */ + @Deprecated + public SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials, + String authenticationDatabaseName) { + this(mongo, databaseName, credentials, false, authenticationDatabaseName); + } + + /** + * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoURI}. + * + * @param uri must not be {@literal null}. + * @throws MongoException + * @throws UnknownHostException + * @see MongoURI + * @deprecated since 1.7. Please use {@link #SimpleMongoDbFactory(MongoClientURI)} instead. + */ + @Deprecated + public SimpleMongoDbFactory(MongoURI uri) throws MongoException, UnknownHostException { + this(new Mongo(uri), uri.getDatabase(), new UserCredentials(uri.getUsername(), parseChars(uri.getPassword())), true, + uri.getDatabase()); + } + + /** + * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClientURI}. + * + * @param uri must not be {@literal null}. + * @throws UnknownHostException + * @since 1.7 + */ + public SimpleMongoDbFactory(MongoClientURI uri) throws UnknownHostException { + this(new MongoClient(uri), uri.getDatabase(), true); + } + + /** + * Creates a new {@link SimpleMongoDbFactory} instance from the given {@link MongoClient}. + * + * @param mongoClient must not be {@literal null}. + * @param databaseName must not be {@literal null}. + * @since 1.7 + */ + public SimpleMongoDbFactory(MongoClient mongoClient, String databaseName) { + this(mongoClient, databaseName, false); + } + + private SimpleMongoDbFactory(Mongo mongo, String databaseName, UserCredentials credentials, + boolean mongoInstanceCreated, String authenticationDatabaseName) { + + if (mongo instanceof MongoClient && (credentials != null && !UserCredentials.NO_CREDENTIALS.equals(credentials))) { + throw new InvalidDataAccessApiUsageException( + "Usage of 'UserCredentials' with 'MongoClient' is no longer supported. Please use 'MongoCredential' for 'MongoClient' or just 'Mongo'."); + } + + Assert.notNull(mongo, "Mongo must not be null"); + Assert.hasText(databaseName, "Database name must not be empty"); + Assert.isTrue(databaseName.matches("[\\w-]+"), + "Database name must only contain letters, numbers, underscores and dashes!"); + + this.mongo = mongo; + this.databaseName = databaseName; + this.mongoInstanceCreated = mongoInstanceCreated; + this.credentials = credentials == null ? UserCredentials.NO_CREDENTIALS : credentials; + this.exceptionTranslator = new MongoExceptionTranslator(); + this.authenticationDatabaseName = StringUtils.hasText(authenticationDatabaseName) ? authenticationDatabaseName + : databaseName; + + Assert.isTrue(this.authenticationDatabaseName.matches("[\\w-]+"), + "Authentication database name must only contain letters, numbers, underscores and dashes!"); + } + + /** + * @param client + * @param databaseName + * @param mongoInstanceCreated + * @since 1.7 + */ + private SimpleMongoDbFactory(MongoClient client, String databaseName, boolean mongoInstanceCreated) { + + Assert.notNull(client, "MongoClient must not be null!"); + Assert.hasText(databaseName, "Database name must not be empty!"); + + this.mongo = client; + this.databaseName = databaseName; + this.mongoInstanceCreated = mongoInstanceCreated; + this.exceptionTranslator = new MongoExceptionTranslator(); + this.credentials = UserCredentials.NO_CREDENTIALS; + this.authenticationDatabaseName = databaseName; + } + + /** + * Configures the {@link WriteConcern} to be used on the {@link DB} instance being created. + * + * @param writeConcern the writeConcern to set + */ + public void setWriteConcern(WriteConcern writeConcern) { + this.writeConcern = writeConcern; + } + + /* + * (non-Javadoc) + * @see org.springframework.data.mongodb.MongoDbFactory#getDb() + */ + public DB getDb() throws DataAccessException { + return getDb(databaseName); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.mongodb.MongoDbFactory#getDb(java.lang.String) + */ + @SuppressWarnings("deprecation") + public DB getDb(String dbName) throws DataAccessException { + + Assert.hasText(dbName, "Database name must not be empty."); + + DB db = MongoDbUtils.getDB(mongo, dbName, credentials, authenticationDatabaseName); + + if (writeConcern != null) { + db.setWriteConcern(writeConcern); + } + + return db; + } + + /** + * Clean up the Mongo instance if it was created by the factory itself. + * + * @see DisposableBean#destroy() + */ + public void destroy() throws Exception { + if (mongoInstanceCreated) { + mongo.close(); + } + } + + private static String parseChars(char[] chars) { + return chars == null ? null : String.valueOf(chars); + } + + /* + * (non-Javadoc) + * @see org.springframework.data.mongodb.MongoDbFactory#getExceptionTranslator() + */ + @Override + public PersistenceExceptionTranslator getExceptionTranslator() { + return this.exceptionTranslator; + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverter.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverter.java index ef9bfd69b..0695a6c45 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoConverter.java @@ -1,43 +1,43 @@ -/* - * Copyright 2010-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core.convert; - -import org.springframework.data.convert.EntityConverter; -import org.springframework.data.convert.EntityReader; -import org.springframework.data.convert.TypeMapper; -import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; -import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; - -import com.mongodb.DBObject; - -/** - * Central Mongo specific converter interface which combines {@link MongoWriter} and {@link MongoReader}. - * - * @author Oliver Gierke - * @author Thomas Darimont - */ -public interface MongoConverter extends - EntityConverter, MongoPersistentProperty, Object, DBObject>, MongoWriter, - EntityReader { - - /** - * Returns thw {@link TypeMapper} being used to write type information into {@link DBObject}s created with that - * converter. - * - * @return will never be {@literal null}. - */ - MongoTypeMapper getTypeMapper(); -} +/* + * Copyright 2010-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core.convert; + +import org.springframework.data.convert.EntityConverter; +import org.springframework.data.convert.EntityReader; +import org.springframework.data.convert.TypeMapper; +import org.springframework.data.mongodb.core.mapping.MongoPersistentEntity; +import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; + +import com.mongodb.DBObject; + +/** + * Central Mongo specific converter interface which combines {@link MongoWriter} and {@link MongoReader}. + * + * @author Oliver Gierke + * @author Thomas Darimont + */ +public interface MongoConverter extends + EntityConverter, MongoPersistentProperty, Object, DBObject>, MongoWriter, + EntityReader { + + /** + * Returns thw {@link TypeMapper} being used to write type information into {@link DBObject}s created with that + * converter. + * + * @return will never be {@literal null}. + */ + MongoTypeMapper getTypeMapper(); +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoWriter.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoWriter.java index 6d25f84a2..81b80f3ca 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoWriter.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/MongoWriter.java @@ -1,63 +1,63 @@ -/* - * Copyright 2010-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core.convert; - -import org.springframework.data.convert.EntityWriter; -import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; -import org.springframework.data.util.TypeInformation; - -import com.mongodb.DBObject; -import com.mongodb.DBRef; - -/** - * 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 - * @author Mark Pollack - * @author Thomas Risberg - * @author Oliver Gierke - */ -public interface MongoWriter extends EntityWriter { - - /** - * Converts the given object into one Mongo will be able to store natively. If the given object can already be stored - * as is, no conversion will happen. - * - * @param obj can be {@literal null}. - * @return - */ - Object convertToMongoType(Object obj); - - /** - * Converts the given object into one Mongo will be able to store natively but retains the type information in case - * the given {@link TypeInformation} differs from the given object type. - * - * @param obj can be {@literal null}. - * @param typeInformation can be {@literal null}. - * @return - */ - Object convertToMongoType(Object obj, TypeInformation typeInformation); - - /** - * Creates a {@link DBRef} to refer to the given object. - * - * @param object the object to create a {@link DBRef} to link to. The object's type has to carry an id attribute. - * @param referingProperty the client-side property referring to the object which might carry additional metadata for - * the {@link DBRef} object to create. Can be {@literal null}. - * @return will never be {@literal null}. - */ - DBRef toDBRef(Object object, MongoPersistentProperty referingProperty); -} +/* + * Copyright 2010-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core.convert; + +import org.springframework.data.convert.EntityWriter; +import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; +import org.springframework.data.util.TypeInformation; + +import com.mongodb.DBObject; +import com.mongodb.DBRef; + +/** + * 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 + * @author Mark Pollack + * @author Thomas Risberg + * @author Oliver Gierke + */ +public interface MongoWriter extends EntityWriter { + + /** + * Converts the given object into one Mongo will be able to store natively. If the given object can already be stored + * as is, no conversion will happen. + * + * @param obj can be {@literal null}. + * @return + */ + Object convertToMongoType(Object obj); + + /** + * Converts the given object into one Mongo will be able to store natively but retains the type information in case + * the given {@link TypeInformation} differs from the given object type. + * + * @param obj can be {@literal null}. + * @param typeInformation can be {@literal null}. + * @return + */ + Object convertToMongoType(Object obj, TypeInformation typeInformation); + + /** + * Creates a {@link DBRef} to refer to the given object. + * + * @param object the object to create a {@link DBRef} to link to. The object's type has to carry an id attribute. + * @param referingProperty the client-side property referring to the object which might carry additional metadata for + * the {@link DBRef} object to create. Can be {@literal null}. + * @return will never be {@literal null}. + */ + DBRef toDBRef(Object object, MongoPersistentProperty referingProperty); +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AbstractMonitor.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AbstractMonitor.java index 9498fcfb9..ab36c2a3f 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AbstractMonitor.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AbstractMonitor.java @@ -1,72 +1,72 @@ -/* - * Copyright 2002-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.data.authentication.UserCredentials; -import org.springframework.data.mongodb.core.MongoDbUtils; - -import com.mongodb.CommandResult; -import com.mongodb.DB; -import com.mongodb.Mongo; -import com.mongodb.MongoException; - -/** - * Base class to encapsulate common configuration settings when connecting to a database - * - * @author Mark Pollack - * @author Oliver Gierke - */ -public abstract class AbstractMonitor { - - private final Logger logger = LoggerFactory.getLogger(getClass()); - - 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 password to use to authenticate with the Mongo database. - * - * @param password The password to use - */ - public void setPassword(String 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 DB getDb(String databaseName) { - return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password)); - } -} +/* + * Copyright 2002-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.data.authentication.UserCredentials; +import org.springframework.data.mongodb.core.MongoDbUtils; + +import com.mongodb.CommandResult; +import com.mongodb.DB; +import com.mongodb.Mongo; +import com.mongodb.MongoException; + +/** + * Base class to encapsulate common configuration settings when connecting to a database + * + * @author Mark Pollack + * @author Oliver Gierke + */ +public abstract class AbstractMonitor { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + 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 password to use to authenticate with the Mongo database. + * + * @param password The password to use + */ + public void setPassword(String 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 DB getDb(String databaseName) { + return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password)); + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AssertMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AssertMetrics.java index 58c1b5778..d1ef6eb7c 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AssertMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/AssertMetrics.java @@ -1,67 +1,67 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedResource; -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; - } - - @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 = "Msg") - public int getMsg() { - return getBtree("msg"); - } - - @ManagedMetric(metricType = MetricType.COUNTER, displayName = "User") - public int getUser() { - return getBtree("user"); - } - - @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); - } - -} +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import com.mongodb.DBObject; +import com.mongodb.Mongo; +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedResource; +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; + } + + @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 = "Msg") + public int getMsg() { + return getBtree("msg"); + } + + @ManagedMetric(metricType = MetricType.COUNTER, displayName = "User") + public int getUser() { + return getBtree("user"); + } + + @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); + } + +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BackgroundFlushingMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BackgroundFlushingMetrics.java index eccd7786b..a58a55a8b 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BackgroundFlushingMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BackgroundFlushingMetrics.java @@ -1,75 +1,75 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import java.util.Date; - -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedResource; -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; - } - - @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.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 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; - } - -} +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import java.util.Date; + +import com.mongodb.DBObject; +import com.mongodb.Mongo; +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedResource; +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; + } + + @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.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 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; + } + +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BtreeIndexCounters.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BtreeIndexCounters.java index 90e902e09..523c3fe51 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BtreeIndexCounters.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/BtreeIndexCounters.java @@ -1,74 +1,74 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedResource; -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; - } - - @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 = "Misses") - public int getMisses() { - return getBtree("misses"); - } - - @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"); - } - - 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); - } - -} +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import com.mongodb.DBObject; +import com.mongodb.Mongo; +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedResource; +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; + } + + @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 = "Misses") + public int getMisses() { + return getBtree("misses"); + } + + @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"); + } + + 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/mongodb/monitor/ConnectionMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/ConnectionMetrics.java index c44ca3049..79e77f05a 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/ConnectionMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/ConnectionMetrics.java @@ -1,53 +1,53 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedResource; -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; - } - - @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); - } - - @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); - } - -} +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import com.mongodb.DBObject; +import com.mongodb.Mongo; +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedResource; +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; + } + + @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); + } + + @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/mongodb/monitor/GlobalLockMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/GlobalLockMetrics.java index 18bcc0f74..760623d90 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/GlobalLockMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/GlobalLockMetrics.java @@ -1,77 +1,77 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedResource; -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; - } - - @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.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 = "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); - } -} +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import com.mongodb.DBObject; +import com.mongodb.Mongo; +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedResource; +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; + } + + @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.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 = "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); + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/MemoryMetrics.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/MemoryMetrics.java index d68d72d45..99095f157 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/MemoryMetrics.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/MemoryMetrics.java @@ -1,68 +1,68 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedResource; -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; - } - - @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 = "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 = "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); - } - -} +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import com.mongodb.DBObject; +import com.mongodb.Mongo; +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedResource; +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; + } + + @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 = "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 = "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/mongodb/monitor/OperationCounters.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/OperationCounters.java index b74ee0dad..bc16931e4 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/OperationCounters.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/OperationCounters.java @@ -1,70 +1,70 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import com.mongodb.DBObject; -import com.mongodb.Mongo; -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedResource; -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; - } - - @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 = "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 = "GetMore operation count") - public int getGetMoreCount() { - return getOpCounter("getmore"); - } - - @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); - } -} +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import com.mongodb.DBObject; +import com.mongodb.Mongo; +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedResource; +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; + } + + @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 = "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 = "GetMore operation count") + public int getGetMoreCount() { + return getOpCounter("getmore"); + } + + @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); + } +} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/ServerInfo.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/ServerInfo.java index 98c9714c1..17937b045 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/ServerInfo.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/monitor/ServerInfo.java @@ -1,76 +1,76 @@ -/* - * Copyright 2012-2015 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import java.net.UnknownHostException; - -import org.springframework.jmx.export.annotation.ManagedMetric; -import org.springframework.jmx.export.annotation.ManagedOperation; -import org.springframework.jmx.export.annotation.ManagedResource; -import org.springframework.jmx.support.MetricType; - -import com.mongodb.Mongo; - -/** - * Expose basic server information via JMX - * - * @author Mark Pollack - * @author Thomas Darimont - * @author Christoph Strobl - */ -@ManagedResource(description = "Server Information") -public class ServerInfo extends AbstractMonitor { - - public ServerInfo(Mongo mongo) { - this.mongo = mongo; - } - - /** - * Returns the hostname of the used server reported by MongoDB. - * - * @return the reported hostname can also be an IP address. - * @throws UnknownHostException - */ - @ManagedOperation(description = "Server host name") - public String getHostName() throws UnknownHostException { - - /* - * UnknownHostException is not necessary anymore, but clients could have - * called this method in a try..catch(UnknownHostException) already - */ - return mongo.getAddress().getHost(); - } - - @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 = "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"); - } -} +/* + * Copyright 2012-2015 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import java.net.UnknownHostException; + +import org.springframework.jmx.export.annotation.ManagedMetric; +import org.springframework.jmx.export.annotation.ManagedOperation; +import org.springframework.jmx.export.annotation.ManagedResource; +import org.springframework.jmx.support.MetricType; + +import com.mongodb.Mongo; + +/** + * Expose basic server information via JMX + * + * @author Mark Pollack + * @author Thomas Darimont + * @author Christoph Strobl + */ +@ManagedResource(description = "Server Information") +public class ServerInfo extends AbstractMonitor { + + public ServerInfo(Mongo mongo) { + this.mongo = mongo; + } + + /** + * Returns the hostname of the used server reported by MongoDB. + * + * @return the reported hostname can also be an IP address. + * @throws UnknownHostException + */ + @ManagedOperation(description = "Server host name") + public String getHostName() throws UnknownHostException { + + /* + * UnknownHostException is not necessary anymore, but clients could have + * called this method in a try..catch(UnknownHostException) already + */ + return mongo.getAddress().getHost(); + } + + @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 = "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"); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java index f76e76893..61e5ebdfe 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceReplicaSetTests.java @@ -1,106 +1,106 @@ -/* - * Copyright 2011-2016 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.data.mongodb.config; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.net.InetAddress; -import java.util.ArrayList; -import java.util.List; - -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.data.mongodb.core.MongoFactoryBean; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import org.springframework.test.util.ReflectionTestUtils; - -import com.mongodb.CommandResult; -import com.mongodb.Mongo; -import com.mongodb.ServerAddress; - -/** - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Thomas Darimont - * @author Mark Paluch - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration -public class MongoNamespaceReplicaSetTests { - - @Autowired private ApplicationContext ctx; - - @Test - @SuppressWarnings("unchecked") - public void testParsingMongoWithReplicaSets() throws Exception { - - assertTrue(ctx.containsBean("replicaSetMongo")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&replicaSetMongo"); - - List replicaSetSeeds = (List) ReflectionTestUtils.getField(mfb, "replicaSetSeeds"); - - assertThat(replicaSetSeeds, is(notNullValue())); - assertThat( - replicaSetSeeds, - hasItems(new ServerAddress(InetAddress.getByName("127.0.0.1"), 10001), - new ServerAddress(InetAddress.getByName("localhost"), 10002))); - } - - @Test - @SuppressWarnings("unchecked") - public void testParsingWithPropertyPlaceHolder() throws Exception { - - assertTrue(ctx.containsBean("manyReplicaSetMongo")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&manyReplicaSetMongo"); - - List replicaSetSeeds = (List) ReflectionTestUtils.getField(mfb, "replicaSetSeeds"); - - assertThat(replicaSetSeeds, is(notNullValue())); - assertThat(replicaSetSeeds, hasSize(3)); - - List ports = new ArrayList(); - for (ServerAddress replicaSetSeed : replicaSetSeeds) { - ports.add(replicaSetSeed.getPort()); - } - - assertThat(ports, hasItems(27017, 27018, 27019)); - } - - @Test - @Ignore("CI infrastructure does not yet support replica sets") - public void testMongoWithReplicaSets() { - - Mongo mongo = ctx.getBean(Mongo.class); - assertEquals(2, mongo.getAllAddress().size()); - List servers = mongo.getAllAddress(); - assertEquals("127.0.0.1", servers.get(0).getHost()); - assertEquals("localhost", servers.get(1).getHost()); - assertEquals(10001, servers.get(0).getPort()); - assertEquals(10002, servers.get(1).getPort()); - - MongoTemplate template = new MongoTemplate(mongo, "admin"); - CommandResult result = template.executeCommand("{replSetGetStatus : 1}"); - assertEquals("blort", result.getString("set")); - } -} +/* + * Copyright 2011-2016 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.data.mongodb.config; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.net.InetAddress; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Ignore; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.data.mongodb.core.MongoFactoryBean; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import org.springframework.test.util.ReflectionTestUtils; + +import com.mongodb.CommandResult; +import com.mongodb.Mongo; +import com.mongodb.ServerAddress; + +/** + * + * @author Mark Pollack + * @author Oliver Gierke + * @author Thomas Darimont + * @author Mark Paluch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class MongoNamespaceReplicaSetTests { + + @Autowired private ApplicationContext ctx; + + @Test + @SuppressWarnings("unchecked") + public void testParsingMongoWithReplicaSets() throws Exception { + + assertTrue(ctx.containsBean("replicaSetMongo")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&replicaSetMongo"); + + List replicaSetSeeds = (List) ReflectionTestUtils.getField(mfb, "replicaSetSeeds"); + + assertThat(replicaSetSeeds, is(notNullValue())); + assertThat( + replicaSetSeeds, + hasItems(new ServerAddress(InetAddress.getByName("127.0.0.1"), 10001), + new ServerAddress(InetAddress.getByName("localhost"), 10002))); + } + + @Test + @SuppressWarnings("unchecked") + public void testParsingWithPropertyPlaceHolder() throws Exception { + + assertTrue(ctx.containsBean("manyReplicaSetMongo")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&manyReplicaSetMongo"); + + List replicaSetSeeds = (List) ReflectionTestUtils.getField(mfb, "replicaSetSeeds"); + + assertThat(replicaSetSeeds, is(notNullValue())); + assertThat(replicaSetSeeds, hasSize(3)); + + List ports = new ArrayList(); + for (ServerAddress replicaSetSeed : replicaSetSeeds) { + ports.add(replicaSetSeed.getPort()); + } + + assertThat(ports, hasItems(27017, 27018, 27019)); + } + + @Test + @Ignore("CI infrastructure does not yet support replica sets") + public void testMongoWithReplicaSets() { + + Mongo mongo = ctx.getBean(Mongo.class); + assertEquals(2, mongo.getAllAddress().size()); + List servers = mongo.getAllAddress(); + assertEquals("127.0.0.1", servers.get(0).getHost()); + assertEquals("localhost", servers.get(1).getHost()); + assertEquals(10001, servers.get(0).getPort()); + assertEquals(10002, servers.get(1).getPort()); + + MongoTemplate template = new MongoTemplate(mongo, "admin"); + CommandResult result = template.executeCommand("{replSetGetStatus : 1}"); + assertEquals("blort", result.getString("set")); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java index 1b6463046..ef903e25b 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/config/MongoNamespaceTests.java @@ -1,253 +1,253 @@ -/* - * Copyright 2010-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.config; - -import static org.junit.Assert.*; -import static org.junit.Assume.*; -import static org.springframework.data.mongodb.util.MongoClientVersion.*; -import static org.springframework.test.util.ReflectionTestUtils.*; - -import javax.net.ssl.SSLSocketFactory; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.data.authentication.UserCredentials; -import org.springframework.data.mongodb.MongoDbFactory; -import org.springframework.data.mongodb.core.MongoClientFactoryBean; -import org.springframework.data.mongodb.core.MongoFactoryBean; -import org.springframework.data.mongodb.core.MongoOperations; -import org.springframework.data.mongodb.core.ReflectiveMongoOptionsInvokerTestUtil; -import org.springframework.data.mongodb.core.convert.MongoConverter; -import org.springframework.data.mongodb.gridfs.GridFsOperations; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.mongodb.Mongo; -import com.mongodb.MongoClientOptions; -import com.mongodb.MongoOptions; -import com.mongodb.WriteConcern; - -/** - * Integration tests for the MongoDB namespace. - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Martin Baumgartner - * @author Thomas Darimont - * @author Christoph Strobl - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration -public class MongoNamespaceTests { - - @Autowired ApplicationContext ctx; - - @BeforeClass - public static void validateMongoDriver() { - assumeFalse(isMongo3Driver()); - } - - @Test - public void testMongoSingleton() throws Exception { - - assertTrue(ctx.containsBean("noAttrMongo")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&noAttrMongo"); - - assertNull(getField(mfb, "host")); - assertNull(getField(mfb, "port")); - } - - @Test - public void testMongoSingletonWithAttributes() throws Exception { - - assertTrue(ctx.containsBean("defaultMongo")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&defaultMongo"); - - String host = (String) getField(mfb, "host"); - Integer port = (Integer) getField(mfb, "port"); - - assertEquals("localhost", host); - assertEquals(new Integer(27017), port); - - MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions"); - assertFalse("By default socketFactory should not be a SSLSocketFactory", - options.getSocketFactory() instanceof SSLSocketFactory); - } - - @Test // DATAMONGO-764 - public void testMongoSingletonWithSslEnabled() throws Exception { - - assertTrue(ctx.containsBean("mongoSsl")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongoSsl"); - - MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions"); - assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); - } - - @Test // DATAMONGO-1490 - public void testMongoClientSingletonWithSslEnabled() { - - assertTrue(ctx.containsBean("mongoClientSsl")); - MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClientSsl"); - - MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions"); - assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); - } - - @Test // DATAMONGO-764 - public void testMongoSingletonWithSslEnabledAndCustomSslSocketFactory() throws Exception { - - assertTrue(ctx.containsBean("mongoSslWithCustomSslFactory")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory"); - - SSLSocketFactory customSslSocketFactory = ctx.getBean("customSslSocketFactory", SSLSocketFactory.class); - MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions"); - - assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); - assertSame(customSslSocketFactory, options.getSocketFactory()); - } - - @Test - public void testSecondMongoDbFactory() { - - assertTrue(ctx.containsBean("secondMongoDbFactory")); - MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("secondMongoDbFactory"); - - Mongo mongo = (Mongo) getField(dbf, "mongo"); - assertEquals("localhost", mongo.getAddress().getHost()); - assertEquals(27017, mongo.getAddress().getPort()); - assertEquals(new UserCredentials("joe", "secret"), getField(dbf, "credentials")); - assertEquals("database", getField(dbf, "databaseName")); - } - - @Test // DATAMONGO-789 - public void testThirdMongoDbFactory() { - - assertTrue(ctx.containsBean("thirdMongoDbFactory")); - - MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("thirdMongoDbFactory"); - Mongo mongo = (Mongo) getField(dbf, "mongo"); - - assertEquals("localhost", mongo.getAddress().getHost()); - assertEquals(27017, mongo.getAddress().getPort()); - assertEquals(new UserCredentials("joe", "secret"), getField(dbf, "credentials")); - assertEquals("database", getField(dbf, "databaseName")); - assertEquals("admin", getField(dbf, "authenticationDatabaseName")); - } - - @Test // DATAMONGO-140 - public void testMongoTemplateFactory() { - - assertTrue(ctx.containsBean("mongoTemplate")); - MongoOperations operations = (MongoOperations) ctx.getBean("mongoTemplate"); - - MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory"); - assertEquals("database", getField(dbf, "databaseName")); - - MongoConverter converter = (MongoConverter) getField(operations, "mongoConverter"); - assertNotNull(converter); - } - - @Test // DATAMONGO-140 - public void testSecondMongoTemplateFactory() { - - assertTrue(ctx.containsBean("anotherMongoTemplate")); - MongoOperations operations = (MongoOperations) ctx.getBean("anotherMongoTemplate"); - - MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory"); - assertEquals("database", getField(dbf, "databaseName")); - - WriteConcern writeConcern = (WriteConcern) getField(operations, "writeConcern"); - assertEquals(WriteConcern.SAFE, writeConcern); - } - - @Test // DATAMONGO-628 - public void testGridFsTemplateFactory() { - - assertTrue(ctx.containsBean("gridFsTemplate")); - GridFsOperations operations = (GridFsOperations) ctx.getBean("gridFsTemplate"); - - MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); - assertEquals("database", getField(dbf, "databaseName")); - - MongoConverter converter = (MongoConverter) getField(operations, "converter"); - assertNotNull(converter); - } - - @Test // DATAMONGO-628 - public void testSecondGridFsTemplateFactory() { - - assertTrue(ctx.containsBean("secondGridFsTemplate")); - GridFsOperations operations = (GridFsOperations) ctx.getBean("secondGridFsTemplate"); - - MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); - assertEquals("database", getField(dbf, "databaseName")); - assertEquals(null, getField(operations, "bucket")); - - MongoConverter converter = (MongoConverter) getField(operations, "converter"); - assertNotNull(converter); - } - - @Test // DATAMONGO-823 - public void testThirdGridFsTemplateFactory() { - - assertTrue(ctx.containsBean("thirdGridFsTemplate")); - GridFsOperations operations = (GridFsOperations) ctx.getBean("thirdGridFsTemplate"); - - MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); - assertEquals("database", getField(dbf, "databaseName")); - assertEquals("bucketString", getField(operations, "bucket")); - - MongoConverter converter = (MongoConverter) getField(operations, "converter"); - assertNotNull(converter); - } - - @Test - @SuppressWarnings("deprecation") - public void testMongoSingletonWithPropertyPlaceHolders() throws Exception { - - assertTrue(ctx.containsBean("mongo")); - MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongo"); - - String host = (String) getField(mfb, "host"); - Integer port = (Integer) getField(mfb, "port"); - - assertEquals("127.0.0.1", host); - assertEquals(new Integer(27017), port); - - Mongo mongo = mfb.getObject(); - MongoOptions mongoOpts = mongo.getMongoOptions(); - - assertEquals(8, mongoOpts.connectionsPerHost); - assertEquals(1000, mongoOpts.connectTimeout); - assertEquals(1500, mongoOpts.maxWaitTime); - - assertEquals(1500, mongoOpts.socketTimeout); - assertEquals(4, mongoOpts.threadsAllowedToBlockForConnectionMultiplier); - assertEquals(true, mongoOpts.socketKeepAlive); - - assertEquals(1, mongoOpts.getWriteConcern().getW()); - assertEquals(0, mongoOpts.getWriteConcern().getWtimeout()); - assertEquals(true, mongoOpts.getWriteConcern().fsync()); - - assertEquals(true, mongoOpts.fsync); - assertEquals(true, ReflectiveMongoOptionsInvokerTestUtil.getAutoConnectRetry(mongoOpts)); - assertEquals(true, ReflectiveMongoOptionsInvokerTestUtil.getSlaveOk(mongoOpts)); - } -} +/* + * Copyright 2010-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.config; + +import static org.junit.Assert.*; +import static org.junit.Assume.*; +import static org.springframework.data.mongodb.util.MongoClientVersion.*; +import static org.springframework.test.util.ReflectionTestUtils.*; + +import javax.net.ssl.SSLSocketFactory; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.ApplicationContext; +import org.springframework.data.authentication.UserCredentials; +import org.springframework.data.mongodb.MongoDbFactory; +import org.springframework.data.mongodb.core.MongoClientFactoryBean; +import org.springframework.data.mongodb.core.MongoFactoryBean; +import org.springframework.data.mongodb.core.MongoOperations; +import org.springframework.data.mongodb.core.ReflectiveMongoOptionsInvokerTestUtil; +import org.springframework.data.mongodb.core.convert.MongoConverter; +import org.springframework.data.mongodb.gridfs.GridFsOperations; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.mongodb.Mongo; +import com.mongodb.MongoClientOptions; +import com.mongodb.MongoOptions; +import com.mongodb.WriteConcern; + +/** + * Integration tests for the MongoDB namespace. + * + * @author Mark Pollack + * @author Oliver Gierke + * @author Martin Baumgartner + * @author Thomas Darimont + * @author Christoph Strobl + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration +public class MongoNamespaceTests { + + @Autowired ApplicationContext ctx; + + @BeforeClass + public static void validateMongoDriver() { + assumeFalse(isMongo3Driver()); + } + + @Test + public void testMongoSingleton() throws Exception { + + assertTrue(ctx.containsBean("noAttrMongo")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&noAttrMongo"); + + assertNull(getField(mfb, "host")); + assertNull(getField(mfb, "port")); + } + + @Test + public void testMongoSingletonWithAttributes() throws Exception { + + assertTrue(ctx.containsBean("defaultMongo")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&defaultMongo"); + + String host = (String) getField(mfb, "host"); + Integer port = (Integer) getField(mfb, "port"); + + assertEquals("localhost", host); + assertEquals(new Integer(27017), port); + + MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions"); + assertFalse("By default socketFactory should not be a SSLSocketFactory", + options.getSocketFactory() instanceof SSLSocketFactory); + } + + @Test // DATAMONGO-764 + public void testMongoSingletonWithSslEnabled() throws Exception { + + assertTrue(ctx.containsBean("mongoSsl")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongoSsl"); + + MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions"); + assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); + } + + @Test // DATAMONGO-1490 + public void testMongoClientSingletonWithSslEnabled() { + + assertTrue(ctx.containsBean("mongoClientSsl")); + MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClientSsl"); + + MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions"); + assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); + } + + @Test // DATAMONGO-764 + public void testMongoSingletonWithSslEnabledAndCustomSslSocketFactory() throws Exception { + + assertTrue(ctx.containsBean("mongoSslWithCustomSslFactory")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory"); + + SSLSocketFactory customSslSocketFactory = ctx.getBean("customSslSocketFactory", SSLSocketFactory.class); + MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions"); + + assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory); + assertSame(customSslSocketFactory, options.getSocketFactory()); + } + + @Test + public void testSecondMongoDbFactory() { + + assertTrue(ctx.containsBean("secondMongoDbFactory")); + MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("secondMongoDbFactory"); + + Mongo mongo = (Mongo) getField(dbf, "mongo"); + assertEquals("localhost", mongo.getAddress().getHost()); + assertEquals(27017, mongo.getAddress().getPort()); + assertEquals(new UserCredentials("joe", "secret"), getField(dbf, "credentials")); + assertEquals("database", getField(dbf, "databaseName")); + } + + @Test // DATAMONGO-789 + public void testThirdMongoDbFactory() { + + assertTrue(ctx.containsBean("thirdMongoDbFactory")); + + MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("thirdMongoDbFactory"); + Mongo mongo = (Mongo) getField(dbf, "mongo"); + + assertEquals("localhost", mongo.getAddress().getHost()); + assertEquals(27017, mongo.getAddress().getPort()); + assertEquals(new UserCredentials("joe", "secret"), getField(dbf, "credentials")); + assertEquals("database", getField(dbf, "databaseName")); + assertEquals("admin", getField(dbf, "authenticationDatabaseName")); + } + + @Test // DATAMONGO-140 + public void testMongoTemplateFactory() { + + assertTrue(ctx.containsBean("mongoTemplate")); + MongoOperations operations = (MongoOperations) ctx.getBean("mongoTemplate"); + + MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory"); + assertEquals("database", getField(dbf, "databaseName")); + + MongoConverter converter = (MongoConverter) getField(operations, "mongoConverter"); + assertNotNull(converter); + } + + @Test // DATAMONGO-140 + public void testSecondMongoTemplateFactory() { + + assertTrue(ctx.containsBean("anotherMongoTemplate")); + MongoOperations operations = (MongoOperations) ctx.getBean("anotherMongoTemplate"); + + MongoDbFactory dbf = (MongoDbFactory) getField(operations, "mongoDbFactory"); + assertEquals("database", getField(dbf, "databaseName")); + + WriteConcern writeConcern = (WriteConcern) getField(operations, "writeConcern"); + assertEquals(WriteConcern.SAFE, writeConcern); + } + + @Test // DATAMONGO-628 + public void testGridFsTemplateFactory() { + + assertTrue(ctx.containsBean("gridFsTemplate")); + GridFsOperations operations = (GridFsOperations) ctx.getBean("gridFsTemplate"); + + MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); + assertEquals("database", getField(dbf, "databaseName")); + + MongoConverter converter = (MongoConverter) getField(operations, "converter"); + assertNotNull(converter); + } + + @Test // DATAMONGO-628 + public void testSecondGridFsTemplateFactory() { + + assertTrue(ctx.containsBean("secondGridFsTemplate")); + GridFsOperations operations = (GridFsOperations) ctx.getBean("secondGridFsTemplate"); + + MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); + assertEquals("database", getField(dbf, "databaseName")); + assertEquals(null, getField(operations, "bucket")); + + MongoConverter converter = (MongoConverter) getField(operations, "converter"); + assertNotNull(converter); + } + + @Test // DATAMONGO-823 + public void testThirdGridFsTemplateFactory() { + + assertTrue(ctx.containsBean("thirdGridFsTemplate")); + GridFsOperations operations = (GridFsOperations) ctx.getBean("thirdGridFsTemplate"); + + MongoDbFactory dbf = (MongoDbFactory) getField(operations, "dbFactory"); + assertEquals("database", getField(dbf, "databaseName")); + assertEquals("bucketString", getField(operations, "bucket")); + + MongoConverter converter = (MongoConverter) getField(operations, "converter"); + assertNotNull(converter); + } + + @Test + @SuppressWarnings("deprecation") + public void testMongoSingletonWithPropertyPlaceHolders() throws Exception { + + assertTrue(ctx.containsBean("mongo")); + MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongo"); + + String host = (String) getField(mfb, "host"); + Integer port = (Integer) getField(mfb, "port"); + + assertEquals("127.0.0.1", host); + assertEquals(new Integer(27017), port); + + Mongo mongo = mfb.getObject(); + MongoOptions mongoOpts = mongo.getMongoOptions(); + + assertEquals(8, mongoOpts.connectionsPerHost); + assertEquals(1000, mongoOpts.connectTimeout); + assertEquals(1500, mongoOpts.maxWaitTime); + + assertEquals(1500, mongoOpts.socketTimeout); + assertEquals(4, mongoOpts.threadsAllowedToBlockForConnectionMultiplier); + assertEquals(true, mongoOpts.socketKeepAlive); + + assertEquals(1, mongoOpts.getWriteConcern().getW()); + assertEquals(0, mongoOpts.getWriteConcern().getWtimeout()); + assertEquals(true, mongoOpts.getWriteConcern().fsync()); + + assertEquals(true, mongoOpts.fsync); + assertEquals(true, ReflectiveMongoOptionsInvokerTestUtil.getAutoConnectRetry(mongoOpts)); + assertEquals(true, ReflectiveMongoOptionsInvokerTestUtil.getSlaveOk(mongoOpts)); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java index 924742ee0..9191f9f13 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoAdminIntegrationTests.java @@ -1,60 +1,60 @@ -/* - * Copyright 2002-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import com.mongodb.CommandResult; -import com.mongodb.DB; -import com.mongodb.Mongo; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -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 { - +/* + * Copyright 2002-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import com.mongodb.CommandResult; +import com.mongodb.DB; +import com.mongodb.Mongo; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +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 final Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class); - - @SuppressWarnings("unused") - private DB testAdminDb; - - @Autowired - Mongo mongo; - - @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); - } + + @SuppressWarnings("unused") + private DB testAdminDb; + + @Autowired + Mongo mongo; + + @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); + } } \ No newline at end of file diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExample.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExample.java index acfa990dd..e4a7f981c 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExample.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExample.java @@ -1,96 +1,96 @@ -/* - * Copyright 2002-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import java.util.List; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.support.AbstractApplicationContext; - -/** - * @author Jon Brisbin - * @author Oliver Gierke - */ -public class PersonExample { - - private static final Logger LOGGER = LoggerFactory.getLogger(PersonExample.class); - - @Autowired private MongoOperations mongoOps; - - public static void main(String[] args) { - AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonExampleAppConfig.class); - PersonExample example = applicationContext.getBean(PersonExample.class); - example.doWork(); - applicationContext.close(); - } - - 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); - - LOGGER.debug("Saved: " + p); - - p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); - - LOGGER.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.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); - LOGGER.debug("Updated: " + p); - - List folks = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class); - LOGGER.debug("Querying for all people..."); - for (PersonWithIdPropertyOfTypeString element : folks) { - LOGGER.debug(element.toString()); - } - - // mongoOps.remove( query(whereId().is(p.getId())), p.getClass()); - - mongoOps.remove(p); - - List people = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class); - - LOGGER.debug("Number of people = : " + people.size()); - - } - - public void doWork2() { - mongoOps.dropCollection("personexample"); - - PersonWithIdPropertyOfTypeString p = new PersonWithIdPropertyOfTypeString(); - p.setFirstName("Sven"); - p.setAge(22); - - } - -} +/* + * Copyright 2002-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.context.support.AbstractApplicationContext; + +/** + * @author Jon Brisbin + * @author Oliver Gierke + */ +public class PersonExample { + + private static final Logger LOGGER = LoggerFactory.getLogger(PersonExample.class); + + @Autowired private MongoOperations mongoOps; + + public static void main(String[] args) { + AbstractApplicationContext applicationContext = new AnnotationConfigApplicationContext(PersonExampleAppConfig.class); + PersonExample example = applicationContext.getBean(PersonExample.class); + example.doWork(); + applicationContext.close(); + } + + 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); + + LOGGER.debug("Saved: " + p); + + p = mongoOps.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); + + LOGGER.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.findById(p.getId(), PersonWithIdPropertyOfTypeString.class); + LOGGER.debug("Updated: " + p); + + List folks = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class); + LOGGER.debug("Querying for all people..."); + for (PersonWithIdPropertyOfTypeString element : folks) { + LOGGER.debug(element.toString()); + } + + // mongoOps.remove( query(whereId().is(p.getId())), p.getClass()); + + mongoOps.remove(p); + + List people = mongoOps.findAll(PersonWithIdPropertyOfTypeString.class); + + LOGGER.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/mongodb/core/PersonExampleAppConfig.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExampleAppConfig.java index 28fa3b066..4819c6739 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExampleAppConfig.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/PersonExampleAppConfig.java @@ -1,41 +1,41 @@ -/* - * Copyright 2002-2010 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import com.mongodb.Mongo; -import com.mongodb.MongoClient; - -@Configuration -public class PersonExampleAppConfig { - - @Bean - public Mongo mongo() throws Exception { - return new MongoClient("localhost"); - } - - @Bean - public MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), "database"); - } - - @Bean - public PersonExample personExample() { - return new PersonExample(); - } -} +/* + * Copyright 2002-2010 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import com.mongodb.Mongo; +import com.mongodb.MongoClient; + +@Configuration +public class PersonExampleAppConfig { + + @Bean + public Mongo mongo() throws Exception { + return new MongoClient("localhost"); + } + + @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/mongodb/core/Portfolio.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Portfolio.java index 45ebcc678..31bd1f8f4 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Portfolio.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Portfolio.java @@ -1,73 +1,73 @@ -/* - * Copyright 2010-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -public class Portfolio { - - private String portfolioName; - private User user; - private List trades; - private Map positions; - private Map portfolioManagers; - - public Map getPortfolioManagers() { - return portfolioManagers; - } - - public void setPortfolioManagers(Map portfolioManagers) { - this.portfolioManagers = portfolioManagers; - } - - public Map getPositions() { - return positions; - } - - public void setPositions(Map positions) { - this.positions = positions; - } - - public Portfolio() { - trades = new ArrayList(); - } - - public String getPortfolioName() { - return portfolioName; - } - - public void setPortfolioName(String portfolioName) { - this.portfolioName = portfolioName; - } - - public List getTrades() { - return trades; - } - - public void setTrades(List trades) { - this.trades = trades; - } - - public User getUser() { - return user; - } - - public void setUser(User user) { - this.user = user; - } -} +/* + * Copyright 2010-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class Portfolio { + + private String portfolioName; + private User user; + private List trades; + private Map positions; + private Map portfolioManagers; + + public Map getPortfolioManagers() { + return portfolioManagers; + } + + public void setPortfolioManagers(Map portfolioManagers) { + this.portfolioManagers = portfolioManagers; + } + + public Map getPositions() { + return positions; + } + + public void setPositions(Map positions) { + this.positions = positions; + } + + public Portfolio() { + trades = new ArrayList(); + } + + public String getPortfolioName() { + return portfolioName; + } + + public void setPortfolioName(String portfolioName) { + this.portfolioName = portfolioName; + } + + public List getTrades() { + return trades; + } + + public void setTrades(List trades) { + this.trades = trades; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Trade.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Trade.java index 85bf0ec84..2c1332827 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Trade.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Trade.java @@ -1,60 +1,60 @@ -/* - * Copyright 2010-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -public class Trade { - - private String ticker; - - private long quantity; - - private double price; - - private String orderType; - - public String getOrderType() { - return orderType; - } - - public void setOrderType(String orderType) { - this.orderType = orderType; - } - - public double getPrice() { - return price; - } - - public void setPrice(double price) { - this.price = price; - } - - public long getQuantity() { - return quantity; - } - - public void setQuantity(long quantity) { - this.quantity = quantity; - } - - public String getTicker() { - return ticker; - } - - public void setTicker(String ticker) { - this.ticker = ticker; - } - -} +/* + * Copyright 2010-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +public class Trade { + + private String ticker; + + private long quantity; + + private double price; + + private String orderType; + + public String getOrderType() { + return orderType; + } + + public void setOrderType(String orderType) { + this.orderType = orderType; + } + + public double getPrice() { + return price; + } + + public void setPrice(double price) { + this.price = price; + } + + public long getQuantity() { + return quantity; + } + + public void setQuantity(long quantity) { + this.quantity = quantity; + } + + 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/mongodb/core/User.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/User.java index 7e1b0cb52..d69e988df 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/User.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/User.java @@ -1,71 +1,71 @@ -/* - * Copyright 2010-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -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 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 userName; - - public String getAccountName() { - return accountName; - } - - public void setAccountName(String accountName) { - this.accountName = accountName; - } - - public String getUserName() { - return userName; - } - - public void setUserName(String userName) { - this.userName = userName; - } - -} +/* + * Copyright 2010-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +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 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 userName; + + public String getAccountName() { + return accountName; + } + + public void setAccountName(String accountName) { + this.accountName = accountName; + } + + 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/mongodb/core/Venue.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Venue.java index 0759c0b18..1b3be0fc1 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Venue.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/Venue.java @@ -1,66 +1,66 @@ -/* - * Copyright 2010-2011 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core; - -import java.util.Arrays; - -import org.joda.time.LocalDate; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.PersistenceConstructor; -import org.springframework.data.mongodb.core.mapping.Document; - -@Document(collection = "newyork") -public class Venue { - - @Id private String id; - private String name; - private double[] location; - private LocalDate openingDate; - - @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; - } - - public double[] getLocation() { - return location; - } - - public LocalDate getOpeningDate() { - return openingDate; - } - - public void setOpeningDate(LocalDate openingDate) { - this.openingDate = openingDate; - } - - @Override - public String toString() { - return "Venue [id=" + id + ", name=" + name + ", location=" + Arrays.toString(location) + "]"; - } -} +/* + * Copyright 2010-2011 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core; + +import java.util.Arrays; + +import org.joda.time.LocalDate; +import org.springframework.data.annotation.Id; +import org.springframework.data.annotation.PersistenceConstructor; +import org.springframework.data.mongodb.core.mapping.Document; + +@Document(collection = "newyork") +public class Venue { + + @Id private String id; + private String name; + private double[] location; + private LocalDate openingDate; + + @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; + } + + public double[] getLocation() { + return location; + } + + public LocalDate getOpeningDate() { + return openingDate; + } + + public void setOpeningDate(LocalDate openingDate) { + this.openingDate = openingDate; + } + + @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/mongodb/core/geo/GeoSpatial2DSphereTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java index a069b183c..7f5e2e8b9 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DSphereTests.java @@ -1,89 +1,89 @@ -/* - * Copyright 2010-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.data.mongodb.core.geo; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; -import static org.springframework.data.mongodb.core.query.Criteria.*; -import static org.springframework.data.mongodb.core.query.Query.*; - -import java.util.List; - -import org.junit.Test; -import org.springframework.data.domain.Sort.Direction; -import org.springframework.data.geo.GeoResults; -import org.springframework.data.geo.Metric; -import org.springframework.data.geo.Metrics; -import org.springframework.data.geo.Point; -import org.springframework.data.mongodb.core.IndexOperations; -import org.springframework.data.mongodb.core.Venue; -import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; -import org.springframework.data.mongodb.core.index.GeospatialIndex; -import org.springframework.data.mongodb.core.index.IndexField; -import org.springframework.data.mongodb.core.index.IndexInfo; -import org.springframework.data.mongodb.core.query.NearQuery; - -/** - * @author Christoph Strobl - */ -public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests { - - @Test // DATAMONGO-360 - public void indexInfoIsCorrect() { - - IndexOperations operations = template.indexOps(Venue.class); - List indexInfo = operations.getIndexInfo(); - - assertThat(indexInfo.size(), is(2)); - - List fields = indexInfo.get(0).getIndexFields(); - assertThat(fields.size(), is(1)); - assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC))); - - fields = indexInfo.get(1).getIndexFields(); - assertThat(fields.size(), is(1)); - assertThat(fields, hasItem(IndexField.geo("location"))); - } - - @Test // DATAMONGO-1110 - public void geoNearWithMinDistance() { - - NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).minDistance(1); - - GeoResults result = template.geoNear(geoNear, Venue.class); - - assertThat(result.getContent().size(), is(not(0))); - assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS)); - } - - @Test // DATAMONGO-1110 - public void nearSphereWithMinDistance() { - Point point = new Point(-73.99171, 40.738868); - List venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), Venue.class); - assertThat(venues.size(), is(1)); - } - - @Override - protected void createIndex() { - template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE)); - } - - @Override - protected void dropIndex() { - template.indexOps(Venue.class).dropIndex("location_2dsphere"); - } -} +/* + * Copyright 2010-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.data.mongodb.core.geo; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.springframework.data.mongodb.core.query.Criteria.*; +import static org.springframework.data.mongodb.core.query.Query.*; + +import java.util.List; + +import org.junit.Test; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.geo.GeoResults; +import org.springframework.data.geo.Metric; +import org.springframework.data.geo.Metrics; +import org.springframework.data.geo.Point; +import org.springframework.data.mongodb.core.IndexOperations; +import org.springframework.data.mongodb.core.Venue; +import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; +import org.springframework.data.mongodb.core.index.GeospatialIndex; +import org.springframework.data.mongodb.core.index.IndexField; +import org.springframework.data.mongodb.core.index.IndexInfo; +import org.springframework.data.mongodb.core.query.NearQuery; + +/** + * @author Christoph Strobl + */ +public class GeoSpatial2DSphereTests extends AbstractGeoSpatialTests { + + @Test // DATAMONGO-360 + public void indexInfoIsCorrect() { + + IndexOperations operations = template.indexOps(Venue.class); + List indexInfo = operations.getIndexInfo(); + + assertThat(indexInfo.size(), is(2)); + + List fields = indexInfo.get(0).getIndexFields(); + assertThat(fields.size(), is(1)); + assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC))); + + fields = indexInfo.get(1).getIndexFields(); + assertThat(fields.size(), is(1)); + assertThat(fields, hasItem(IndexField.geo("location"))); + } + + @Test // DATAMONGO-1110 + public void geoNearWithMinDistance() { + + NearQuery geoNear = NearQuery.near(-73, 40, Metrics.KILOMETERS).num(10).minDistance(1); + + GeoResults result = template.geoNear(geoNear, Venue.class); + + assertThat(result.getContent().size(), is(not(0))); + assertThat(result.getAverageDistance().getMetric(), is((Metric) Metrics.KILOMETERS)); + } + + @Test // DATAMONGO-1110 + public void nearSphereWithMinDistance() { + Point point = new Point(-73.99171, 40.738868); + List venues = template.find(query(where("location").nearSphere(point).minDistance(0.01)), Venue.class); + assertThat(venues.size(), is(1)); + } + + @Override + protected void createIndex() { + template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE)); + } + + @Override + protected void dropIndex() { + template.indexOps(Venue.class).dropIndex("location_2dsphere"); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DTests.java index 896871b34..d2455d067 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoSpatial2DTests.java @@ -1,79 +1,79 @@ -/* - * Copyright 2010-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.springframework.data.mongodb.core.geo; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; -import static org.springframework.data.mongodb.core.query.Criteria.*; -import static org.springframework.data.mongodb.core.query.Query.*; - -import java.util.List; - -import org.junit.Test; -import org.springframework.data.domain.Sort.Direction; -import org.springframework.data.geo.Point; -import org.springframework.data.mongodb.core.IndexOperations; -import org.springframework.data.mongodb.core.Venue; -import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; -import org.springframework.data.mongodb.core.index.GeospatialIndex; -import org.springframework.data.mongodb.core.index.IndexField; -import org.springframework.data.mongodb.core.index.IndexInfo; - -/** - * Modified from https://github.com/deftlabs/mongo-java-geospatial-example - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Thomas Darimont - * @author Christoph Strobl - */ -public class GeoSpatial2DTests extends AbstractGeoSpatialTests { - - @Test - public void nearPoint() { - Point point = new Point(-73.99171, 40.738868); - List venues = template.find(query(where("location").near(point).maxDistance(0.01)), Venue.class); - assertThat(venues.size(), is(7)); - } - - @Test // DATAMONGO-360 - public void indexInfoIsCorrect() { - - IndexOperations operations = template.indexOps(Venue.class); - List indexInfo = operations.getIndexInfo(); - - assertThat(indexInfo.size(), is(2)); - - List fields = indexInfo.get(0).getIndexFields(); - assertThat(fields.size(), is(1)); - assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC))); - - fields = indexInfo.get(1).getIndexFields(); - assertThat(fields.size(), is(1)); - assertThat(fields, hasItem(IndexField.geo("location"))); - } - - @Override - protected void createIndex() { - template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2D)); - } - - @Override - protected void dropIndex() { - template.indexOps(Venue.class).dropIndex("location_2d"); - } -} +/* + * Copyright 2010-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.springframework.data.mongodb.core.geo; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; +import static org.springframework.data.mongodb.core.query.Criteria.*; +import static org.springframework.data.mongodb.core.query.Query.*; + +import java.util.List; + +import org.junit.Test; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.geo.Point; +import org.springframework.data.mongodb.core.IndexOperations; +import org.springframework.data.mongodb.core.Venue; +import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; +import org.springframework.data.mongodb.core.index.GeospatialIndex; +import org.springframework.data.mongodb.core.index.IndexField; +import org.springframework.data.mongodb.core.index.IndexInfo; + +/** + * Modified from https://github.com/deftlabs/mongo-java-geospatial-example + * + * @author Mark Pollack + * @author Oliver Gierke + * @author Thomas Darimont + * @author Christoph Strobl + */ +public class GeoSpatial2DTests extends AbstractGeoSpatialTests { + + @Test + public void nearPoint() { + Point point = new Point(-73.99171, 40.738868); + List venues = template.find(query(where("location").near(point).maxDistance(0.01)), Venue.class); + assertThat(venues.size(), is(7)); + } + + @Test // DATAMONGO-360 + public void indexInfoIsCorrect() { + + IndexOperations operations = template.indexOps(Venue.class); + List indexInfo = operations.getIndexInfo(); + + assertThat(indexInfo.size(), is(2)); + + List fields = indexInfo.get(0).getIndexFields(); + assertThat(fields.size(), is(1)); + assertThat(fields, hasItem(IndexField.create("_id", Direction.ASC))); + + fields = indexInfo.get(1).getIndexFields(); + assertThat(fields.size(), is(1)); + assertThat(fields, hasItem(IndexField.geo("location"))); + } + + @Override + protected void createIndex() { + template.indexOps(Venue.class).ensureIndex(new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2D)); + } + + @Override + protected void dropIndex() { + template.indexOps(Venue.class).dropIndex("location_2d"); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java index 3c49752f6..04892b856 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/GeoIndexedAppConfig.java @@ -1,50 +1,50 @@ -/* - * Copyright 2011-2013 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core.mapping; - -import org.springframework.context.annotation.Bean; -import org.springframework.data.mongodb.config.AbstractMongoConfiguration; -import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener; - -import com.mongodb.Mongo; -import com.mongodb.MongoClient; - -public class GeoIndexedAppConfig extends AbstractMongoConfiguration { - - public static String GEO_DB = "database"; - public static String GEO_COLLECTION = "geolocation"; - - @Override - public String getDatabaseName() { - return GEO_DB; - } - - @Override - @Bean - public Mongo mongo() throws Exception { - return new MongoClient("127.0.0.1"); - } - - @Override - public String getMappingBasePackage() { - return "org.springframework.data.mongodb.core.core.mapping"; - } - - @Bean - public LoggingEventListener mappingEventsListener() { - return new LoggingEventListener(); - } -} +/* + * Copyright 2011-2013 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core.mapping; + +import org.springframework.context.annotation.Bean; +import org.springframework.data.mongodb.config.AbstractMongoConfiguration; +import org.springframework.data.mongodb.core.mapping.event.LoggingEventListener; + +import com.mongodb.Mongo; +import com.mongodb.MongoClient; + +public class GeoIndexedAppConfig extends AbstractMongoConfiguration { + + public static String GEO_DB = "database"; + public static String GEO_COLLECTION = "geolocation"; + + @Override + public String getDatabaseName() { + return GEO_DB; + } + + @Override + @Bean + public Mongo mongo() throws Exception { + return new MongoClient("127.0.0.1"); + } + + @Override + public String getMappingBasePackage() { + return "org.springframework.data.mongodb.core.core.mapping"; + } + + @Bean + public LoggingEventListener mappingEventsListener() { + return new LoggingEventListener(); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/CriteriaTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/CriteriaTests.java index f73fbfde1..06bb9b2ff 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/CriteriaTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/CriteriaTests.java @@ -1,219 +1,219 @@ -/* - * Copyright 2010-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core.query; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.springframework.data.mongodb.test.util.IsBsonObject.*; - -import org.junit.Test; -import org.springframework.data.geo.Point; -import org.springframework.data.mongodb.InvalidMongoDbApiUsageException; -import org.springframework.data.mongodb.core.geo.GeoJsonLineString; -import org.springframework.data.mongodb.core.geo.GeoJsonPoint; - -import com.mongodb.BasicDBObject; -import com.mongodb.BasicDBObjectBuilder; -import com.mongodb.DBObject; - -/** - * @author Oliver Gierke - * @author Thomas Darimont - * @author Christoph Strobl - */ -public class CriteriaTests { - - @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 testChainedCriteria() { - Criteria c = new Criteria("name").is("Bubba").and("age").lt(21); - assertEquals("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}", c.getCriteriaObject().toString()); - } - - @Test(expected = InvalidMongoDbApiUsageException.class) - public void testCriteriaWithMultipleConditionsForSameKey() { - Criteria c = new Criteria("name").gte("M").and("name").ne("A"); - c.getCriteriaObject(); - } - - @Test - public void equalIfCriteriaMatches() { - - Criteria left = new Criteria("name").is("Foo").and("lastname").is("Bar"); - Criteria right = new Criteria("name").is("Bar").and("lastname").is("Bar"); - - assertThat(left, is(not(right))); - assertThat(right, is(not(left))); - } - - @Test(expected = IllegalArgumentException.class) // DATAMONGO-507 - public void shouldThrowExceptionWhenTryingToNegateAndOperation() { - - new Criteria() // - .not() // - .andOperator(Criteria.where("delete").is(true).and("_id").is(42)); // - } - - @Test(expected = IllegalArgumentException.class) // DATAMONGO-507 - public void shouldThrowExceptionWhenTryingToNegateOrOperation() { - - new Criteria() // - .not() // - .orOperator(Criteria.where("delete").is(true).and("_id").is(42)); // - } - - @Test(expected = IllegalArgumentException.class) // DATAMONGO-507 - public void shouldThrowExceptionWhenTryingToNegateNorOperation() { - - new Criteria() // - .not() // - .norOperator(Criteria.where("delete").is(true).and("_id").is(42)); // - } - - @Test // DATAMONGO-507 - public void shouldNegateFollowingSimpleExpression() { - - Criteria c = Criteria.where("age").not().gt(18).and("status").is("student"); - DBObject co = c.getCriteriaObject(); - - assertThat(co, is(notNullValue())); - assertThat(co.toString(), is("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}")); - } - - @Test // DATAMONGO-1068 - public void getCriteriaObjectShouldReturnEmptyDBOWhenNoCriteriaSpecified() { - - DBObject dbo = new Criteria().getCriteriaObject(); - - assertThat(dbo, equalTo(new BasicDBObjectBuilder().get())); - } - - @Test // DATAMONGO-1068 - public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresent() { - - DBObject dbo = new Criteria().lt("foo").getCriteriaObject(); - - assertThat(dbo, equalTo(new BasicDBObjectBuilder().add("$lt", "foo").get())); - } - - @Test // DATAMONGO-1068 - public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresentButMultipleCriteriasPresent() { - - DBObject dbo = new Criteria().lt("foo").gt("bar").getCriteriaObject(); - - assertThat(dbo, equalTo(new BasicDBObjectBuilder().add("$lt", "foo").add("$gt", "bar").get())); - } - - @Test // DATAMONGO-1068 - public void getCriteriaObjectShouldRespectNotWhenNoKeyPresent() { - - DBObject dbo = new Criteria().lt("foo").not().getCriteriaObject(); - - assertThat(dbo, equalTo(new BasicDBObjectBuilder().add("$not", new BasicDBObject("$lt", "foo")).get())); - } - - @Test // DATAMONGO-1135 - public void geoJsonTypesShouldBeWrappedInGeometry() { - - DBObject dbo = new Criteria("foo").near(new GeoJsonPoint(100, 200)).getCriteriaObject(); - - assertThat(dbo, isBsonObject().containing("foo.$near.$geometry", new GeoJsonPoint(100, 200))); - } - - @Test // DATAMONGO-1135 - public void legacyCoordinateTypesShouldNotBeWrappedInGeometry() { - - DBObject dbo = new Criteria("foo").near(new Point(100, 200)).getCriteriaObject(); - - assertThat(dbo, isBsonObject().notContaining("foo.$near.$geometry")); - } - - @Test // DATAMONGO-1135 - public void maxDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() { - - DBObject dbo = new Criteria("foo").near(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject(); - - assertThat(dbo, isBsonObject().containing("foo.$near.$maxDistance", 50D)); - } - - @Test // DATAMONGO-1135 - public void maxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { - - DBObject dbo = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject(); - - assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$maxDistance", 50D)); - } - - @Test // DATAMONGO-1110 - public void minDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() { - - DBObject dbo = new Criteria("foo").near(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject(); - - assertThat(dbo, isBsonObject().containing("foo.$near.$minDistance", 50D)); - } - - @Test // DATAMONGO-1110 - public void minDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { - - DBObject dbo = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject(); - - assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D)); - } - - @Test // DATAMONGO-1110 - public void minAndMaxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { - - DBObject dbo = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).maxDistance(100D) - .getCriteriaObject(); - - assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D)); - assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$maxDistance", 100D)); - } - - @Test(expected = IllegalArgumentException.class) // DATAMONGO-1134 - public void intersectsShouldThrowExceptionWhenCalledWihtNullValue() { - new Criteria("foo").intersects(null); - } - - @Test // DATAMONGO-1134 - public void intersectsShouldWrapGeoJsonTypeInGeometryCorrectly() { - - GeoJsonLineString lineString = new GeoJsonLineString(new Point(0, 0), new Point(10, 10)); - DBObject dbo = new Criteria("foo").intersects(lineString).getCriteriaObject(); - - assertThat(dbo, isBsonObject().containing("foo.$geoIntersects.$geometry", lineString)); - } -} +/* + * Copyright 2010-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core.query; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; +import static org.springframework.data.mongodb.test.util.IsBsonObject.*; + +import org.junit.Test; +import org.springframework.data.geo.Point; +import org.springframework.data.mongodb.InvalidMongoDbApiUsageException; +import org.springframework.data.mongodb.core.geo.GeoJsonLineString; +import org.springframework.data.mongodb.core.geo.GeoJsonPoint; + +import com.mongodb.BasicDBObject; +import com.mongodb.BasicDBObjectBuilder; +import com.mongodb.DBObject; + +/** + * @author Oliver Gierke + * @author Thomas Darimont + * @author Christoph Strobl + */ +public class CriteriaTests { + + @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 testChainedCriteria() { + Criteria c = new Criteria("name").is("Bubba").and("age").lt(21); + assertEquals("{ \"name\" : \"Bubba\" , \"age\" : { \"$lt\" : 21}}", c.getCriteriaObject().toString()); + } + + @Test(expected = InvalidMongoDbApiUsageException.class) + public void testCriteriaWithMultipleConditionsForSameKey() { + Criteria c = new Criteria("name").gte("M").and("name").ne("A"); + c.getCriteriaObject(); + } + + @Test + public void equalIfCriteriaMatches() { + + Criteria left = new Criteria("name").is("Foo").and("lastname").is("Bar"); + Criteria right = new Criteria("name").is("Bar").and("lastname").is("Bar"); + + assertThat(left, is(not(right))); + assertThat(right, is(not(left))); + } + + @Test(expected = IllegalArgumentException.class) // DATAMONGO-507 + public void shouldThrowExceptionWhenTryingToNegateAndOperation() { + + new Criteria() // + .not() // + .andOperator(Criteria.where("delete").is(true).and("_id").is(42)); // + } + + @Test(expected = IllegalArgumentException.class) // DATAMONGO-507 + public void shouldThrowExceptionWhenTryingToNegateOrOperation() { + + new Criteria() // + .not() // + .orOperator(Criteria.where("delete").is(true).and("_id").is(42)); // + } + + @Test(expected = IllegalArgumentException.class) // DATAMONGO-507 + public void shouldThrowExceptionWhenTryingToNegateNorOperation() { + + new Criteria() // + .not() // + .norOperator(Criteria.where("delete").is(true).and("_id").is(42)); // + } + + @Test // DATAMONGO-507 + public void shouldNegateFollowingSimpleExpression() { + + Criteria c = Criteria.where("age").not().gt(18).and("status").is("student"); + DBObject co = c.getCriteriaObject(); + + assertThat(co, is(notNullValue())); + assertThat(co.toString(), is("{ \"age\" : { \"$not\" : { \"$gt\" : 18}} , \"status\" : \"student\"}")); + } + + @Test // DATAMONGO-1068 + public void getCriteriaObjectShouldReturnEmptyDBOWhenNoCriteriaSpecified() { + + DBObject dbo = new Criteria().getCriteriaObject(); + + assertThat(dbo, equalTo(new BasicDBObjectBuilder().get())); + } + + @Test // DATAMONGO-1068 + public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresent() { + + DBObject dbo = new Criteria().lt("foo").getCriteriaObject(); + + assertThat(dbo, equalTo(new BasicDBObjectBuilder().add("$lt", "foo").get())); + } + + @Test // DATAMONGO-1068 + public void getCriteriaObjectShouldUseCritieraValuesWhenNoKeyIsPresentButMultipleCriteriasPresent() { + + DBObject dbo = new Criteria().lt("foo").gt("bar").getCriteriaObject(); + + assertThat(dbo, equalTo(new BasicDBObjectBuilder().add("$lt", "foo").add("$gt", "bar").get())); + } + + @Test // DATAMONGO-1068 + public void getCriteriaObjectShouldRespectNotWhenNoKeyPresent() { + + DBObject dbo = new Criteria().lt("foo").not().getCriteriaObject(); + + assertThat(dbo, equalTo(new BasicDBObjectBuilder().add("$not", new BasicDBObject("$lt", "foo")).get())); + } + + @Test // DATAMONGO-1135 + public void geoJsonTypesShouldBeWrappedInGeometry() { + + DBObject dbo = new Criteria("foo").near(new GeoJsonPoint(100, 200)).getCriteriaObject(); + + assertThat(dbo, isBsonObject().containing("foo.$near.$geometry", new GeoJsonPoint(100, 200))); + } + + @Test // DATAMONGO-1135 + public void legacyCoordinateTypesShouldNotBeWrappedInGeometry() { + + DBObject dbo = new Criteria("foo").near(new Point(100, 200)).getCriteriaObject(); + + assertThat(dbo, isBsonObject().notContaining("foo.$near.$geometry")); + } + + @Test // DATAMONGO-1135 + public void maxDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() { + + DBObject dbo = new Criteria("foo").near(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject(); + + assertThat(dbo, isBsonObject().containing("foo.$near.$maxDistance", 50D)); + } + + @Test // DATAMONGO-1135 + public void maxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { + + DBObject dbo = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).maxDistance(50D).getCriteriaObject(); + + assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$maxDistance", 50D)); + } + + @Test // DATAMONGO-1110 + public void minDistanceShouldBeMappedInsideNearWhenUsedAlongWithGeoJsonType() { + + DBObject dbo = new Criteria("foo").near(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject(); + + assertThat(dbo, isBsonObject().containing("foo.$near.$minDistance", 50D)); + } + + @Test // DATAMONGO-1110 + public void minDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { + + DBObject dbo = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).getCriteriaObject(); + + assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D)); + } + + @Test // DATAMONGO-1110 + public void minAndMaxDistanceShouldBeMappedInsideNearSphereWhenUsedAlongWithGeoJsonType() { + + DBObject dbo = new Criteria("foo").nearSphere(new GeoJsonPoint(100, 200)).minDistance(50D).maxDistance(100D) + .getCriteriaObject(); + + assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$minDistance", 50D)); + assertThat(dbo, isBsonObject().containing("foo.$nearSphere.$maxDistance", 100D)); + } + + @Test(expected = IllegalArgumentException.class) // DATAMONGO-1134 + public void intersectsShouldThrowExceptionWhenCalledWihtNullValue() { + new Criteria("foo").intersects(null); + } + + @Test // DATAMONGO-1134 + public void intersectsShouldWrapGeoJsonTypeInGeometryCorrectly() { + + GeoJsonLineString lineString = new GeoJsonLineString(new Point(0, 0), new Point(10, 10)); + DBObject dbo = new Criteria("foo").intersects(lineString).getCriteriaObject(); + + assertThat(dbo, isBsonObject().containing("foo.$geoIntersects.$geometry", lineString)); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IndexUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IndexUnitTests.java index b4c7013f7..be93b8af6 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IndexUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/IndexUnitTests.java @@ -1,102 +1,102 @@ -/* - * Copyright 2010-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core.query; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - -import org.junit.Test; -import org.springframework.data.domain.Sort.Direction; -import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; -import org.springframework.data.mongodb.core.index.GeospatialIndex; -import org.springframework.data.mongodb.core.index.Index; -import org.springframework.data.mongodb.core.index.Index.Duplicates; - -/** - * Unit tests for {@link Index}. - * - * @author Oliver Gierke - * @author Laurent Canet - */ -public class IndexUnitTests { - - @Test - public void testWithAscendingIndex() { - Index i = new Index().on("name", Direction.ASC); - assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); - } - - @Test - public void testWithDescendingIndex() { - Index i = new Index().on("name", Direction.DESC); - assertEquals("{ \"name\" : -1}", i.getIndexKeys().toString()); - } - - @Test - public void testNamedMultiFieldUniqueIndex() { - Index i = new Index().on("name", Direction.ASC).on("age", Direction.DESC); - i.named("test").unique(); - assertEquals("{ \"name\" : 1 , \"age\" : -1}", i.getIndexKeys().toString()); - assertEquals("{ \"name\" : \"test\" , \"unique\" : true}", i.getIndexOptions().toString()); - } - - @Test - public void testWithDropDuplicates() { - Index i = new Index().on("name", Direction.ASC); - i.unique(Duplicates.DROP); - assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); - assertEquals("{ \"unique\" : true , \"dropDups\" : true}", i.getIndexOptions().toString()); - } - - @Test - public void testWithSparse() { - Index i = new Index().on("name", Direction.ASC); - i.sparse().unique(); - assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); - assertEquals("{ \"unique\" : true , \"sparse\" : true}", i.getIndexOptions().toString()); - } - - @Test - public void testGeospatialIndex() { - GeospatialIndex i = new GeospatialIndex("location").withMin(0); - assertEquals("{ \"location\" : \"2d\"}", i.getIndexKeys().toString()); - assertEquals("{ \"min\" : 0}", i.getIndexOptions().toString()); - } - - @Test // DATAMONGO-778 - public void testGeospatialIndex2DSphere() { - - GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE); - assertEquals("{ \"location\" : \"2dsphere\"}", i.getIndexKeys().toString()); - assertEquals("{ }", i.getIndexOptions().toString()); - } - - @Test // DATAMONGO-778 - public void testGeospatialIndexGeoHaystack() { - - GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_HAYSTACK) - .withAdditionalField("name").withBucketSize(40); - assertEquals("{ \"location\" : \"geoHaystack\" , \"name\" : 1}", i.getIndexKeys().toString()); - assertEquals("{ \"bucketSize\" : 40.0}", i.getIndexOptions().toString()); - } - - @Test - public void ensuresPropertyOrder() { - - Index on = new Index("foo", Direction.ASC).on("bar", Direction.ASC); - assertThat(on.getIndexKeys().toString(), is("{ \"foo\" : 1 , \"bar\" : 1}")); - } -} +/* + * Copyright 2010-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core.query; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import org.junit.Test; +import org.springframework.data.domain.Sort.Direction; +import org.springframework.data.mongodb.core.index.GeoSpatialIndexType; +import org.springframework.data.mongodb.core.index.GeospatialIndex; +import org.springframework.data.mongodb.core.index.Index; +import org.springframework.data.mongodb.core.index.Index.Duplicates; + +/** + * Unit tests for {@link Index}. + * + * @author Oliver Gierke + * @author Laurent Canet + */ +public class IndexUnitTests { + + @Test + public void testWithAscendingIndex() { + Index i = new Index().on("name", Direction.ASC); + assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); + } + + @Test + public void testWithDescendingIndex() { + Index i = new Index().on("name", Direction.DESC); + assertEquals("{ \"name\" : -1}", i.getIndexKeys().toString()); + } + + @Test + public void testNamedMultiFieldUniqueIndex() { + Index i = new Index().on("name", Direction.ASC).on("age", Direction.DESC); + i.named("test").unique(); + assertEquals("{ \"name\" : 1 , \"age\" : -1}", i.getIndexKeys().toString()); + assertEquals("{ \"name\" : \"test\" , \"unique\" : true}", i.getIndexOptions().toString()); + } + + @Test + public void testWithDropDuplicates() { + Index i = new Index().on("name", Direction.ASC); + i.unique(Duplicates.DROP); + assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); + assertEquals("{ \"unique\" : true , \"dropDups\" : true}", i.getIndexOptions().toString()); + } + + @Test + public void testWithSparse() { + Index i = new Index().on("name", Direction.ASC); + i.sparse().unique(); + assertEquals("{ \"name\" : 1}", i.getIndexKeys().toString()); + assertEquals("{ \"unique\" : true , \"sparse\" : true}", i.getIndexOptions().toString()); + } + + @Test + public void testGeospatialIndex() { + GeospatialIndex i = new GeospatialIndex("location").withMin(0); + assertEquals("{ \"location\" : \"2d\"}", i.getIndexKeys().toString()); + assertEquals("{ \"min\" : 0}", i.getIndexOptions().toString()); + } + + @Test // DATAMONGO-778 + public void testGeospatialIndex2DSphere() { + + GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_2DSPHERE); + assertEquals("{ \"location\" : \"2dsphere\"}", i.getIndexKeys().toString()); + assertEquals("{ }", i.getIndexOptions().toString()); + } + + @Test // DATAMONGO-778 + public void testGeospatialIndexGeoHaystack() { + + GeospatialIndex i = new GeospatialIndex("location").typed(GeoSpatialIndexType.GEO_HAYSTACK) + .withAdditionalField("name").withBucketSize(40); + assertEquals("{ \"location\" : \"geoHaystack\" , \"name\" : 1}", i.getIndexKeys().toString()); + assertEquals("{ \"bucketSize\" : 40.0}", i.getIndexOptions().toString()); + } + + @Test + public void ensuresPropertyOrder() { + + Index on = new Index("foo", Direction.ASC).on("bar", Direction.ASC); + assertThat(on.getIndexKeys().toString(), is("{ \"foo\" : 1 , \"bar\" : 1}")); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/SortTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/SortTests.java index 701193bd2..c0b5e7e4f 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/SortTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/query/SortTests.java @@ -1,50 +1,50 @@ -/* - * Copyright 2010-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.core.query; - -import static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - -import org.junit.Test; -import org.springframework.data.domain.Sort; -import org.springframework.data.domain.Sort.Direction; - -/** - * Unit tests for sorting. - * - * @author Oliver Gierke - */ -public class SortTests { - - @Test - public void testWithSortAscending() { - Query s = new Query().with(new Sort(Direction.ASC, "name")); - assertEquals("{ \"name\" : 1}", s.getSortObject().toString()); - } - - @Test - public void testWithSortDescending() { - Query s = new Query().with(new Sort(Direction.DESC, "name")); - assertEquals("{ \"name\" : -1}", s.getSortObject().toString()); - } - - @Test // DATADOC-177 - public void preservesOrderKeysOnMultipleSorts() { - - Query sort = new Query().with(new Sort(Direction.DESC, "foo").and(new Sort(Direction.DESC, "bar"))); - assertThat(sort.getSortObject().toString(), is("{ \"foo\" : -1 , \"bar\" : -1}")); - } -} +/* + * Copyright 2010-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.core.query; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import org.junit.Test; +import org.springframework.data.domain.Sort; +import org.springframework.data.domain.Sort.Direction; + +/** + * Unit tests for sorting. + * + * @author Oliver Gierke + */ +public class SortTests { + + @Test + public void testWithSortAscending() { + Query s = new Query().with(new Sort(Direction.ASC, "name")); + assertEquals("{ \"name\" : 1}", s.getSortObject().toString()); + } + + @Test + public void testWithSortDescending() { + Query s = new Query().with(new Sort(Direction.DESC, "name")); + assertEquals("{ \"name\" : -1}", s.getSortObject().toString()); + } + + @Test // DATADOC-177 + public void preservesOrderKeysOnMultipleSorts() { + + Query sort = new Query().with(new Sort(Direction.DESC, "foo").and(new Sort(Direction.DESC, "bar"))); + assertThat(sort.getSortObject().toString(), is("{ \"foo\" : -1 , \"bar\" : -1}")); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/monitor/MongoMonitorIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/monitor/MongoMonitorIntegrationTests.java index d9d6e66d6..f5537694d 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/monitor/MongoMonitorIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/monitor/MongoMonitorIntegrationTests.java @@ -1,71 +1,71 @@ -/* - * Copyright 2002-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.springframework.data.mongodb.monitor; - -import static org.hamcrest.Matchers.*; -import static org.junit.Assert.*; - -import java.net.UnknownHostException; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import com.mongodb.Mongo; - -/** - * This test class assumes that you are already running the MongoDB server. - * - * @author Mark Pollack - * @author Thomas Darimont - * @author Mark Paluch - */ -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration("classpath:infrastructure.xml") -public class MongoMonitorIntegrationTests { - - @Autowired Mongo mongo; - - @Test - public void serverInfo() { - ServerInfo serverInfo = new ServerInfo(mongo); - serverInfo.getVersion(); - } - - @Test // DATAMONGO-685 - public void getHostNameShouldReturnServerNameReportedByMongo() throws UnknownHostException { - - ServerInfo serverInfo = new ServerInfo(mongo); - - String hostName = null; - try { - hostName = serverInfo.getHostName(); - } catch (UnknownHostException e) { - throw e; - } - - assertThat(hostName, is(notNullValue())); - assertThat(hostName, is("127.0.0.1")); - } - - @Test - public void operationCounters() { - OperationCounters operationCounters = new OperationCounters(mongo); - operationCounters.getInsertCount(); - } -} +/* + * Copyright 2002-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.springframework.data.mongodb.monitor; + +import static org.hamcrest.Matchers.*; +import static org.junit.Assert.*; + +import java.net.UnknownHostException; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import com.mongodb.Mongo; + +/** + * This test class assumes that you are already running the MongoDB server. + * + * @author Mark Pollack + * @author Thomas Darimont + * @author Mark Paluch + */ +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration("classpath:infrastructure.xml") +public class MongoMonitorIntegrationTests { + + @Autowired Mongo mongo; + + @Test + public void serverInfo() { + ServerInfo serverInfo = new ServerInfo(mongo); + serverInfo.getVersion(); + } + + @Test // DATAMONGO-685 + public void getHostNameShouldReturnServerNameReportedByMongo() throws UnknownHostException { + + ServerInfo serverInfo = new ServerInfo(mongo); + + String hostName = null; + try { + hostName = serverInfo.getHostName(); + } catch (UnknownHostException e) { + throw e; + } + + assertThat(hostName, is(notNullValue())); + assertThat(hostName, is("127.0.0.1")); + } + + @Test + public void operationCounters() { + OperationCounters operationCounters = new OperationCounters(mongo); + operationCounters.getInsertCount(); + } +} diff --git a/spring-data-mongodb/src/test/resources/META-INF/beans.xml b/spring-data-mongodb/src/test/resources/META-INF/beans.xml index 73ae3a251..71dc6db1f 100644 --- a/spring-data-mongodb/src/test/resources/META-INF/beans.xml +++ b/spring-data-mongodb/src/test/resources/META-INF/beans.xml @@ -1,6 +1,6 @@ - - - - + + + +