From db9934c7d861e104546c8f262e63202ca1477c64 Mon Sep 17 00:00:00 2001 From: Christoph Strobl Date: Wed, 15 Mar 2017 14:55:57 +0100 Subject: [PATCH] DATAMONGO-1643 - Replace references to Mongo by MongoClient. Remove and replace usage of "mongo" by "mongoClient". This involves xsd schema, bean names, constructor and parameter types. This required some API changes as some server commands are no longer directly available through the api, but have to be invoked via runCommand. Also remove references to outdated API using Credentials and an authentication DB instead of MongoCredentials for authentication. Updated and removed (unused) tests; Altered documentation. Original pull request: #451. --- .../META-INF/spring/applicationContext.xml | 4 +- .../config/AbstractMongoConfiguration.java | 42 +-- .../data/mongodb/config/BeanNames.java | 5 +- .../mongodb/config/MongoDbFactoryParser.java | 31 +-- .../data/mongodb/config/MongoJmxParser.java | 11 +- .../mongodb/config/MongoNamespaceHandler.java | 3 +- .../data/mongodb/config/MongoParser.java | 76 ------ .../mongodb/config/MongoParsingUtils.java | 37 --- .../data/mongodb/core/MongoAdmin.java | 54 ++-- .../mongodb/core/MongoClientFactoryBean.java | 13 +- .../core/MongoClientOptionsFactoryBean.java | 2 + .../data/mongodb/core/MongoDbUtils.java | 216 --------------- .../data/mongodb/core/MongoFactoryBean.java | 199 -------------- .../mongodb/core/MongoOptionsFactoryBean.java | 255 ------------------ .../data/mongodb/core/MongoTemplate.java | 120 +-------- .../core/ReflectiveDBCollectionInvoker.java | 39 +-- .../mongodb/core/ReflectiveDbInvoker.java | 134 --------- .../core/ReflectiveMapReduceInvoker.java | 62 ----- .../core/ReflectiveMongoOptionsInvoker.java | 158 ----------- .../core/ReflectiveWriteConcernInvoker.java | 48 ---- .../core/ReflectiveWriteResultInvoker.java | 78 ------ .../mongodb/core/SimpleMongoDbFactory.java | 116 +------- .../mongodb/core/WriteResultChecking.java | 8 +- .../core/convert/DefaultDbRefResolver.java | 17 +- .../core/convert/ReflectiveDBRefResolver.java | 69 ----- .../data/mongodb/monitor/AbstractMonitor.java | 51 +--- .../data/mongodb/monitor/AssertMetrics.java | 10 +- .../monitor/BackgroundFlushingMetrics.java | 14 +- .../mongodb/monitor/BtreeIndexCounters.java | 14 +- .../mongodb/monitor/ConnectionMetrics.java | 12 +- .../mongodb/monitor/GlobalLockMetrics.java | 13 +- .../data/mongodb/monitor/MemoryMetrics.java | 10 +- .../mongodb/monitor/OperationCounters.java | 10 +- .../data/mongodb/monitor/ServerInfo.java | 8 +- .../data/mongodb/config/spring-mongo-2.0.xsd | 41 --- .../java/ConfigClassInDefaultPackage.java | 2 +- .../config/AbstractIntegrationTests.java | 4 +- .../AbstractMongoConfigurationUnitTests.java | 18 +- ...uditingViaJavaConfigRepositoriesTests.java | 4 +- .../MongoClientParserIntegrationTests.java | 4 +- .../MongoDbFactoryParserIntegrationTests.java | 51 ---- .../config/MongoNamespaceReplicaSetTests.java | 1 - .../mongodb/config/MongoNamespaceTests.java | 64 ++--- .../config/MongoParserIntegrationTests.java | 4 +- .../core/DefaultScriptOperationsTests.java | 4 +- .../core/MongoAdminIntegrationTests.java | 33 +-- .../core/MongoDbUtilsIntegrationTests.java | 170 ------------ .../mongodb/core/MongoDbUtilsUnitTests.java | 200 -------------- .../MongoFactoryBeanIntegrationTests.java | 68 ----- .../MongoOptionsFactoryBeanUnitTests.java | 19 +- .../data/mongodb/core/MongoTemplateTests.java | 8 +- .../mongodb/core/MongoTemplateUnitTests.java | 3 +- .../data/mongodb/core/NoExplicitIdTests.java | 2 +- .../mongodb/core/PersonExampleAppConfig.java | 4 +- ...ReflectiveMongoOptionsInvokerTestUtil.java | 52 ---- .../core/SimpleMongoDbFactoryUnitTests.java | 50 +--- .../mongodb/core/TestMongoConfiguration.java | 2 +- .../ReflectiveDBRefResolverUnitTests.java | 91 ------- .../core/geo/AbstractGeoSpatialTests.java | 2 +- .../data/mongodb/core/geo/GeoJsonTests.java | 2 +- .../core/mapping/GeoIndexedAppConfig.java | 2 +- ...ApplicationContextEventTestsAppConfig.java | 2 +- .../monitor/MongoMonitorIntegrationTests.java | 10 +- .../mongodb/performance/PerformanceTests.java | 2 +- .../ComplexIdRepositoryIntegrationTests.java | 2 +- ...oRepositoryTextSearchIntegrationTests.java | 2 +- .../src/test/resources/infrastructure.xml | 4 +- .../db-factory-bean-custom-write-concern.xml | 2 +- .../resources/namespace/db-factory-bean.xml | 2 +- .../test/resources/namespace/mongo-bean.xml | 2 +- .../mongo-client-uri-and-details.xml | 10 - ...o-client-uri-write-concern-and-details.xml | 10 - .../namespace/mongo-uri-and-details.xml | 10 - .../resources/namespace/mongo-uri-and-id.xml | 2 +- .../namespace/mongo-uri-no-credentials.xml | 2 +- .../mongo-uri-write-concern-and-details.xml | 2 +- .../test/resources/namespace/mongo-uri.xml | 10 - ...bFactoryNoDatabaseRunningTests-context.xml | 7 +- .../config/MongoNamespaceTests-context.xml | 46 ++-- ...tyIndexCreatorIntegrationTests-context.xml | 4 +- src/main/asciidoc/reference/cross-store.adoc | 4 +- src/main/asciidoc/reference/jmx.adoc | 2 +- src/main/asciidoc/reference/mapping.adoc | 10 +- .../reference/mongo-repositories.adoc | 4 +- src/main/asciidoc/reference/mongodb.adoc | 140 ++++------ .../asciidoc/reference/reactive-mongodb.adoc | 6 +- 86 files changed, 330 insertions(+), 2811 deletions(-) delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParser.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoDbUtils.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoFactoryBean.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBean.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDbInvoker.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMapReduceInvoker.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvoker.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteConcernInvoker.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteResultInvoker.java delete mode 100644 spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolver.java delete mode 100644 spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsIntegrationTests.java delete mode 100644 spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsUnitTests.java delete mode 100644 spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoFactoryBeanIntegrationTests.java delete mode 100644 spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvokerTestUtil.java delete mode 100644 spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolverUnitTests.java delete mode 100644 spring-data-mongodb/src/test/resources/namespace/mongo-client-uri-and-details.xml delete mode 100644 spring-data-mongodb/src/test/resources/namespace/mongo-client-uri-write-concern-and-details.xml delete mode 100644 spring-data-mongodb/src/test/resources/namespace/mongo-uri-and-details.xml delete mode 100644 spring-data-mongodb/src/test/resources/namespace/mongo-uri.xml diff --git a/spring-data-mongodb-cross-store/src/test/resources/META-INF/spring/applicationContext.xml b/spring-data-mongodb-cross-store/src/test/resources/META-INF/spring/applicationContext.xml index 587c05610..3fad886b0 100644 --- a/spring-data-mongodb-cross-store/src/test/resources/META-INF/spring/applicationContext.xml +++ b/spring-data-mongodb-cross-store/src/test/resources/META-INF/spring/applicationContext.xml @@ -20,13 +20,13 @@ - + - + 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 a72521ade..f6ccc1f90 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,5 +1,5 @@ /* - * Copyright 2011-2016 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package org.springframework.data.mongodb.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.data.authentication.UserCredentials; import org.springframework.data.mongodb.MongoDbFactory; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; @@ -26,7 +25,6 @@ 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 com.mongodb.Mongo; import com.mongodb.MongoClient; /** @@ -44,26 +42,13 @@ import com.mongodb.MongoClient; public abstract class AbstractMongoConfiguration extends MongoConfigurationSupport { /** - * 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 the {@link MongoClient} instance to connect to. Annotate with {@link Bean} in case you want to expose a + * {@link MongoClient} instance to the {@link org.springframework.context.ApplicationContext}. * * @return * @throws Exception */ - public abstract Mongo mongo() throws Exception; + public abstract MongoClient mongoClient() throws Exception; /** * Creates a {@link MongoTemplate}. @@ -77,8 +62,8 @@ public abstract class AbstractMongoConfiguration extends MongoConfigurationSuppo } /** - * Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link Mongo} instance - * configured in {@link #mongo()}. + * Creates a {@link SimpleMongoDbFactory} to be used by the {@link MongoTemplate}. Will use the {@link MongoClient} + * instance configured in {@link #mongo()}. * * @see #mongo() * @see #mongoTemplate() @@ -87,7 +72,7 @@ public abstract class AbstractMongoConfiguration extends MongoConfigurationSuppo */ @Bean public MongoDbFactory mongoDbFactory() throws Exception { - return new SimpleMongoDbFactory(mongo(), getDatabaseName(), getUserCredentials(), getAuthenticationDatabaseName()); + return new SimpleMongoDbFactory(mongoClient(), getDatabaseName()); } /** @@ -107,19 +92,6 @@ public abstract class AbstractMongoConfiguration extends MongoConfigurationSuppo return mappingBasePackage == null ? null : mappingBasePackage.getName(); } - /** - * 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 MappingMongoConverter} using the configured {@link #mongoDbFactory()} and * {@link #mongoMappingContext()}. Will get {@link #customConversions()} applied. diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/BeanNames.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/BeanNames.java index e3da27751..8761992e3 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/BeanNames.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/BeanNames.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2014 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,13 +21,14 @@ package org.springframework.data.mongodb.config; * @author Jon Brisbin * @author Oliver Gierke * @author Martin Baumgartner + * @author Christoph Strobl */ public abstract class BeanNames { public static final String MAPPING_CONTEXT_BEAN_NAME = "mongoMappingContext"; static final String INDEX_HELPER_BEAN_NAME = "indexCreationHelper"; - static final String MONGO_BEAN_NAME = "mongo"; + static final String MONGO_BEAN_NAME = "mongoClient"; static final String DB_FACTORY_BEAN_NAME = "mongoDbFactory"; static final String VALIDATING_EVENT_LISTENER_BEAN_NAME = "validatingMongoEventListener"; static final String IS_NEW_STRATEGY_FACTORY_BEAN_NAME = "isNewStrategyFactory"; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java index b2febd8fe..19baf1211 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoDbFactoryParser.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2015 by the original author(s). + * Copyright 2011-2017 by the original author(s). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +30,6 @@ import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.BeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; -import org.springframework.data.authentication.UserCredentials; import org.springframework.data.config.BeanComponentDefinitionBuilder; import org.springframework.data.mongodb.core.MongoClientFactoryBean; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; @@ -99,8 +98,6 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { String mongoRef = element.getAttribute("mongo-ref"); String dbname = element.getAttribute("dbname"); - BeanDefinition userCredentials = getUserCredentialsBeanDefinition(element, parserContext); - // Defaulting if (StringUtils.hasText(mongoRef)) { dbFactoryBuilder.addConstructorArgReference(mongoRef); @@ -109,8 +106,6 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { } dbFactoryBuilder.addConstructorArgValue(StringUtils.hasText(dbname) ? dbname : "db"); - dbFactoryBuilder.addConstructorArgValue(userCredentials); - dbFactoryBuilder.addConstructorArgValue(element.getAttribute("authentication-dbname")); BeanDefinitionBuilder writeConcernPropertyEditorBuilder = getWriteConcernPropertyEditorBuilder(); @@ -138,28 +133,6 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { return getSourceBeanDefinition(mongoBuilder, parserContext, element); } - /** - * Returns a {@link BeanDefinition} for a {@link UserCredentials} object. - * - * @param element - * @return the {@link BeanDefinition} or {@literal null} if neither username nor password given. - */ - private BeanDefinition getUserCredentialsBeanDefinition(Element element, ParserContext context) { - - String username = element.getAttribute("username"); - String password = element.getAttribute("password"); - - if (!StringUtils.hasText(username) && !StringUtils.hasText(password)) { - return null; - } - - BeanDefinitionBuilder userCredentialsBuilder = BeanDefinitionBuilder.genericBeanDefinition(UserCredentials.class); - userCredentialsBuilder.addConstructorArgValue(StringUtils.hasText(username) ? username : null); - userCredentialsBuilder.addConstructorArgValue(StringUtils.hasText(password) ? password : null); - - return getSourceBeanDefinition(userCredentialsBuilder, context, element); - } - /** * Creates a {@link BeanDefinition} for a {@link MongoURI} or {@link MongoClientURI} depending on configured * attributes.
@@ -193,7 +166,7 @@ public class MongoDbFactoryParser extends AbstractBeanDefinitionParser { parserContext.extractSource(element)); } - Class type = hasClientUri ? MongoClientURI.class : MongoURI.class; + Class type = MongoClientURI.class; String uri = hasClientUri ? element.getAttribute("client-uri") : element.getAttribute("uri"); BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(type); 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..0bfb398d9 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,5 +1,5 @@ /* - * Copyright 2011 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,12 +26,19 @@ import org.springframework.data.mongodb.monitor.*; import org.springframework.util.StringUtils; import org.w3c.dom.Element; +/** + * @author Mark Pollack + * @author Thomas Risberg + * @author John Brisbin + * @author Oliver Gierke + * @author Christoph Strobl + */ public class MongoJmxParser implements BeanDefinitionParser { public BeanDefinition parse(Element element, ParserContext parserContext) { String name = element.getAttribute("mongo-ref"); if (!StringUtils.hasText(name)) { - name = "mongo"; + name = BeanNames.MONGO_BEAN_NAME; } registerJmxComponents(name, element, parserContext); return null; diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoNamespaceHandler.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoNamespaceHandler.java index 377eedb44..72c9431aa 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoNamespaceHandler.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoNamespaceHandler.java @@ -1,5 +1,5 @@ /* - * Copyright 2011-2015 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,7 +33,6 @@ public class MongoNamespaceHandler extends NamespaceHandlerSupport { public void init() { registerBeanDefinitionParser("mapping-converter", new MappingMongoConverterParser()); - registerBeanDefinitionParser("mongo", new MongoParser()); registerBeanDefinitionParser("mongo-client", new MongoClientParser()); registerBeanDefinitionParser("db-factory", new MongoDbFactoryParser()); registerBeanDefinitionParser("jmx", new MongoJmxParser()); diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParser.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParser.java deleted file mode 100644 index 604214f26..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/config/MongoParser.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * 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.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.config.BeanComponentDefinitionBuilder; -import org.springframework.data.config.ParsingUtils; -import org.springframework.data.mongodb.core.MongoFactoryBean; -import org.springframework.util.StringUtils; -import org.w3c.dom.Element; - -/** - * Parser for <mongo;gt; definitions. - * - * @author Mark Pollack - * @author Oliver Gierke - * @author Christoph Strobl - */ -public class MongoParser implements BeanDefinitionParser { - - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.xml.BeanDefinitionParser#parse(org.w3c.dom.Element, org.springframework.beans.factory.xml.ParserContext) - */ - public BeanDefinition parse(Element element, ParserContext parserContext) { - - Object source = parserContext.extractSource(element); - String id = element.getAttribute("id"); - - BeanComponentDefinitionBuilder helper = new BeanComponentDefinitionBuilder(element, parserContext); - - BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(MongoFactoryBean.class); - ParsingUtils.setPropertyValue(builder, element, "port", "port"); - ParsingUtils.setPropertyValue(builder, element, "host", "host"); - ParsingUtils.setPropertyValue(builder, element, "write-concern", "writeConcern"); - - MongoParsingUtils.parseMongoOptions(element, builder); - MongoParsingUtils.parseReplicaSet(element, builder); - - String defaultedId = StringUtils.hasText(id) ? id : BeanNames.MONGO_BEAN_NAME; - - parserContext.pushContainingComponent(new CompositeComponentDefinition("Mongo", source)); - - BeanComponentDefinition mongoComponent = helper.getComponent(builder, defaultedId); - parserContext.registerBeanComponent(mongoComponent); - BeanComponentDefinition serverAddressPropertyEditor = helper.getComponent(MongoParsingUtils - .getServerAddressPropertyEditorBuilder()); - parserContext.registerBeanComponent(serverAddressPropertyEditor); - BeanComponentDefinition writeConcernPropertyEditor = helper.getComponent(MongoParsingUtils - .getWriteConcernPropertyEditorBuilder()); - parserContext.registerBeanComponent(writeConcernPropertyEditor); - - parserContext.popAndRegisterContainingComponent(); - - return mongoComponent.getBeanDefinition(); - } - -} 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..1821adad7 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 @@ -25,7 +25,6 @@ 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; @@ -54,42 +53,6 @@ abstract class MongoParsingUtils { 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. 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..745119d06 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 @@ -15,33 +15,30 @@ */ package org.springframework.data.mongodb.core; -import org.springframework.data.authentication.UserCredentials; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; +import org.bson.Document; 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 + * @author Christoph Strobl */ @ManagedResource(description = "Mongo Admin Operations") public class MongoAdmin implements MongoAdminOperations { - private final Mongo mongo; - private String username; - private String password; - private String authenticationDatabaseName; + private final MongoClient mongoClient; - public MongoAdmin(Mongo mongo) { + public MongoAdmin(MongoClient mongoClient) { - Assert.notNull(mongo, "Mongo must not be null!"); - this.mongo = mongo; + Assert.notNull(mongoClient, "MongoClient must not be null!"); + this.mongoClient = mongoClient; } /* (non-Javadoc) @@ -49,7 +46,7 @@ public class MongoAdmin implements MongoAdminOperations { */ @ManagedOperation public void dropDatabase(String databaseName) { - getDB(databaseName).dropDatabase(); + getDB(databaseName).drop(); } /* (non-Javadoc) @@ -65,37 +62,16 @@ public class MongoAdmin implements MongoAdminOperations { */ @ManagedOperation public String getDatabaseStats(String databaseName) { - return getDB(databaseName).getStats().toString(); + return getDB(databaseName).runCommand(new Document("dbStats", 1).append("scale" , 1024)).toJson(); } - /** - * 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; + @ManagedOperation + public String getServerStatus() { + return getDB("admin").runCommand(new Document("serverStatus", 1).append("rangeDeleter", 1).append("repl", 1)).toJson(); } - /** - * 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); + MongoDatabase getDB(String databaseName) { + return mongoClient.getDatabase(databaseName); } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java index 1b579774f..cea3784ff 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientFactoryBean.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import com.mongodb.Mongo; import com.mongodb.MongoClient; import com.mongodb.MongoClientOptions; import com.mongodb.MongoCredential; @@ -38,7 +37,7 @@ import com.mongodb.ServerAddress; * @author Christoph Strobl * @since 1.7 */ -public class MongoClientFactoryBean extends AbstractFactoryBean implements PersistenceExceptionTranslator { +public class MongoClientFactoryBean extends AbstractFactoryBean implements PersistenceExceptionTranslator { private static final PersistenceExceptionTranslator DEFAULT_EXCEPTION_TRANSLATOR = new MongoExceptionTranslator(); @@ -108,8 +107,8 @@ public class MongoClientFactoryBean extends AbstractFactoryBean implement * (non-Javadoc) * @see org.springframework.beans.factory.FactoryBean#getObjectType() */ - public Class getObjectType() { - return Mongo.class; + public Class getObjectType() { + return MongoClient.class; } /* @@ -125,7 +124,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean implement * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() */ @Override - protected Mongo createInstance() throws Exception { + protected MongoClient createInstance() throws Exception { if (mongoClientOptions == null) { mongoClientOptions = MongoClientOptions.builder().build(); @@ -143,7 +142,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean implement * @see org.springframework.beans.factory.config.AbstractFactoryBean#destroyInstance(java.lang.Object) */ @Override - protected void destroyInstance(Mongo instance) throws Exception { + protected void destroyInstance(MongoClient instance) throws Exception { instance.close(); } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java index e5c07c6c4..0e5f39c72 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoClientOptionsFactoryBean.java @@ -249,7 +249,9 @@ public class MongoClientOptionsFactoryBean extends AbstractFactoryBeannull) - * @return whether the DB is transactional - */ - public static boolean isDBTransactional(DB db, Mongo mongo) { - - if (mongo == null) { - return false; - } - DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo); - return dbHolder != null && dbHolder.containsDB(db); - } - - /** - * Perform actual closing of the Mongo DB object, catching and logging any cleanup exceptions thrown. - * - * @param db the DB to close (may be null) - * @deprecated since 1.7. The main use case for this method is to ensure that applications can read their own - * unacknowledged writes, but this is no longer so prevalent since the MongoDB Java driver version 3 - * started defaulting to acknowledged writes. - */ - @Deprecated - public static void closeDB(DB db) { - - if (db != null) { - LOGGER.debug("Closing Mongo DB object"); - try { - ReflectiveDbInvoker.requestDone(db); - } catch (Throwable ex) { - LOGGER.debug("Unexpected exception on closing Mongo DB object", ex); - } - } - } - - /** - * Check if credentials present. In case we're using a mongo-java-driver version 3 or above we do not have the need - * for authentication as the auth data has to be provided within the MongoClient - * - * @param credentials - * @return - */ - private static boolean requiresAuthDbAuthentication(UserCredentials credentials) { - - if (credentials == null || !credentials.hasUsername()) { - return false; - } - - return !MongoClientVersion.isMongo3Driver(); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoFactoryBean.java deleted file mode 100644 index 03107f611..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoFactoryBean.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2010-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.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.springframework.dao.DataAccessException; -import org.springframework.dao.support.PersistenceExceptionTranslator; -import org.springframework.data.mongodb.CannotGetMongoDbConnectionException; -import org.springframework.util.StringUtils; - -import com.mongodb.Mongo; -import com.mongodb.MongoOptions; -import com.mongodb.ServerAddress; -import com.mongodb.WriteConcern; - -/** - * Convenient factory for configuring MongoDB. - * - * @author Thomas Risberg - * @author Graeme Rocher - * @author Oliver Gierke - * @author Thomas Darimont - * @author Christoph Strobl - * @since 1.0 - * @deprecated since 1.7. Please use {@link MongoClientFactoryBean} instead. - */ -@Deprecated -public class MongoFactoryBean extends AbstractFactoryBean implements PersistenceExceptionTranslator { - - private static final PersistenceExceptionTranslator DEFAULT_EXCEPTION_TRANSLATOR = new MongoExceptionTranslator(); - - private MongoOptions mongoOptions; - private String host; - private Integer port; - private WriteConcern writeConcern; - private List replicaSetSeeds; - private List replicaPair; - private PersistenceExceptionTranslator exceptionTranslator = DEFAULT_EXCEPTION_TRANSLATOR; - - /** - * @param mongoOptions - */ - public void setMongoOptions(MongoOptions mongoOptions) { - this.mongoOptions = mongoOptions; - } - - public void setReplicaSetSeeds(ServerAddress[] replicaSetSeeds) { - this.replicaSetSeeds = filterNonNullElementsAsList(replicaSetSeeds); - } - - /** - * @deprecated use {@link #setReplicaSetSeeds(ServerAddress[])} instead - * @param replicaPair - */ - @Deprecated - public void setReplicaPair(ServerAddress[] replicaPair) { - this.replicaPair = filterNonNullElementsAsList(replicaPair); - } - - /** - * Configures the host to connect to. - * - * @param host - */ - public void setHost(String host) { - this.host = host; - } - - /** - * Configures the port to connect to. - * - * @param port - */ - public void setPort(int port) { - this.port = port; - } - - /** - * Sets the {@link WriteConcern} to be configured for the {@link Mongo} instance to be created. - * - * @param writeConcern - */ - public void setWriteConcern(WriteConcern writeConcern) { - this.writeConcern = writeConcern; - } - - /** - * Configures the {@link PersistenceExceptionTranslator} to use. - * - * @param exceptionTranslator can be {@literal null}. - */ - public void setExceptionTranslator(PersistenceExceptionTranslator exceptionTranslator) { - this.exceptionTranslator = exceptionTranslator == null ? DEFAULT_EXCEPTION_TRANSLATOR : exceptionTranslator; - } - - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.FactoryBean#getObjectType() - */ - public Class getObjectType() { - return Mongo.class; - } - - /* - * (non-Javadoc) - * @see org.springframework.dao.support.PersistenceExceptionTranslator#translateExceptionIfPossible(java.lang.RuntimeException) - */ - public DataAccessException translateExceptionIfPossible(RuntimeException ex) { - return exceptionTranslator.translateExceptionIfPossible(ex); - } - - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() - */ - @Override - protected Mongo createInstance() throws Exception { - - Mongo mongo; - ServerAddress defaultOptions = new ServerAddress(); - - if (mongoOptions == null) { - mongoOptions = new MongoOptions(); - } - - if (!isNullOrEmpty(replicaPair)) { - if (replicaPair.size() < 2) { - throw new CannotGetMongoDbConnectionException("A replica pair must have two server entries"); - } - mongo = new Mongo(replicaPair.get(0), replicaPair.get(1), mongoOptions); - } else if (!isNullOrEmpty(replicaSetSeeds)) { - mongo = new Mongo(replicaSetSeeds, mongoOptions); - } else { - String mongoHost = StringUtils.hasText(host) ? host : defaultOptions.getHost(); - mongo = port != null ? new Mongo(new ServerAddress(mongoHost, port), mongoOptions) : new Mongo(mongoHost, - mongoOptions); - } - - if (writeConcern != null) { - mongo.setWriteConcern(writeConcern); - } - - return mongo; - } - - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.config.AbstractFactoryBean#destroyInstance(java.lang.Object) - */ - @Override - protected void destroyInstance(Mongo mongo) throws Exception { - mongo.close(); - } - - private static boolean isNullOrEmpty(Collection elements) { - return elements == null || elements.isEmpty(); - } - - /** - * Returns the given array as {@link List} with all {@literal null} elements removed. - * - * @param elements the elements to filter - * @return a new unmodifiable {@link List#} from the given elements without nulls - */ - private static List filterNonNullElementsAsList(T[] elements) { - - if (elements == null) { - return Collections.emptyList(); - } - - List candidateElements = new ArrayList(); - - for (T element : elements) { - if (element != null) { - candidateElements.add(element); - } - } - - return Collections.unmodifiableList(candidateElements); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBean.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBean.java deleted file mode 100644 index c10335a03..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBean.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright 2010-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 javax.net.ssl.SSLSocketFactory; - -import org.springframework.beans.factory.config.AbstractFactoryBean; -import org.springframework.data.mongodb.util.MongoClientVersion; - -import com.mongodb.MongoOptions; - -/** - * A factory bean for construction of a {@link MongoOptions} instance. In case used with MongoDB Java driver version 3 - * porperties not suppprted by the driver will be ignored. - * - * @author Graeme Rocher - * @author Mark Pollack - * @author Mike Saavedra - * @author Thomas Darimont - * @author Christoph Strobl - * @deprecated since 1.7. Please use {@link MongoClientOptionsFactoryBean} instead. - */ -@Deprecated -public class MongoOptionsFactoryBean extends AbstractFactoryBean { - - private static final MongoOptions DEFAULT_MONGO_OPTIONS = new MongoOptions(); - - private int connectionsPerHost = DEFAULT_MONGO_OPTIONS.getConnectionsPerHost(); - private int threadsAllowedToBlockForConnectionMultiplier = DEFAULT_MONGO_OPTIONS - .getThreadsAllowedToBlockForConnectionMultiplier(); - private int maxWaitTime = DEFAULT_MONGO_OPTIONS.getMaxWaitTime(); - private int connectTimeout = DEFAULT_MONGO_OPTIONS.getConnectTimeout(); - private int socketTimeout = DEFAULT_MONGO_OPTIONS.getSocketTimeout(); - private boolean socketKeepAlive = DEFAULT_MONGO_OPTIONS.isSocketKeepAlive(); - private int writeNumber = DEFAULT_MONGO_OPTIONS.getW(); - private int writeTimeout = DEFAULT_MONGO_OPTIONS.getWtimeout(); - private boolean writeFsync = DEFAULT_MONGO_OPTIONS.isFsync(); - - private boolean autoConnectRetry = !MongoClientVersion.isMongo3Driver() ? ReflectiveMongoOptionsInvoker - .getAutoConnectRetry(DEFAULT_MONGO_OPTIONS) : false; - private long maxAutoConnectRetryTime = !MongoClientVersion.isMongo3Driver() ? ReflectiveMongoOptionsInvoker - .getMaxAutoConnectRetryTime(DEFAULT_MONGO_OPTIONS) : -1; - private boolean slaveOk = !MongoClientVersion.isMongo3Driver() ? ReflectiveMongoOptionsInvoker - .getSlaveOk(DEFAULT_MONGO_OPTIONS) : false; - - private boolean ssl; - private SSLSocketFactory sslSocketFactory; - - /** - * Configures the maximum number of connections allowed per host until we will block. - * - * @param connectionsPerHost - */ - public void setConnectionsPerHost(int connectionsPerHost) { - this.connectionsPerHost = connectionsPerHost; - } - - /** - * A multiplier for connectionsPerHost for # of threads that can block a connection. If connectionsPerHost is 10, and - * threadsAllowedToBlockForConnectionMultiplier is 5, then 50 threads can block. If more threads try to block an - * exception will be thrown. - * - * @param threadsAllowedToBlockForConnectionMultiplier - */ - public void setThreadsAllowedToBlockForConnectionMultiplier(int threadsAllowedToBlockForConnectionMultiplier) { - this.threadsAllowedToBlockForConnectionMultiplier = threadsAllowedToBlockForConnectionMultiplier; - } - - /** - * Max wait time of a blocking thread for a connection. - * - * @param maxWaitTime - */ - public void setMaxWaitTime(int maxWaitTime) { - this.maxWaitTime = maxWaitTime; - } - - /** - * Configures the connect timeout in milliseconds. Defaults to 0 (infinite time). - * - * @param connectTimeout - */ - public void setConnectTimeout(int connectTimeout) { - this.connectTimeout = connectTimeout; - } - - /** - * Configures the socket timeout. Defaults to 0 (infinite time). - * - * @param socketTimeout - */ - public void setSocketTimeout(int socketTimeout) { - this.socketTimeout = socketTimeout; - } - - /** - * Configures whether or not to have socket keep alive turned on (SO_KEEPALIVE). Defaults to {@literal false}. - * - * @param socketKeepAlive - */ - public void setSocketKeepAlive(boolean socketKeepAlive) { - this.socketKeepAlive = socketKeepAlive; - } - - /** - * This specifies the number of servers to wait for on the write operation, and exception raising behavior. The 'w' - * option to the getlasterror command. Defaults to 0. - *
    - *
  • -1 = don't even report network errors
  • - *
  • 0 = default, don't call getLastError by default
  • - *
  • 1 = basic, call getLastError, but don't wait for slaves
  • - *
  • 2 += wait for slaves
  • - *
- * - * @param writeNumber the number of servers to wait for on the write operation, and exception raising behavior. - */ - public void setWriteNumber(int writeNumber) { - this.writeNumber = writeNumber; - } - - /** - * Configures the timeout for write operations in milliseconds. This defaults to {@literal 0} (indefinite). - * - * @param writeTimeout - */ - public void setWriteTimeout(int writeTimeout) { - this.writeTimeout = writeTimeout; - } - - /** - * Configures whether or not to fsync. The 'fsync' option to the getlasterror command. Defaults to {@literal false}. - * - * @param writeFsync to fsync on write (true), otherwise {@literal false}. - */ - public void setWriteFsync(boolean writeFsync) { - this.writeFsync = writeFsync; - } - - /** - * Configures whether or not the system retries automatically on a failed connect. This defaults to {@literal false}. - * - * @deprecated since 1.7. - */ - @Deprecated - public void setAutoConnectRetry(boolean autoConnectRetry) { - this.autoConnectRetry = autoConnectRetry; - } - - /** - * Configures the maximum amount of time in millisecons to spend retrying to open connection to the same server. This - * defaults to {@literal 0}, which means to use the default {@literal 15s} if {@link #autoConnectRetry} is on. - * - * @param maxAutoConnectRetryTime the maxAutoConnectRetryTime to set - * @deprecated since 1.7 - */ - @Deprecated - public void setMaxAutoConnectRetryTime(long maxAutoConnectRetryTime) { - this.maxAutoConnectRetryTime = maxAutoConnectRetryTime; - } - - /** - * Specifies if the driver is allowed to read from secondaries or slaves. Defaults to {@literal false}. - * - * @param slaveOk true if the driver should read from secondaries or slaves. - * @deprecated since 1.7 - */ - @Deprecated - public void setSlaveOk(boolean slaveOk) { - this.slaveOk = slaveOk; - } - - /** - * Specifies if the driver should use an SSL connection to Mongo. This defaults to {@literal false}. By default - * {@link SSLSocketFactory#getDefault()} will be used. See {@link #setSslSocketFactory(SSLSocketFactory)} if you want - * to configure a custom factory. - * - * @param ssl true if the driver should use an SSL connection. - * @see #setSslSocketFactory(SSLSocketFactory) - */ - public void setSsl(boolean ssl) { - this.ssl = ssl; - } - - /** - * Specifies the {@link SSLSocketFactory} to use for creating SSL connections to Mongo. Defaults to - * {@link SSLSocketFactory#getDefault()}. Implicitly activates {@link #setSsl(boolean)} if a non-{@literal null} value - * is given. - * - * @param sslSocketFactory the sslSocketFactory to use. - * @see #setSsl(boolean) - */ - public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { - - setSsl(sslSocketFactory != null); - this.sslSocketFactory = sslSocketFactory; - } - - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.config.AbstractFactoryBean#createInstance() - */ - @Override - protected MongoOptions createInstance() throws Exception { - - if (MongoClientVersion.isMongo3Driver()) { - throw new IllegalArgumentException( - String - .format("Usage of 'mongo-options' is no longer supported for MongoDB Java driver version 3 and above. Please use 'mongo-client-options' and refer to chapter 'MongoDB 3.0 Support' for details.")); - } - - MongoOptions options = new MongoOptions(); - - options.setConnectionsPerHost(connectionsPerHost); - options.setThreadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier); - options.setMaxWaitTime(maxWaitTime); - options.setConnectTimeout(connectTimeout); - options.setSocketTimeout(socketTimeout); - options.setSocketKeepAlive(socketKeepAlive); - - options.setW(writeNumber); - options.setWtimeout(writeTimeout); - options.setFsync(writeFsync); - - if (ssl) { - options.setSocketFactory(sslSocketFactory != null ? sslSocketFactory : SSLSocketFactory.getDefault()); - } - - ReflectiveMongoOptionsInvoker.setAutoConnectRetry(options, autoConnectRetry); - ReflectiveMongoOptionsInvoker.setMaxAutoConnectRetryTime(options, maxAutoConnectRetryTime); - ReflectiveMongoOptionsInvoker.setSlaveOk(options, slaveOk); - - return options; - } - - /* - * (non-Javadoc) - * @see org.springframework.beans.factory.FactoryBean#getObjectType() - */ - public Class getObjectType() { - return MongoOptions.class; - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java index 9d6ccde59..5e36f8658 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/MongoTemplate.java @@ -20,19 +20,8 @@ import static org.springframework.data.mongodb.core.query.SerializationUtils.*; import static org.springframework.data.util.Optionals.*; import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.Optional; -import java.util.Scanner; -import java.util.Set; import java.util.concurrent.TimeUnit; import org.bson.Document; @@ -55,7 +44,6 @@ import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.OptimisticLockingFailureException; import org.springframework.dao.support.PersistenceExceptionTranslator; import org.springframework.data.annotation.Id; -import org.springframework.data.authentication.UserCredentials; import org.springframework.data.convert.EntityReader; import org.springframework.data.geo.Distance; import org.springframework.data.geo.GeoResult; @@ -115,15 +103,14 @@ import org.springframework.util.ObjectUtils; import org.springframework.util.ResourceUtils; import org.springframework.util.StringUtils; -import com.mongodb.CommandResult; import com.mongodb.Cursor; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.Mongo; +import com.mongodb.MongoClient; import com.mongodb.MongoException; import com.mongodb.ReadPreference; import com.mongodb.WriteConcern; -import com.mongodb.WriteResult; import com.mongodb.client.AggregateIterable; import com.mongodb.client.FindIterable; import com.mongodb.client.MapReduceIterable; @@ -193,28 +180,14 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, private ResourceLoader resourceLoader; private MongoPersistentEntityIndexCreator indexCreator; - private Mongo mongo; - /** * Constructor used for a basic template configuration * - * @param mongo must not be {@literal null}. + * @param mongoClient must not be {@literal null}. * @param databaseName must not be {@literal null} or empty. */ - public MongoTemplate(Mongo mongo, String databaseName) { - this(new SimpleMongoDbFactory(mongo, databaseName), null); - } - - /** - * Constructor used for a template configuration with user credentials in the form of - * {@link org.springframework.data.authentication.UserCredentials} - * - * @param mongo must not be {@literal null}. - * @param databaseName must not be {@literal null} or empty. - * @param userCredentials - */ - public MongoTemplate(Mongo mongo, String databaseName, UserCredentials userCredentials) { - this(new SimpleMongoDbFactory(mongo, databaseName, userCredentials)); + public MongoTemplate(MongoClient mongoClient, String databaseName) { + this(new SimpleMongoDbFactory(mongoClient, databaseName), null); } /** @@ -256,7 +229,7 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, /** * Configures the {@link WriteResultChecking} to be used with the template. Setting {@literal null} will reset the - * default of {@value #DEFAULT_WRITE_RESULT_CHECKING}. + * default of {@link #DEFAULT_WRITE_RESULT_CHECKING}. * * @param resultChecking */ @@ -285,8 +258,8 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } /** - * Used by @{link {@link #prepareCollection(DBCollection)} to set the {@link ReadPreference} before any operations are - * performed. + * Used by @{link {@link #prepareCollection(MongoCollection)} to set the {@link ReadPreference} before any operations + * are performed. * * @param readPreference */ @@ -426,15 +399,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, return result; } - protected void logCommandExecutionError(final Document command, CommandResult result) { - - String error = result.getErrorMessage(); - - if (error != null) { - LOGGER.warn("Command execution of {} failed: {}", command.toString(), error); - } - } - public void executeQuery(Query query, String collectionName, DocumentCallbackHandler dch) { executeQuery(query, collectionName, dch, new QueryCursorPreparer(query, null)); } @@ -2185,70 +2149,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, return mappingContext.getRequiredPersistentEntity(entityClass).getCollection(); } - /** - * Handles {@link WriteResult} errors based on the configured {@link WriteResultChecking}. - * - * @param writeResult - * @param query - * @param operation - */ - protected void handleAnyWriteResultErrors(WriteResult writeResult, Document query, MongoActionOperation operation) { - - if (writeResultChecking == WriteResultChecking.NONE) { - return; - } - - String error = ReflectiveWriteResultInvoker.getError(writeResult); - - if (error == null) { - return; - } - - String message; - - switch (operation) { - - case INSERT: - case SAVE: - message = String.format("Insert/Save for %s failed: %s", query, error); - break; - case INSERT_LIST: - message = String.format("Insert list failed: %s", error); - break; - default: - message = String.format("Execution of %s%s failed: %s", operation, - query == null ? "" : " using query " + query.toString(), error); - } - - if (writeResultChecking == WriteResultChecking.EXCEPTION) { - throw new MongoDataIntegrityViolationException(message, writeResult, operation); - } else { - LOGGER.error(message); - return; - } - } - - /** - * Inspects the given {@link CommandResult} for erros and potentially throws an - * {@link InvalidDataAccessApiUsageException} for that error. - * - * @param result must not be {@literal null}. - * @param source must not be {@literal null}. - */ - private void handleCommandError(CommandResult result, Document source) { - - try { - result.throwOnError(); - } catch (MongoException ex) { - - String error = result.getErrorMessage(); - error = error == null ? "NO MESSAGE" : error; - - throw new InvalidDataAccessApiUsageException( - "Command execution failed: Error [" + error + "], Command = " + source, ex); - } - } - private static final MongoConverter getDefaultMongoConverter(MongoDbFactory factory) { DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory); @@ -2700,10 +2600,6 @@ public class MongoTemplate implements MongoOperations, ApplicationContextAware, } } - public Mongo getMongo() { - return mongo; - } - public MongoDbFactory getMongoDbFactory() { return mongoDbFactory; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDBCollectionInvoker.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDBCollectionInvoker.java index 82cc401a3..ca1595f67 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDBCollectionInvoker.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDBCollectionInvoker.java @@ -1,5 +1,5 @@ /* - * Copyright 2015 the original author or authors. + * Copyright 2015-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -15,11 +15,6 @@ */ package org.springframework.data.mongodb.core; -import static org.springframework.data.mongodb.util.MongoClientVersion.*; -import static org.springframework.util.ReflectionUtils.*; - -import java.lang.reflect.Method; - import org.bson.Document; import org.springframework.data.mongodb.util.MongoClientVersion; @@ -35,15 +30,6 @@ import com.mongodb.DBCollection; */ class ReflectiveDBCollectionInvoker { - private static final Method GEN_INDEX_NAME_METHOD; - private static final Method RESET_INDEX_CHACHE_METHOD; - - static { - - GEN_INDEX_NAME_METHOD = findMethod(DBCollection.class, "genIndexName", Document.class); - RESET_INDEX_CHACHE_METHOD = findMethod(DBCollection.class, "resetIndexCache"); - } - private ReflectiveDBCollectionInvoker() {} /** @@ -54,28 +40,7 @@ class ReflectiveDBCollectionInvoker { * @return */ public static String generateIndexName(Document keys) { - - if (isMongo3Driver()) { - return genIndexName(keys); - } - return (String) invokeMethod(GEN_INDEX_NAME_METHOD, null, keys); - } - - /** - * In case of MongoDB Java driver version 2 all indices that have not yet been applied to this collection will be - * cleared. Since this method is not available for the MongoDB Java driver version 3 the operation will throw - * {@link UnsupportedOperationException}. - * - * @param dbCollection - * @throws UnsupportedOperationException - */ - public static void resetIndexCache(DBCollection dbCollection) { - - if (isMongo3Driver()) { - throw new UnsupportedOperationException("The mongo java driver 3 does no loger support resetIndexCache!"); - } - - invokeMethod(RESET_INDEX_CHACHE_METHOD, dbCollection); + return genIndexName(keys); } /** diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDbInvoker.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDbInvoker.java deleted file mode 100644 index 9a2280812..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveDbInvoker.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Copyright 2015-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.core; - -import static org.springframework.data.mongodb.util.MongoClientVersion.*; -import static org.springframework.util.ReflectionUtils.*; - -import java.lang.reflect.Method; - -import org.springframework.data.authentication.UserCredentials; -import org.springframework.data.mongodb.CannotGetMongoDbConnectionException; -import org.springframework.data.mongodb.util.MongoClientVersion; - -import com.mongodb.DB; -import com.mongodb.Mongo; - -/** - * {@link ReflectiveDbInvoker} provides reflective access to {@link DB} API that is not consistently available for - * various driver versions. - * - * @author Christoph Strobl - * @author Oliver Gierke - * @since 1.7 - */ -final class ReflectiveDbInvoker { - - private static final Method DB_IS_AUTHENTICATED_METHOD; - private static final Method DB_AUTHENTICATE_METHOD; - private static final Method DB_REQUEST_DONE_METHOD; - private static final Method DB_ADD_USER_METHOD; - private static final Method DB_REQUEST_START_METHOD; - - static { - - DB_IS_AUTHENTICATED_METHOD = findMethod(DB.class, "isAuthenticated"); - DB_AUTHENTICATE_METHOD = findMethod(DB.class, "authenticate", String.class, char[].class); - DB_REQUEST_DONE_METHOD = findMethod(DB.class, "requestDone"); - DB_ADD_USER_METHOD = findMethod(DB.class, "addUser", String.class, char[].class); - DB_REQUEST_START_METHOD = findMethod(DB.class, "requestStart"); - } - - private ReflectiveDbInvoker() {} - - /** - * Authenticate against database using provided credentials in case of a MongoDB Java driver version 2. - * - * @param mongo must not be {@literal null}. - * @param db must not be {@literal null}. - * @param credentials must not be {@literal null}. - * @param authenticationDatabaseName - */ - public static void authenticate(Mongo mongo, DB db, UserCredentials credentials, String authenticationDatabaseName) { - - String databaseName = db.getName(); - - DB authDb = databaseName.equals(authenticationDatabaseName) ? db : mongo.getDB(authenticationDatabaseName); - - synchronized (authDb) { - - Boolean isAuthenticated = (Boolean) invokeMethod(DB_IS_AUTHENTICATED_METHOD, authDb); - if (!isAuthenticated) { - - String username = credentials.getUsername(); - String password = credentials.hasPassword() ? credentials.getPassword() : null; - - Boolean authenticated = (Boolean) invokeMethod(DB_AUTHENTICATE_METHOD, authDb, username, - password == null ? null : password.toCharArray()); - if (!authenticated) { - throw new CannotGetMongoDbConnectionException("Failed to authenticate to database [" + databaseName + "], " - + credentials.toString(), databaseName, credentials); - } - } - } - } - - /** - * Starts a new 'consistent request' in case of MongoDB Java driver version 2. Will do nothing for MongoDB Java driver - * version 3 since the operation is no longer available. - * - * @param db - */ - public static void requestStart(DB db) { - - if (isMongo3Driver()) { - return; - } - - invokeMethod(DB_REQUEST_START_METHOD, db); - } - - /** - * Ends the current 'consistent request'. a new 'consistent request' in case of MongoDB Java driver version 2. Will do - * nothing for MongoDB Java driver version 3 since the operation is no longer available - * - * @param db - */ - public static void requestDone(DB db) { - - if (MongoClientVersion.isMongo3Driver()) { - return; - } - - invokeMethod(DB_REQUEST_DONE_METHOD, db); - } - - /** - * @param db - * @param username - * @param password - * @throws UnsupportedOperationException - */ - public static void addUser(DB db, String username, char[] password) { - - if (isMongo3Driver()) { - throw new UnsupportedOperationException( - "Please use DB.command(…) to call either the createUser or updateUser command!"); - } - - invokeMethod(DB_ADD_USER_METHOD, db, username, password); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMapReduceInvoker.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMapReduceInvoker.java deleted file mode 100644 index 014632613..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMapReduceInvoker.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 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 static org.springframework.data.mongodb.util.MongoClientVersion.*; -import static org.springframework.util.ReflectionUtils.*; - -import java.lang.reflect.Method; - -import org.springframework.util.Assert; - -import com.mongodb.MapReduceCommand; - -/** - * {@link ReflectiveMapReduceInvoker} provides reflective access to {@link MapReduceCommand} API that is not - * consistently available for various driver versions. - * - * @author Christoph Strobl - * @author Oliver Gierke - * @since 1.7 - */ -final class ReflectiveMapReduceInvoker { - - private static final Method ADD_EXTRA_OPTION_METHOD; - - static { - - ADD_EXTRA_OPTION_METHOD = findMethod(MapReduceCommand.class, "addExtraOption", String.class, Object.class); - } - - private ReflectiveMapReduceInvoker() {} - - /** - * Sets the extra option for MongoDB Java driver version 2. Will do nothing for MongoDB Java driver version 2. - * - * @param cmd can be {@literal null} for MongoDB Java driver version 2. - * @param key - * @param value - */ - public static void addExtraOption(MapReduceCommand cmd, String key, Object value) { - - if (isMongo3Driver()) { - return; - } - - Assert.notNull(cmd, "MapReduceCommand must not be null!"); - invokeMethod(ADD_EXTRA_OPTION_METHOD, cmd, key, value); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvoker.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvoker.java deleted file mode 100644 index 14f040e20..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvoker.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * Copyright 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 static org.springframework.data.mongodb.util.MongoClientVersion.*; -import static org.springframework.util.ReflectionUtils.*; - -import java.lang.reflect.Method; - -import org.springframework.beans.DirectFieldAccessor; -import org.springframework.util.ReflectionUtils; - -import com.mongodb.MongoOptions; - -/** - * {@link ReflectiveMongoOptionsInvoker} provides reflective access to {@link MongoOptions} API that is not consistently - * available for various driver versions. - * - * @author Christoph Strobl - * @author Oliver Gierke - * @since 1.7 - */ -@SuppressWarnings("deprecation") -class ReflectiveMongoOptionsInvoker { - - private static final Method GET_AUTO_CONNECT_RETRY_METHOD; - private static final Method SET_AUTO_CONNECT_RETRY_METHOD; - private static final Method GET_MAX_AUTO_CONNECT_RETRY_TIME_METHOD; - private static final Method SET_MAX_AUTO_CONNECT_RETRY_TIME_METHOD; - - static { - - SET_AUTO_CONNECT_RETRY_METHOD = ReflectionUtils - .findMethod(MongoOptions.class, "setAutoConnectRetry", boolean.class); - GET_AUTO_CONNECT_RETRY_METHOD = ReflectionUtils.findMethod(MongoOptions.class, "isAutoConnectRetry"); - SET_MAX_AUTO_CONNECT_RETRY_TIME_METHOD = ReflectionUtils.findMethod(MongoOptions.class, - "setMaxAutoConnectRetryTime", long.class); - GET_MAX_AUTO_CONNECT_RETRY_TIME_METHOD = ReflectionUtils.findMethod(MongoOptions.class, - "getMaxAutoConnectRetryTime"); - } - - private ReflectiveMongoOptionsInvoker() {} - - /** - * Sets the retry connection flag for MongoDB Java driver version 2. Will do nothing for MongoDB Java driver version 3 - * since the method has been removed. - * - * @param options can be {@literal null} for MongoDB Java driver version 3. - * @param autoConnectRetry - */ - public static void setAutoConnectRetry(MongoOptions options, boolean autoConnectRetry) { - - if (isMongo3Driver()) { - return; - } - - invokeMethod(SET_AUTO_CONNECT_RETRY_METHOD, options, autoConnectRetry); - } - - /** - * Sets the maxAutoConnectRetryTime attribute for MongoDB Java driver version 2. Will do nothing for MongoDB Java - * driver version 3 since the method has been removed. - * - * @param options can be {@literal null} for MongoDB Java driver version 3. - * @param maxAutoConnectRetryTime - */ - public static void setMaxAutoConnectRetryTime(MongoOptions options, long maxAutoConnectRetryTime) { - - if (isMongo3Driver()) { - return; - } - - invokeMethod(SET_MAX_AUTO_CONNECT_RETRY_TIME_METHOD, options, maxAutoConnectRetryTime); - } - - /** - * Sets the slaveOk attribute for MongoDB Java driver version 2. Will do nothing for MongoDB Java driver version 3 - * since the method has been removed. - * - * @param options can be {@literal null} for MongoDB Java driver version 3. - * @param slaveOk - */ - public static void setSlaveOk(MongoOptions options, boolean slaveOk) { - - if (isMongo3Driver()) { - return; - } - - new DirectFieldAccessor(options).setPropertyValue("slaveOk", slaveOk); - } - - /** - * Gets the slaveOk attribute for MongoDB Java driver version 2. Throws {@link UnsupportedOperationException} for - * MongoDB Java driver version 3 since the method has been removed. - * - * @param options can be {@literal null} for MongoDB Java driver version 3. - * @return - * @throws UnsupportedOperationException - */ - public static boolean getSlaveOk(MongoOptions options) { - - if (isMongo3Driver()) { - throw new UnsupportedOperationException( - "Cannot get value for autoConnectRetry which has been removed in MongoDB Java driver version 3."); - } - - return ((Boolean) new DirectFieldAccessor(options).getPropertyValue("slaveOk")).booleanValue(); - } - - /** - * Gets the autoConnectRetry attribute for MongoDB Java driver version 2. Throws {@link UnsupportedOperationException} - * for MongoDB Java driver version 3 since the method has been removed. - * - * @param options can be {@literal null} for MongoDB Java driver version 3. - * @return - * @throws UnsupportedOperationException - */ - public static boolean getAutoConnectRetry(MongoOptions options) { - - if (isMongo3Driver()) { - throw new UnsupportedOperationException( - "Cannot get value for autoConnectRetry which has been removed in MongoDB Java driver version 3."); - } - - return ((Boolean) invokeMethod(GET_AUTO_CONNECT_RETRY_METHOD, options)).booleanValue(); - } - - /** - * Gets the maxAutoConnectRetryTime attribute for MongoDB Java driver version 2. Throws - * {@link UnsupportedOperationException} for MongoDB Java driver version 3 since the method has been removed. - * - * @param options can be {@literal null} for MongoDB Java driver version 3. - * @return - * @throws UnsupportedOperationException - */ - public static long getMaxAutoConnectRetryTime(MongoOptions options) { - - if (isMongo3Driver()) { - throw new UnsupportedOperationException( - "Cannot get value for maxAutoConnectRetryTime which has been removed in MongoDB Java driver version 3."); - } - - return ((Long) invokeMethod(GET_MAX_AUTO_CONNECT_RETRY_TIME_METHOD, options)).longValue(); - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteConcernInvoker.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteConcernInvoker.java deleted file mode 100644 index 49abdf60f..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteConcernInvoker.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright 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 static org.springframework.data.mongodb.util.MongoClientVersion.*; - -import org.springframework.beans.DirectFieldAccessor; - -import com.mongodb.WriteConcern; - -/** - * {@link ReflectiveWriteConcernInvoker} provides reflective access to {@link WriteConcern} API that is not consistently - * available for various driver versions. - * - * @author Christoph Strobl - * @author Oliver Gierke - * @since 1.7 - */ -class ReflectiveWriteConcernInvoker { - - private static final WriteConcern NONE_OR_UNACKNOWLEDGED; - - static { - - NONE_OR_UNACKNOWLEDGED = isMongo3Driver() ? WriteConcern.UNACKNOWLEDGED : (WriteConcern) new DirectFieldAccessor( - new WriteConcern()).getPropertyValue("NONE"); - } - - /** - * @return {@link WriteConcern#NONE} for MongoDB Java driver version 2, otherwise {@link WriteConcern#UNACKNOWLEDGED}. - */ - public static WriteConcern noneOrUnacknowledged() { - return NONE_OR_UNACKNOWLEDGED; - } -} diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteResultInvoker.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteResultInvoker.java deleted file mode 100644 index c572e5279..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/ReflectiveWriteResultInvoker.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 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 static org.springframework.data.mongodb.util.MongoClientVersion.*; -import static org.springframework.util.ReflectionUtils.*; - -import java.lang.reflect.Method; - -import com.mongodb.MongoException; -import com.mongodb.WriteResult; -import com.mongodb.client.result.UpdateResult; - -/** - * {@link ReflectiveWriteResultInvoker} provides reflective access to {@link WriteResult} API that is not consistently - * available for various driver versions. - * - * @author Christoph Strobl - * @author Oliver Gierke - * @since 1.7 - */ -final class ReflectiveWriteResultInvoker { - - private static final Method GET_ERROR_METHOD; - private static final Method WAS_ACKNOWLEDGED_METHOD; - private static final Method WAS_ACKNOWLEDGED_METHOD_UR; - - private ReflectiveWriteResultInvoker() {} - - static { - - GET_ERROR_METHOD = findMethod(WriteResult.class, "getError"); - WAS_ACKNOWLEDGED_METHOD = findMethod(WriteResult.class, "wasAcknowledged"); - WAS_ACKNOWLEDGED_METHOD_UR = findMethod(UpdateResult.class, "wasAcknowledged"); - } - - /** - * @param writeResult can be {@literal null} for MongoDB Java driver version 3. - * @return null in case of MongoDB Java driver version 3 since errors are thrown as {@link MongoException}. - */ - public static String getError(WriteResult writeResult) { - - if (isMongo3Driver()) { - return null; - } - - return (String) invokeMethod(GET_ERROR_METHOD, writeResult); - } - - /** - * @param writeResult - * @return return in case of MongoDB Java driver version 2. - */ - public static boolean wasAcknowledged(WriteResult writeResult) { - return isMongo3Driver() ? ((Boolean) invokeMethod(WAS_ACKNOWLEDGED_METHOD, writeResult)).booleanValue() : true; - } - - /** - * @param writeResult - * @return return in case of MongoDB Java driver version 2. - */ - public static boolean wasAcknowledged(UpdateResult writeResult) { - return isMongo3Driver() ? ((Boolean) invokeMethod(WAS_ACKNOWLEDGED_METHOD_UR, writeResult)).booleanValue() : true; - } -} 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 53583e9bc..c1b89fcea 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,5 +1,5 @@ /* - * Copyright 2011-2016 the original author or authors. + * Copyright 2011-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,24 +19,18 @@ 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; import com.mongodb.client.MongoDatabase; /** - * Factory to create {@link DB} instances from a {@link Mongo} instance. + * Factory to create {@link DB} instances from a {@link MongoClient} instance. * * @author Mark Pollack * @author Oliver Gierke @@ -45,70 +39,13 @@ import com.mongodb.client.MongoDatabase; */ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { - private final Mongo mongo; + private final MongoClient mongoClient; 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}. * @@ -116,7 +53,7 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { * @throws UnknownHostException * @since 1.7 */ - public SimpleMongoDbFactory(MongoClientURI uri) throws UnknownHostException { + public SimpleMongoDbFactory(MongoClientURI uri) { this(new MongoClient(uri), uri.getDatabase(), true); } @@ -131,48 +68,23 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { 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) { + private SimpleMongoDbFactory(MongoClient mongoClient, String databaseName, boolean mongoInstanceCreated) { - Assert.notNull(client, "MongoClient must not be null!"); + Assert.notNull(mongoClient, "MongoClient 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 = client; + this.mongoClient = mongoClient; this.databaseName = databaseName; this.mongoInstanceCreated = mongoInstanceCreated; this.exceptionTranslator = new MongoExceptionTranslator(); - this.credentials = UserCredentials.NO_CREDENTIALS; - this.authenticationDatabaseName = databaseName; } /** @@ -200,7 +112,7 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { Assert.hasText(dbName, "Database name must not be empty."); - MongoDatabase db = ((MongoClient) mongo).getDatabase(dbName); + MongoDatabase db = mongoClient.getDatabase(dbName); if (writeConcern == null) { return db; @@ -216,14 +128,10 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { */ public void destroy() throws Exception { if (mongoInstanceCreated) { - mongo.close(); + mongoClient.close(); } } - private static String parseChars(char[] chars) { - return chars == null ? null : String.valueOf(chars); - } - /* * (non-Javadoc) * @see org.springframework.data.mongodb.MongoDbFactory#getExceptionTranslator() @@ -236,6 +144,6 @@ public class SimpleMongoDbFactory implements DisposableBean, MongoDbFactory { @SuppressWarnings("deprecation") @Override public DB getLegacyDb() { - return mongo.getDB(databaseName); + return mongoClient.getDB(databaseName); } } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/WriteResultChecking.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/WriteResultChecking.java index 9d4e4b5b3..5e327ab31 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/WriteResultChecking.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/WriteResultChecking.java @@ -1,5 +1,5 @@ /* - * Copyright 2012 the original author or authors. + * Copyright 2012-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,12 +17,12 @@ package org.springframework.data.mongodb.core; /** * Enum to represent how strict the check of {@link com.mongodb.WriteResult} shall be. It can either be skipped entirely - * (use {@link #NONE}), or errors can be logged ({@link #LOG}) or cause an exception to be thrown {@link #EXCEPTION}. - * + * (use {@link #NONE}) or cause an exception to be thrown {@link #EXCEPTION}. + * * @author Thomas Risberg * @author Oliver Gierke */ public enum WriteResultChecking { - NONE, LOG, EXCEPTION + NONE, EXCEPTION } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java index 175d3cc41..68f03be88 100644 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java +++ b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/DefaultDbRefResolver.java @@ -1,5 +1,5 @@ /* - * Copyright 2013-2016 the original author or authors. + * Copyright 2013-2017 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -46,9 +46,11 @@ import org.springframework.data.mongodb.core.mapping.MongoPersistentProperty; import org.springframework.objenesis.ObjenesisStd; import org.springframework.util.Assert; import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; import com.mongodb.DBRef; import com.mongodb.client.MongoDatabase; +import com.mongodb.client.model.Filters; /** * A {@link DbRefResolver} that resolves {@link org.springframework.data.mongodb.core.mapping.DBRef}s by delegating to a @@ -105,6 +107,11 @@ public class DefaultDbRefResolver implements DbRefResolver { @Override public DBRef createDbRef(org.springframework.data.mongodb.core.mapping.DBRef annotation, MongoPersistentEntity entity, Object id) { + + if (annotation != null && StringUtils.hasText(annotation.db())) { + return new DBRef(annotation.db(), entity.getCollection(), id); + } + return new DBRef(entity.getCollection(), id); } @@ -114,7 +121,11 @@ public class DefaultDbRefResolver implements DbRefResolver { */ @Override public Document fetch(DBRef dbRef) { - return ReflectiveDBRefResolver.fetch(mongoDbFactory, dbRef); + + StringUtils.hasText(dbRef.getDatabaseName()); + return (StringUtils.hasText(dbRef.getDatabaseName()) ? mongoDbFactory.getDb(dbRef.getDatabaseName()) + : mongoDbFactory.getDb()).getCollection(dbRef.getCollectionName(), Document.class) + .find(Filters.eq("_id", dbRef.getId())).first(); } /* @@ -147,7 +158,7 @@ public class DefaultDbRefResolver implements DbRefResolver { MongoDatabase db = mongoDbFactory.getDb(); List result = new ArrayList<>(); db.getCollection(collection).find(new Document("_id", new Document("$in", ids))).into(result); - Collections.sort(result, new DbRefByReferencePositionComparator(ids)); + result.sort(new DbRefByReferencePositionComparator(ids)); return result; } diff --git a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolver.java b/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolver.java deleted file mode 100644 index 4b9733891..000000000 --- a/spring-data-mongodb/src/main/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolver.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2015-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.core.convert; - -import static org.springframework.data.mongodb.util.MongoClientVersion.*; -import static org.springframework.util.ReflectionUtils.*; - -import java.lang.reflect.Method; - -import org.bson.Document; -import org.springframework.data.mongodb.MongoDbFactory; -import org.springframework.util.Assert; - -import com.mongodb.DBCollection; -import com.mongodb.DBRef; -import com.mongodb.client.model.Filters; - -/** - * {@link ReflectiveDBRefResolver} provides reflective access to {@link DBRef} API that is not consistently available - * for various driver versions. - * - * @author Christoph Strobl - * @author Oliver Gierke - * @since 1.7 - */ -class ReflectiveDBRefResolver { - - private static final Method FETCH_METHOD; - - static { - FETCH_METHOD = findMethod(DBRef.class, "fetch"); - } - - /** - * Fetches the object referenced from the database either be directly calling {@link DBRef#fetch()} or - * {@link DBCollection#findOne(Object)}. - * - * @param db can be {@literal null} when using MongoDB Java driver in version 2.x. - * @param ref must not be {@literal null}. - * @return the document that this references. - */ - public static Document fetch(MongoDbFactory factory, DBRef ref) { - - Assert.notNull(ref, "DBRef to fetch must not be null!"); - - if (isMongo3Driver()) { - - Assert.notNull(factory, "DbFactory to fetch DB from must not be null!"); - - return factory.getDb().getCollection(ref.getCollectionName(), Document.class).find(Filters.eq("_id", ref.getId())) - .first(); - } - - return (Document) invokeMethod(FETCH_METHOD, ref); - } -} 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..68462dd68 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,5 +1,5 @@ /* - * Copyright 2002-2015 the original author or authors. + * 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. @@ -15,58 +15,35 @@ */ 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 org.bson.Document; -import com.mongodb.CommandResult; -import com.mongodb.DB; -import com.mongodb.Mongo; -import com.mongodb.MongoException; +import com.mongodb.MongoClient; +import com.mongodb.client.MongoDatabase; /** * Base class to encapsulate common configuration settings when connecting to a database * * @author Mark Pollack * @author Oliver Gierke + * @author Christoph Strobl */ public abstract class AbstractMonitor { - private final Logger logger = LoggerFactory.getLogger(getClass()); + private final MongoClient mongoClient; - 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; + protected AbstractMonitor(MongoClient mongoClient) { + this.mongoClient = mongoClient; } - /** - * 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 Document getServerStatus() { + return getDb("admin").runCommand(new Document("serverStatus", 1).append("rangeDeleter", 1).append("repl", 1)); } - 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 MongoDatabase getDb(String databaseName) { + return mongoClient.getDatabase(databaseName); } - public DB getDb(String databaseName) { - return MongoDbUtils.getDB(mongo, databaseName, new UserCredentials(username, password)); + protected MongoClient getMongoClient() { + return mongoClient; } } 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 72d108aa6..32cec841d 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,5 +1,5 @@ /* - * Copyright 2002-2016 the original author or authors. + * 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. @@ -15,6 +15,8 @@ */ package org.springframework.data.mongodb.monitor; +import com.mongodb.MongoClient; +import org.bson.Document; import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; @@ -30,8 +32,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Assertion Metrics") public class AssertMetrics extends AbstractMonitor { - public AssertMetrics(Mongo mongo) { - this.mongo = mongo; + public AssertMetrics(MongoClient mongoClient) { + super(mongoClient); } @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Regular") @@ -60,7 +62,7 @@ public class AssertMetrics extends AbstractMonitor { } private int getBtree(String key) { - DBObject asserts = (DBObject) getServerStatus().get("asserts"); + Document asserts = (Document) 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 4cb27f6d5..6c6435018 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,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -17,12 +17,12 @@ package org.springframework.data.mongodb.monitor; import java.util.Date; +import org.bson.Document; import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; -import com.mongodb.DBObject; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * JMX Metrics for Background Flushing @@ -32,8 +32,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Background Flushing Metrics") public class BackgroundFlushingMetrics extends AbstractMonitor { - public BackgroundFlushingMetrics(Mongo mongo) { - this.mongo = mongo; + public BackgroundFlushingMetrics(MongoClient mongoClient) { + super(mongoClient); } @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Flushes") @@ -63,12 +63,12 @@ public class BackgroundFlushingMetrics extends AbstractMonitor { @SuppressWarnings("unchecked") private T getFlushingData(String key, Class targetClass) { - DBObject mem = (DBObject) getServerStatus().get("backgroundFlushing"); + Document mem = (Document) getServerStatus().get("backgroundFlushing"); return (T) mem.get(key); } private Date getLast() { - DBObject bgFlush = (DBObject) getServerStatus().get("backgroundFlushing"); + Document bgFlush = (Document) 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 eae91cf84..2f4068222 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,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -15,12 +15,12 @@ */ package org.springframework.data.mongodb.monitor; +import org.bson.Document; import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; -import com.mongodb.DBObject; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * JMX Metrics for B-tree index counters @@ -30,8 +30,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Btree Metrics") public class BtreeIndexCounters extends AbstractMonitor { - public BtreeIndexCounters(Mongo mongo) { - this.mongo = mongo; + public BtreeIndexCounters(MongoClient mongoClient) { + super(mongoClient); } @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Accesses") @@ -60,14 +60,14 @@ public class BtreeIndexCounters extends AbstractMonitor { } private int getBtree(String key) { - DBObject indexCounters = (DBObject) getServerStatus().get("indexCounters"); + Document indexCounters = (Document) 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"); + Document btree = (Document) 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 08a606af6..6f7153375 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,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -15,12 +15,12 @@ */ package org.springframework.data.mongodb.monitor; +import org.bson.Document; import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; -import com.mongodb.DBObject; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * JMX Metrics for Connections @@ -30,8 +30,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Connection metrics") public class ConnectionMetrics extends AbstractMonitor { - public ConnectionMetrics(Mongo mongo) { - this.mongo = mongo; + public ConnectionMetrics(MongoClient mongoClient) { + super(mongoClient); } @ManagedMetric(metricType = MetricType.GAUGE, displayName = "Current Connections") @@ -46,7 +46,7 @@ public class ConnectionMetrics extends AbstractMonitor { @SuppressWarnings("unchecked") private T getConnectionData(String key, Class targetClass) { - DBObject mem = (DBObject) getServerStatus().get("connections"); + Document mem = (Document) 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 cb2ccc5f8..0ca8a5742 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,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -15,12 +15,13 @@ */ package org.springframework.data.mongodb.monitor; +import org.bson.Document; import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; import com.mongodb.DBObject; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * JMX Metrics for Global Locks @@ -30,8 +31,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Global Lock Metrics") public class GlobalLockMetrics extends AbstractMonitor { - public GlobalLockMetrics(Mongo mongo) { - this.mongo = mongo; + public GlobalLockMetrics(MongoClient mongoClient) { + super(mongoClient); } @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Total time") @@ -71,8 +72,8 @@ public class GlobalLockMetrics extends AbstractMonitor { } private int getCurrentQueue(String key) { - DBObject globalLock = (DBObject) getServerStatus().get("globalLock"); - DBObject currentQueue = (DBObject) globalLock.get("currentQueue"); + Document globalLock = (Document) getServerStatus().get("globalLock"); + Document currentQueue = (Document) 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 a07002b38..42a884fcd 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 @@ -15,12 +15,12 @@ */ package org.springframework.data.mongodb.monitor; +import org.bson.Document; import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; -import com.mongodb.DBObject; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * JMX Metrics for Memory @@ -30,8 +30,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Memory Metrics") public class MemoryMetrics extends AbstractMonitor { - public MemoryMetrics(Mongo mongo) { - this.mongo = mongo; + public MemoryMetrics(MongoClient mongoClient) { + super(mongoClient); } @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Memory address size") @@ -61,7 +61,7 @@ public class MemoryMetrics extends AbstractMonitor { @SuppressWarnings("unchecked") private T getMemData(String key, Class targetClass) { - DBObject mem = (DBObject) getServerStatus().get("mem"); + Document mem = (Document) 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 5aa15598b..49d48a162 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 @@ -15,12 +15,12 @@ */ package org.springframework.data.mongodb.monitor; +import org.bson.Document; import org.springframework.jmx.export.annotation.ManagedMetric; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; -import com.mongodb.DBObject; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * JMX Metrics for Operation counters @@ -30,8 +30,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Operation Counters") public class OperationCounters extends AbstractMonitor { - public OperationCounters(Mongo mongo) { - this.mongo = mongo; + public OperationCounters(MongoClient mongoClient) { + super(mongoClient); } @ManagedMetric(metricType = MetricType.COUNTER, displayName = "Insert operation count") @@ -65,7 +65,7 @@ public class OperationCounters extends AbstractMonitor { } private int getOpCounter(String key) { - DBObject opCounters = (DBObject) getServerStatus().get("opcounters"); + Document opCounters = (Document) 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..b531654f5 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 @@ -22,7 +22,7 @@ import org.springframework.jmx.export.annotation.ManagedOperation; import org.springframework.jmx.export.annotation.ManagedResource; import org.springframework.jmx.support.MetricType; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * Expose basic server information via JMX @@ -34,8 +34,8 @@ import com.mongodb.Mongo; @ManagedResource(description = "Server Information") public class ServerInfo extends AbstractMonitor { - public ServerInfo(Mongo mongo) { - this.mongo = mongo; + public ServerInfo(MongoClient mongoClient) { + super(mongoClient); } /** @@ -51,7 +51,7 @@ public class ServerInfo extends AbstractMonitor { * UnknownHostException is not necessary anymore, but clients could have * called this method in a try..catch(UnknownHostException) already */ - return mongo.getAddress().getHost(); + return getMongoClient().getAddress().getHost(); } @ManagedMetric(displayName = "Uptime Estimate") diff --git a/spring-data-mongodb/src/main/resources/org/springframework/data/mongodb/config/spring-mongo-2.0.xsd b/spring-data-mongodb/src/main/resources/org/springframework/data/mongodb/config/spring-mongo-2.0.xsd index 51689b3c9..bca922e1c 100644 --- a/spring-data-mongodb/src/main/resources/org/springframework/data/mongodb/config/spring-mongo-2.0.xsd +++ b/spring-data-mongodb/src/main/resources/org/springframework/data/mongodb/config/spring-mongo-2.0.xsd @@ -56,47 +56,6 @@ The name of the database to connect to. Default is 'db'. ]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - values = definition.getPropertyValues().getPropertyValueList(); @@ -63,7 +63,7 @@ public class MongoParserIntegrationTests { assertThat(x.getPropertyValues().getPropertyValueList(), hasItem(new PropertyValue("writeConcern", "SAFE"))); - factory.getBean("mongo"); + factory.getBean("mongoClient"); } @Test // DATAMONGO-343 diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsTests.java index c88c49910..23bef3d7e 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/DefaultScriptOperationsTests.java @@ -55,13 +55,13 @@ public class DefaultScriptOperationsTests { private static final String DB_NAME = "script-tests"; @Bean - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient(); } @Bean public MongoTemplate template() throws Exception { - return new MongoTemplate(mongo(), DB_NAME); + return new MongoTemplate(mongoClient(), DB_NAME); } } 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..6611d9540 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,5 +1,5 @@ /* - * Copyright 2002-2011 the original author or authors. + * 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. @@ -15,9 +15,6 @@ */ 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; @@ -27,6 +24,9 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; +import com.mongodb.DB; +import com.mongodb.MongoClient; + /** * This test class assumes that you are already running the MongoDB server. * @@ -36,25 +36,26 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @ContextConfiguration("classpath:infrastructure.xml") public class MongoAdminIntegrationTests { - private static final Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class); + private static final Log logger = LogFactory.getLog(MongoAdminIntegrationTests.class); - @SuppressWarnings("unused") - private DB testAdminDb; + @SuppressWarnings("unused") private DB testAdminDb; - @Autowired - Mongo mongo; + @Autowired MongoClient mongoClient; + + MongoAdmin mongoAdmin; @Before public void setUp() { - mongo.getDB("testAdminDb").dropDatabase(); - testAdminDb = mongo.getDB("testAdminDb"); - + mongoAdmin = new MongoAdmin(mongoClient); } @Test public void serverStats() { - // CommandResult result = testAdminDb.getStats(); - CommandResult result = mongo.getDB("admin").command("serverStatus"); - logger.info("stats = " + result); + logger.info("stats = " + mongoAdmin.getServerStatus()); } -} \ No newline at end of file + + @Test + public void datanaseStats() { + logger.info(mongoAdmin.getDatabaseStats("testAdminDb")); + } +} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsIntegrationTests.java deleted file mode 100644 index ae73cdeef..000000000 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsIntegrationTests.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * Copyright 2012-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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 static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.junit.Assume.*; -import static org.springframework.data.mongodb.util.MongoClientVersion.*; - -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; - -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; -import org.springframework.dao.DataAccessException; -import org.springframework.data.authentication.UserCredentials; -import org.springframework.scheduling.concurrent.ThreadPoolExecutorFactoryBean; - -import com.mongodb.DB; -import com.mongodb.Mongo; -import com.mongodb.MongoClient; -import com.mongodb.MongoException; -import com.mongodb.client.MongoDatabase; - -/** - * Integration tests for {@link MongoDbUtils}. - * - * @author Oliver Gierke - * @author Thomas Darimont - * @author Christoph Strobl - */ -public class MongoDbUtilsIntegrationTests { - - static final String AUTHENTICATION_DATABASE_NAME = "admin"; - static final String DATABASE_NAME = "dbAuthTests"; - static final UserCredentials CREDENTIALS = new UserCredentials("admin", "admin"); - - static Mongo mongo; - static MongoTemplate template; - static ThreadPoolExecutorFactoryBean factory; - static ExecutorService service; - - Exception exception; - - @BeforeClass - public static void setUp() throws Exception { - - mongo = new MongoClient(); - template = new MongoTemplate(mongo, DATABASE_NAME); - - factory = new ThreadPoolExecutorFactoryBean(); - factory.setCorePoolSize(2); - factory.setMaxPoolSize(10); - factory.setWaitForTasksToCompleteOnShutdown(true); - factory.afterPropertiesSet(); - - service = factory.getObject(); - - assumeFalse(isMongo3Driver()); - } - - @AfterClass - public static void tearDown() { - - factory.destroy(); - - // Remove test database - - template.execute(new DbCallback() { - public Void doInDB(MongoDatabase db) throws MongoException, DataAccessException { - db.drop(); - return null; - } - }); - } - - @Test // DATAMONGO-585 - public void authenticatesCorrectlyInMultithreadedEnvironment() throws Exception { - - // Create sample user - template.execute(new DbCallback() { - public Void doInDB(MongoDatabase db) throws MongoException, DataAccessException { - - // ReflectiveDbInvoker.addUser(db, "admin", "admin".toCharArray()); - return null; - } - }); - - Callable callable = new Callable() { - public Void call() throws Exception { - - try { - DB db = MongoDbUtils.getDB(mongo, DATABASE_NAME, CREDENTIALS); - assertThat(db, is(notNullValue())); - } catch (Exception o_O) { - MongoDbUtilsIntegrationTests.this.exception = o_O; - } - - return null; - } - }; - - List> callables = new ArrayList>(); - - for (int i = 0; i < 10; i++) { - callables.add(callable); - } - - service.invokeAll(callables); - - if (exception != null) { - fail("Exception occurred!" + exception); - } - } - - @Test // DATAMONGO-789 - public void authenticatesCorrectlyWithAuthenticationDB() throws Exception { - - // Create sample user - template.execute(new DbCallback() { - public Void doInDB(MongoDatabase db) throws MongoException, DataAccessException { - - // ReflectiveDbInvoker.addUser(db.getSisterDB("admin"), "admin", "admin".toCharArray()); - return null; - } - }); - - Callable callable = new Callable() { - public Void call() throws Exception { - - try { - DB db = MongoDbUtils.getDB(mongo, DATABASE_NAME, CREDENTIALS, AUTHENTICATION_DATABASE_NAME); - assertThat(db, is(notNullValue())); - } catch (Exception o_O) { - MongoDbUtilsIntegrationTests.this.exception = o_O; - } - - return null; - } - }; - - List> callables = new ArrayList>(); - - for (int i = 0; i < 10; i++) { - callables.add(callable); - } - - service.invokeAll(callables); - - if (exception != null) { - fail("Exception occurred!" + exception); - } - } -} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsUnitTests.java deleted file mode 100644 index 5bc812a23..000000000 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoDbUtilsUnitTests.java +++ /dev/null @@ -1,200 +0,0 @@ -/* - * Copyright 2012-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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 static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; -import static org.junit.Assume.*; -import static org.mockito.Mockito.*; - -import java.util.List; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.data.authentication.UserCredentials; -import org.springframework.data.mongodb.CannotGetMongoDbConnectionException; -import org.springframework.data.mongodb.util.MongoClientVersion; -import org.springframework.transaction.support.TransactionSynchronization; -import org.springframework.transaction.support.TransactionSynchronizationManager; -import org.springframework.transaction.support.TransactionSynchronizationUtils; - -import com.mongodb.DB; -import com.mongodb.Mongo; -import com.mongodb.MongoClient; - -/** - * Unit tests for {@link MongoDbUtils}. - * - * @author Oliver Gierke - * @author Randy Watler - * @author Christoph Strobl - */ -@RunWith(MockitoJUnitRunner.class) -public class MongoDbUtilsUnitTests { - - @Mock Mongo mongo; - @Mock MongoClient mongoClientMock; - @Mock DB dbMock; - - @Before - public void setUp() throws Exception { - - when(mongo.getDB(anyString())).thenReturn(dbMock).thenReturn(mock(DB.class)); - when(mongoClientMock.getDB(anyString())).thenReturn(dbMock); - - TransactionSynchronizationManager.initSynchronization(); - } - - @After - public void tearDown() { - - for (Object key : TransactionSynchronizationManager.getResourceMap().keySet()) { - TransactionSynchronizationManager.unbindResource(key); - } - - TransactionSynchronizationManager.clearSynchronization(); - } - - @Test - public void returnsNewInstanceForDifferentDatabaseName() { - - DB first = MongoDbUtils.getDB(mongo, "first"); - DB second = MongoDbUtils.getDB(mongo, "second"); - assertThat(second, is(not(first))); - } - - @Test - public void returnsSameInstanceForSameDatabaseName() { - - DB first = MongoDbUtils.getDB(mongo, "first"); - assertThat(first, is(notNullValue())); - assertThat(MongoDbUtils.getDB(mongo, "first"), is(sameInstance(first))); - } - - @Test // DATAMONGO-737 - public void handlesTransactionSynchronizationLifecycle() { - - // ensure transaction synchronization manager has no registered - // transaction synchronizations or bound resources at start of test - assertThat(TransactionSynchronizationManager.getSynchronizations().isEmpty(), is(true)); - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty(), is(true)); - - // access database for one mongo instance, (registers transaction - // synchronization and binds transaction resource) - MongoDbUtils.getDB(mongo, "first"); - - // ensure transaction synchronization manager has registered - // transaction synchronizations and bound resources - assertThat(TransactionSynchronizationManager.getSynchronizations().isEmpty(), is(false)); - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty(), is(false)); - - // simulate transaction completion, (unbinds transaction resource) - try { - simulateTransactionCompletion(); - } catch (Exception e) { - fail("Unexpected exception thrown during transaction completion: " + e); - } - - // ensure transaction synchronization manager has no bound resources - // at end of test - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty(), is(true)); - } - - @Test // DATAMONGO-737 - public void handlesTransactionSynchronizationsLifecycle() { - - // ensure transaction synchronization manager has no registered - // transaction synchronizations or bound resources at start of test - assertThat(TransactionSynchronizationManager.getSynchronizations().isEmpty(), is(true)); - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty(), is(true)); - - // access multiple databases for one mongo instance, (registers - // transaction synchronizations and binds transaction resources) - MongoDbUtils.getDB(mongo, "first"); - MongoDbUtils.getDB(mongo, "second"); - - // ensure transaction synchronization manager has registered - // transaction synchronizations and bound resources - assertThat(TransactionSynchronizationManager.getSynchronizations().isEmpty(), is(false)); - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty(), is(false)); - - // simulate transaction completion, (unbinds transaction resources) - try { - simulateTransactionCompletion(); - } catch (Exception e) { - fail("Unexpected exception thrown during transaction completion: " + e); - } - - // ensure transaction synchronization manager has no bound - // transaction resources at end of test - assertThat(TransactionSynchronizationManager.getResourceMap().isEmpty(), is(true)); - } - - @Test // DATAMONGO-1218 - @SuppressWarnings("deprecation") - public void getDBDAuthenticateViaAuthDbWhenCalledWithMongoInstance() { - - assumeThat(MongoClientVersion.isMongo3Driver(), is(false)); - - when(dbMock.getName()).thenReturn("db"); - - try { - MongoDbUtils.getDB(mongo, "db", new UserCredentials("shallan", "davar"), "authdb"); - } catch (CannotGetMongoDbConnectionException e) { - // need to catch that one since we cannot answer the reflective call sufficiently - } - - verify(mongo, times(1)).getDB("authdb"); - } - - @Test // DATAMONGO-1218 - @SuppressWarnings("deprecation") - public void getDBDShouldSkipAuthenticationViaAuthDbWhenCalledWithMongoClientInstance() { - - MongoDbUtils.getDB(mongoClientMock, "db", new UserCredentials("dalinar", "kholin"), "authdb"); - - verify(mongoClientMock, never()).getDB("authdb"); - } - - /** - * Simulate transaction rollback/commit completion protocol on managed transaction synchronizations which will unbind - * managed transaction resources. Does not swallow exceptions for testing purposes. - * - * @see TransactionSynchronizationUtils#triggerBeforeCompletion() - * @see TransactionSynchronizationUtils#triggerAfterCompletion(int) - */ - private void simulateTransactionCompletion() { - - // triggerBeforeCompletion() implementation without swallowed exceptions - List synchronizations = TransactionSynchronizationManager.getSynchronizations(); - for (TransactionSynchronization synchronization : synchronizations) { - synchronization.beforeCompletion(); - } - - // triggerAfterCompletion() implementation without swallowed exceptions - List remainingSynchronizations = TransactionSynchronizationManager - .getSynchronizations(); - if (remainingSynchronizations != null) { - for (TransactionSynchronization remainingSynchronization : remainingSynchronizations) { - remainingSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK); - } - } - } -} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoFactoryBeanIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoFactoryBeanIntegrationTests.java deleted file mode 100644 index f31205b39..000000000 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoFactoryBeanIntegrationTests.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2012-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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 static org.hamcrest.CoreMatchers.*; -import static org.junit.Assert.*; - -import org.junit.Test; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.beans.factory.support.RootBeanDefinition; -import org.springframework.data.mongodb.config.ServerAddressPropertyEditor; -import org.springframework.data.mongodb.config.WriteConcernPropertyEditor; -import org.springframework.test.util.ReflectionTestUtils; - -import com.mongodb.Mongo; -import com.mongodb.ServerAddress; -import com.mongodb.WriteConcern; - -/** - * Integration tests for {@link MongoFactoryBean}. - * - * @author Oliver Gierke - * @author Thomas Darimont - */ -public class MongoFactoryBeanIntegrationTests { - - @Test // DATAMONGO-408 - public void convertsWriteConcernCorrectly() { - - RootBeanDefinition definition = new RootBeanDefinition(MongoFactoryBean.class); - definition.getPropertyValues().addPropertyValue("writeConcern", "SAFE"); - - DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); - factory.registerCustomEditor(WriteConcern.class, WriteConcernPropertyEditor.class); - factory.registerBeanDefinition("factory", definition); - - MongoFactoryBean bean = factory.getBean("&factory", MongoFactoryBean.class); - assertThat(ReflectionTestUtils.getField(bean, "writeConcern"), is((Object) WriteConcern.SAFE)); - } - - @Test // DATAMONGO-693 - public void createMongoInstanceWithHostAndEmptyReplicaSets() { - - RootBeanDefinition definition = new RootBeanDefinition(MongoFactoryBean.class); - definition.getPropertyValues().addPropertyValue("host", "localhost"); - definition.getPropertyValues().addPropertyValue("replicaPair", ""); - - DefaultListableBeanFactory factory = new DefaultListableBeanFactory(); - factory.registerCustomEditor(ServerAddress.class, ServerAddressPropertyEditor.class); - factory.registerBeanDefinition("factory", definition); - - Mongo mongo = factory.getBean(Mongo.class); - assertNotNull(mongo); - } -} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBeanUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBeanUnitTests.java index c490ec567..0dd3b18f6 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBeanUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoOptionsFactoryBeanUnitTests.java @@ -15,10 +15,8 @@ */ package org.springframework.data.mongodb.core; -import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.*; import static org.junit.Assume.*; -import static org.springframework.data.mongodb.core.ReflectiveMongoOptionsInvoker.*; import static org.springframework.data.mongodb.util.MongoClientVersion.*; import javax.net.ssl.SSLSocketFactory; @@ -26,7 +24,7 @@ import javax.net.ssl.SSLSocketFactory; import org.junit.BeforeClass; import org.junit.Test; -import com.mongodb.MongoOptions; +import com.mongodb.MongoClientOptions; /** * Unit tests for {@link MongoOptionsFactoryBean}. @@ -43,25 +41,14 @@ public class MongoOptionsFactoryBeanUnitTests { assumeFalse(isMongo3Driver()); } - @Test // DATADOC-280 - public void setsMaxConnectRetryTime() throws Exception { - - MongoOptionsFactoryBean bean = new MongoOptionsFactoryBean(); - bean.setMaxAutoConnectRetryTime(27); - bean.afterPropertiesSet(); - - MongoOptions options = bean.getObject(); - assertThat(getMaxAutoConnectRetryTime(options), is(27L)); - } - @Test // DATAMONGO-764 public void testSslConnection() throws Exception { - MongoOptionsFactoryBean bean = new MongoOptionsFactoryBean(); + MongoClientOptionsFactoryBean bean = new MongoClientOptionsFactoryBean(); bean.setSsl(true); bean.afterPropertiesSet(); - MongoOptions options = bean.getObject(); + MongoClientOptions options = bean.getObject(); assertNotNull(options.getSocketFactory()); assertTrue(options.getSocketFactory() instanceof SSLSocketFactory); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java index 9f84d4b4b..586efb346 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateTests.java @@ -18,8 +18,6 @@ package org.springframework.data.mongodb.core; import static org.hamcrest.Matchers.*; import static org.junit.Assert.*; import static org.junit.Assume.*; -import static org.springframework.data.mongodb.core.ReflectiveWriteConcernInvoker.*; -import static org.springframework.data.mongodb.core.ReflectiveWriteResultInvoker.*; import static org.springframework.data.mongodb.core.query.Criteria.*; import static org.springframework.data.mongodb.core.query.Query.*; import static org.springframework.data.mongodb.core.query.Update.*; @@ -1026,7 +1024,7 @@ public class MongoTemplateTests { UpdateResult wr = template.updateMulti(new Query(), u, PersonWithIdPropertyOfTypeObjectId.class); - if (wasAcknowledged(wr)) { + if (wr.wasAcknowledged()) { assertThat(wr.getModifiedCount(), is(2L)); } @@ -1182,7 +1180,7 @@ public class MongoTemplateTests { person.setId(new ObjectId()); person.setFirstName("Dave"); - template.setWriteConcern(noneOrUnacknowledged()); + template.setWriteConcern(WriteConcern.UNACKNOWLEDGED); template.save(person); UpdateResult result = template.updateFirst(query(where("id").is(person.getId())), update("firstName", "Carter"), PersonWithIdPropertyOfTypeObjectId.class); @@ -1195,7 +1193,7 @@ public class MongoTemplateTests { MongoAction lastMongoAction = resolver.getMongoAction(); assertThat(lastMongoAction.getCollectionName(), is("personWithIdPropertyOfTypeObjectId")); - assertThat(lastMongoAction.getDefaultWriteConcern(), equalTo(noneOrUnacknowledged())); + assertThat(lastMongoAction.getDefaultWriteConcern(), equalTo(WriteConcern.UNACKNOWLEDGED)); assertThat(lastMongoAction.getDocument(), notNullValue()); assertThat(lastMongoAction.getEntityType().toString(), is(PersonWithIdPropertyOfTypeObjectId.class.toString())); assertThat(lastMongoAction.getMongoActionOperation(), is(MongoActionOperation.UPDATE)); diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java index cd2bd841b..2bde06830 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/MongoTemplateUnitTests.java @@ -26,6 +26,7 @@ import java.util.List; import java.util.Optional; import java.util.regex.Pattern; +import com.mongodb.MongoClient; import org.bson.Document; import org.bson.conversions.Bson; import org.bson.types.ObjectId; @@ -93,7 +94,7 @@ public class MongoTemplateUnitTests extends MongoOperationsUnitTests { MongoTemplate template; @Mock MongoDbFactory factory; - @Mock Mongo mongo; + @Mock MongoClient mongo; @Mock MongoDatabase db; @Mock MongoCollection collection; @Mock MongoCursor cursor; diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/NoExplicitIdTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/NoExplicitIdTests.java index 971790bd8..01cf6d4ab 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/NoExplicitIdTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/NoExplicitIdTests.java @@ -56,7 +56,7 @@ public class NoExplicitIdTests { } @Override - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient(); } } 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..06b6f3390 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 @@ -25,13 +25,13 @@ import com.mongodb.MongoClient; public class PersonExampleAppConfig { @Bean - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient("localhost"); } @Bean public MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), "database"); + return new MongoTemplate(mongoClient(), "database"); } @Bean diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvokerTestUtil.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvokerTestUtil.java deleted file mode 100644 index 017963996..000000000 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/ReflectiveMongoOptionsInvokerTestUtil.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright 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 com.mongodb.MongoOptions; - -/** - * Helper class allowing to keep {@link ReflectiveMongoOptionsInvoker} within default visibility while using it publicly - * across tests. - * - * @author Christoph Strobl - */ -@SuppressWarnings("deprecation") -public class ReflectiveMongoOptionsInvokerTestUtil { - - public static void setAutoConnectRetry(MongoOptions options, boolean autoConnectRetry) { - ReflectiveMongoOptionsInvoker.setAutoConnectRetry(options, autoConnectRetry); - } - - public static void setMaxAutoConnectRetryTime(MongoOptions options, long maxAutoConnectRetryTime) { - ReflectiveMongoOptionsInvoker.setMaxAutoConnectRetryTime(options, maxAutoConnectRetryTime); - } - - public static void setSlaveOk(MongoOptions options, boolean slaveOk) { - ReflectiveMongoOptionsInvoker.setSlaveOk(options, slaveOk); - } - - public static boolean getSlaveOk(MongoOptions options) { - return ReflectiveMongoOptionsInvoker.getSlaveOk(options); - } - - public static boolean getAutoConnectRetry(MongoOptions options) { - return ReflectiveMongoOptionsInvoker.getAutoConnectRetry(options); - } - - public static long getMaxAutoConnectRetryTime(MongoOptions options) { - return ReflectiveMongoOptionsInvoker.getMaxAutoConnectRetryTime(options); - } -} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SimpleMongoDbFactoryUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SimpleMongoDbFactoryUnitTests.java index f2979e04d..bda0dee38 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SimpleMongoDbFactoryUnitTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/SimpleMongoDbFactoryUnitTests.java @@ -47,7 +47,7 @@ import com.mongodb.MongoURI; public class SimpleMongoDbFactoryUnitTests { public @Rule ExpectedException expectedException = ExpectedException.none(); - @Mock Mongo mongo; + @Mock MongoClient mongo; @Test // DATADOC-254 public void rejectsIllegalDatabaseNames() { @@ -67,21 +67,12 @@ public class SimpleMongoDbFactoryUnitTests { @SuppressWarnings("deprecation") public void mongoUriConstructor() throws UnknownHostException { - MongoURI mongoURI = new MongoURI("mongodb://myUsername:myPassword@localhost/myDatabase.myCollection"); + MongoClientURI mongoURI = new MongoClientURI("mongodb://myUsername:myPassword@localhost/myDatabase.myCollection"); MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoURI); - assertThat(getField(mongoDbFactory, "credentials"), is((Object) new UserCredentials("myUsername", "myPassword"))); assertThat(getField(mongoDbFactory, "databaseName").toString(), is("myDatabase")); } - @Test // DATAMONGO-789 - @SuppressWarnings("deprecation") - public void defaultsAuthenticationDatabaseToDatabase() { - - SimpleMongoDbFactory factory = new SimpleMongoDbFactory(mongo, "foo"); - assertThat(getField(factory, "authenticationDatabaseName"), is((Object) "foo")); - } - @Test // DATAMONGO-1158 public void constructsMongoClientAccordingToMongoUri() throws UnknownHostException { @@ -91,43 +82,6 @@ public class SimpleMongoDbFactoryUnitTests { assertThat(getField(factory, "databaseName").toString(), is("myDataBase")); } - @Test // DATAMONGO-1158 - public void shouldDefaultAuthenticationDbNameToDbNameWhenUsingMongoClient() throws UnknownHostException { - - MongoClient clientMock = mock(MongoClient.class); - SimpleMongoDbFactory factory = new SimpleMongoDbFactory(clientMock, "FooBar"); - - assertThat(getField(factory, "authenticationDatabaseName").toString(), is("FooBar")); - } - - @Test // DATAMONGO-1260 - public void rejectsMongoClientWithUserCredentials() { - - expectedException.expect(InvalidDataAccessApiUsageException.class); - expectedException.expectMessage("use 'MongoCredential' for 'MongoClient'"); - - new SimpleMongoDbFactory(mock(MongoClient.class), "cairhienin", new UserCredentials("moiraine", "sedai")); - } - - @Test // DATAMONGO-1260 - public void rejectsMongoClientWithUserCredentialsAndAuthDb() { - - expectedException.expect(InvalidDataAccessApiUsageException.class); - expectedException.expectMessage("use 'MongoCredential' for 'MongoClient'"); - - new SimpleMongoDbFactory(mock(MongoClient.class), "malkieri", new UserCredentials("lan", "mandragoran"), "authdb"); - } - - @Test // DATAMONGO-1260 - public void shouldNotRejectMongoClientWithNoCredentials() { - new SimpleMongoDbFactory(mock(MongoClient.class), "andoran", UserCredentials.NO_CREDENTIALS); - } - - @Test // DATAMONGO-1260 - public void shouldNotRejectMongoClientWithEmptyUserCredentials() { - new SimpleMongoDbFactory(mock(MongoClient.class), "shangtai", new UserCredentials("", "")); - } - @SuppressWarnings("deprecation") private void rejectsDatabaseName(String databaseName) { diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java index 34ee5dcba..c946b79aa 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/TestMongoConfiguration.java @@ -21,7 +21,7 @@ public class TestMongoConfiguration extends AbstractMongoConfiguration { @Override @Bean - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient("127.0.0.1", 27017); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolverUnitTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolverUnitTests.java deleted file mode 100644 index e3fc1c810..000000000 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/convert/ReflectiveDBRefResolverUnitTests.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2015-2017 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * 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 static org.hamcrest.core.Is.*; -import static org.hamcrest.core.IsNull.*; -import static org.junit.Assert.*; -import static org.junit.Assume.*; -import static org.mockito.Mockito.*; -import static org.springframework.data.mongodb.util.MongoClientVersion.*; - -import org.bson.Document; -import org.bson.conversions.Bson; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.springframework.data.mongodb.MongoDbFactory; - -import com.mongodb.DBRef; -import com.mongodb.client.FindIterable; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; - -/** - * Unit tests for {@link ReflectiveDBRefResolver}. - * - * @author Christoph Strobl - */ -@RunWith(MockitoJUnitRunner.class) -public class ReflectiveDBRefResolverUnitTests { - - @Mock MongoDbFactory dbFactoryMock; - @Mock DBRef dbRefMock; - @Mock MongoDatabase dbMock; - @Mock MongoCollection collectionMock; - @Mock FindIterable fi; - - @Before - public void setUp() { - - when(dbRefMock.getCollectionName()).thenReturn("collection-1"); - when(dbRefMock.getId()).thenReturn("id-1"); - when(dbFactoryMock.getDb()).thenReturn(dbMock); - when(dbMock.getCollection(eq("collection-1"), eq(Document.class))).thenReturn(collectionMock); - when(collectionMock.find(any(Bson.class))).thenReturn(fi); - when(fi.first()).thenReturn(new Document("_id", "id-1")); - } - - @Test // DATAMONGO-1193 - public void fetchShouldNotLookUpDbWhenUsingDriverVersion2() { - - assumeThat(isMongo3Driver(), is(false)); - - ReflectiveDBRefResolver.fetch(dbFactoryMock, dbRefMock); - - verify(dbFactoryMock, never()).getDb(); - verify(dbFactoryMock, never()).getDb(anyString()); - } - - @Test // DATAMONGO-1193 - public void fetchShouldUseDbToResolveDbRefWhenUsingDriverVersion3() { - - assumeThat(isMongo3Driver(), is(true)); - - assertThat(ReflectiveDBRefResolver.fetch(dbFactoryMock, dbRefMock), notNullValue()); - verify(dbFactoryMock, times(1)).getDb(); - } - - @Test(expected = IllegalArgumentException.class) // DATAMONGO-1193 - public void fetchShouldThrowExceptionWhenDbFactoryIsNullUsingDriverVersion3() { - - assumeThat(isMongo3Driver(), is(true)); - - ReflectiveDBRefResolver.fetch(null, dbRefMock); - } -} diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java index 6d6641eb3..ffee1cbd4 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/AbstractGeoSpatialTests.java @@ -65,7 +65,7 @@ public abstract class AbstractGeoSpatialTests { } @Override - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient(); } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java index e0778fa04..b22b9baad 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/geo/GeoJsonTests.java @@ -70,7 +70,7 @@ public class GeoJsonTests { } @Override - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient(); } } 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..a485cd872 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 @@ -34,7 +34,7 @@ public class GeoIndexedAppConfig extends AbstractMongoConfiguration { @Override @Bean - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient("127.0.0.1"); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/event/ApplicationContextEventTestsAppConfig.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/event/ApplicationContextEventTestsAppConfig.java index 594efdab3..f3750afae 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/event/ApplicationContextEventTestsAppConfig.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/core/mapping/event/ApplicationContextEventTestsAppConfig.java @@ -32,7 +32,7 @@ public class ApplicationContextEventTestsAppConfig extends AbstractMongoConfigur @Override @Bean - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient("127.0.0.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..cdcdfa1f3 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 @@ -26,7 +26,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; /** * This test class assumes that you are already running the MongoDB server. @@ -39,18 +39,18 @@ import com.mongodb.Mongo; @ContextConfiguration("classpath:infrastructure.xml") public class MongoMonitorIntegrationTests { - @Autowired Mongo mongo; + @Autowired MongoClient mongoClient; @Test public void serverInfo() { - ServerInfo serverInfo = new ServerInfo(mongo); + ServerInfo serverInfo = new ServerInfo(mongoClient); serverInfo.getVersion(); } @Test // DATAMONGO-685 public void getHostNameShouldReturnServerNameReportedByMongo() throws UnknownHostException { - ServerInfo serverInfo = new ServerInfo(mongo); + ServerInfo serverInfo = new ServerInfo(mongoClient); String hostName = null; try { @@ -65,7 +65,7 @@ public class MongoMonitorIntegrationTests { @Test public void operationCounters() { - OperationCounters operationCounters = new OperationCounters(mongo); + OperationCounters operationCounters = new OperationCounters(mongoClient); operationCounters.getInsertCount(); } } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/performance/PerformanceTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/performance/PerformanceTests.java index a0a448d6b..694130072 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/performance/PerformanceTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/performance/PerformanceTests.java @@ -80,7 +80,7 @@ public class PerformanceTests { private static final int COLLECTION_SIZE = 1024 * 1024 * 256; // 256 MB private static final Collection COLLECTION_NAMES = Arrays.asList("template", "driver", "person"); - Mongo mongo; + MongoClient mongo; MongoTemplate operations; PersonRepository repository; MongoConverter converter; diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/ComplexIdRepositoryIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/ComplexIdRepositoryIntegrationTests.java index 70a39a02b..fbfe91a02 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/ComplexIdRepositoryIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/ComplexIdRepositoryIntegrationTests.java @@ -57,7 +57,7 @@ public class ComplexIdRepositoryIntegrationTests { } @Override - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient(); } diff --git a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/MongoRepositoryTextSearchIntegrationTests.java b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/MongoRepositoryTextSearchIntegrationTests.java index b3b439f37..657bf2a23 100644 --- a/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/MongoRepositoryTextSearchIntegrationTests.java +++ b/spring-data-mongodb/src/test/java/org/springframework/data/mongodb/repository/MongoRepositoryTextSearchIntegrationTests.java @@ -207,7 +207,7 @@ public class MongoRepositoryTextSearchIntegrationTests { } @Override - public Mongo mongo() throws Exception { + public MongoClient mongoClient() throws Exception { return new MongoClient(); } diff --git a/spring-data-mongodb/src/test/resources/infrastructure.xml b/spring-data-mongodb/src/test/resources/infrastructure.xml index 92a590eef..0107de40a 100644 --- a/spring-data-mongodb/src/test/resources/infrastructure.xml +++ b/spring-data-mongodb/src/test/resources/infrastructure.xml @@ -3,13 +3,13 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - + - + diff --git a/spring-data-mongodb/src/test/resources/namespace/db-factory-bean-custom-write-concern.xml b/spring-data-mongodb/src/test/resources/namespace/db-factory-bean-custom-write-concern.xml index 1c7bb540d..469489df9 100644 --- a/spring-data-mongodb/src/test/resources/namespace/db-factory-bean-custom-write-concern.xml +++ b/spring-data-mongodb/src/test/resources/namespace/db-factory-bean-custom-write-concern.xml @@ -8,7 +8,7 @@ - + diff --git a/spring-data-mongodb/src/test/resources/namespace/db-factory-bean.xml b/spring-data-mongodb/src/test/resources/namespace/db-factory-bean.xml index b5433944d..15641c366 100644 --- a/spring-data-mongodb/src/test/resources/namespace/db-factory-bean.xml +++ b/spring-data-mongodb/src/test/resources/namespace/db-factory-bean.xml @@ -8,7 +8,7 @@ - + - - + + - + diff --git a/spring-data-mongodb/src/test/resources/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreatorIntegrationTests-context.xml b/spring-data-mongodb/src/test/resources/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreatorIntegrationTests-context.xml index 6ed28955f..ce49033e7 100644 --- a/spring-data-mongodb/src/test/resources/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreatorIntegrationTests-context.xml +++ b/spring-data-mongodb/src/test/resources/org/springframework/data/mongodb/core/index/MongoPersistentEntityIndexCreatorIntegrationTests-context.xml @@ -17,7 +17,7 @@ - - + + diff --git a/src/main/asciidoc/reference/cross-store.adoc b/src/main/asciidoc/reference/cross-store.adoc index fda6aa124..94dc4ca57 100644 --- a/src/main/asciidoc/reference/cross-store.adoc +++ b/src/main/asciidoc/reference/cross-store.adoc @@ -127,10 +127,10 @@ Finally, you need to configure your project to use MongoDB and also configure th ... - + - + diff --git a/src/main/asciidoc/reference/jmx.adoc b/src/main/asciidoc/reference/jmx.adoc index 9ebb6f591..d398d2c45 100644 --- a/src/main/asciidoc/reference/jmx.adoc +++ b/src/main/asciidoc/reference/jmx.adoc @@ -25,7 +25,7 @@ Spring's Mongo namespace enables you to easily enable JMX functionality http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - + diff --git a/src/main/asciidoc/reference/mapping.adoc b/src/main/asciidoc/reference/mapping.adoc index ce05cdcb4..b54311eaa 100644 --- a/src/main/asciidoc/reference/mapping.adoc +++ b/src/main/asciidoc/reference/mapping.adoc @@ -5,8 +5,6 @@ Rich mapping support is provided by the `MappingMongoConverter`. `MappingMongoCo In this section we will describe the features of the `MappingMongoConverter`. How to use conventions for mapping objects to documents and how to override those conventions with annotation based mapping metadata. -NOTE: `SimpleMongoConverter` has been deprecated in Spring Data MongoDB M3 as all of its functionality has been subsumed into `MappingMongoConverter`. - [[mapping-conventions]] == Convention based Mapping @@ -252,7 +250,7 @@ calling `get()` before the actual conversion Unless explicitly configured, an instance of `MappingMongoConverter` is created by default when creating a `MongoTemplate`. You can create your own instance of the `MappingMongoConverter` so as to tell it where to scan the classpath at startup your domain classes in order to extract metadata and construct indexes. Also, by creating your own instance you can register Spring converters to use for mapping specific classes to and from the database. -You can configure the `MappingMongoConverter` as well as `com.mongodb.Mongo` and MongoTemplate either using Java or XML based metadata. Here is an example using Spring's Java based configuration +You can configure the `MappingMongoConverter` as well as `com.mongodb.MongoClient` and MongoTemplate either using Java or XML based metadata. Here is an example using Spring's Java based configuration .@Configuration class to configure MongoDB mapping support ==== @@ -296,7 +294,7 @@ public class GeoSpatialAppConfig extends AbstractMongoConfiguration { ---- ==== -`AbstractMongoConfiguration` requires you to implement methods that define a `com.mongodb.Mongo` as well as provide a database name. `AbstractMongoConfiguration` also has a method you can override named `getMappingBasePackage(…)` which tells the converter where to scan for classes annotated with the `@Document` annotation. +`AbstractMongoConfiguration` requires you to implement methods that define a `com.mongodb.MongoClient` as well as provide a database name. `AbstractMongoConfiguration` also has a method you can override named `getMappingBasePackage(…)` which tells the converter where to scan for classes annotated with the `@Document` annotation. You can add additional converters to the converter by overriding the method afterMappingMongoConverterCreation. Also shown in the above example is a `LoggingEventListener` which logs `MongoMappingEvent` s that are posted onto Spring's `ApplicationContextEvent` infrastructure. @@ -320,9 +318,9 @@ Spring's MongoDB namespace enables you to easily enable mapping functionality in http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - + - + diff --git a/src/main/asciidoc/reference/mongo-repositories.adoc b/src/main/asciidoc/reference/mongo-repositories.adoc index 80f8c2f1f..149b7aa1b 100644 --- a/src/main/asciidoc/reference/mongo-repositories.adoc +++ b/src/main/asciidoc/reference/mongo-repositories.adoc @@ -56,10 +56,10 @@ Right now this interface simply serves typing purposes but we will add additiona http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd"> - + - + diff --git a/src/main/asciidoc/reference/mongodb.adoc b/src/main/asciidoc/reference/mongodb.adoc index f9192fca7..e96b12931 100644 --- a/src/main/asciidoc/reference/mongodb.adoc +++ b/src/main/asciidoc/reference/mongodb.adoc @@ -21,7 +21,7 @@ For most tasks you will find yourself using `MongoTemplate` or the Repository su [[mongodb-getting-started]] == Getting Started -Spring MongoDB support requires MongoDB 2.6 or higher and Java SE 6 or higher. An easy way to bootstrap setting up a working environment is to create a Spring based project in http://spring.io/tools/sts[STS]. +Spring MongoDB support requires MongoDB 2.6 or higher and Java SE 8 or higher. An easy way to bootstrap setting up a working environment is to create a Spring based project in http://spring.io/tools/sts[STS]. First you need to set up a running Mongodb server. Refer to the http://docs.mongodb.org/manual/core/introduction/[Mongodb Quick Start guide] for an explanation on how to startup a MongoDB instance. Once installed starting MongoDB is typically a matter of executing the following command: `MONGO_HOME/bin/mongod` @@ -122,7 +122,7 @@ import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; public class MongoApp { @@ -130,7 +130,7 @@ public class MongoApp { public static void main(String[] args) throws Exception { - MongoOperations mongoOps = new MongoTemplate(new Mongo(), "database"); + MongoOperations mongoOps = new MongoTemplate(new MongoClient(), "database"); mongoOps.insert(new Person("Joe", 34)); log.info(mongoOps.findOne(new Query(where("name").is("Joe")), Person.class)); @@ -153,7 +153,7 @@ This will produce the following output Even in this simple example, there are few things to take notice of -* You can instantiate the central helper class of Spring Mongo, <>, using the standard `com.mongodb.Mongo` object and the name of the database to use. +* You can instantiate the central helper class of Spring Mongo, <>, using the standard `com.mongodb.MongoClient` object and the name of the database to use. * The mapper works against standard POJO objects without the need for any additional metadata (though you can optionally provide that information. See <>.). * Conventions are used for handling the id field, converting it to be a `ObjectId` when stored in the database. * Mapping conventions can use field access. Notice the Person class has only getters. @@ -167,16 +167,16 @@ There is an https://github.com/spring-projects/spring-data-examples[github repos [[mongodb-connectors]] == Connecting to MongoDB with Spring -One of the first tasks when using MongoDB and Spring is to create a `com.mongodb.Mongo` object using the IoC container. There are two main ways to do this, either using Java based bean metadata or XML based bean metadata. These are discussed in the following sections. +One of the first tasks when using MongoDB and Spring is to create a `com.mongodb.MongoClient` object using the IoC container. There are two main ways to do this, either using Java based bean metadata or XML based bean metadata. These are discussed in the following sections. NOTE: For those not familiar with how to configure the Spring container using Java based bean metadata instead of XML based metadata see the high level introduction in the reference docs http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/new-in-3.0.html#new-java-configuration[here ] as well as the detailed documentation http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/beans.html#beans-java-instantiating-container[ here]. [[mongo.mongo-java-config]] === Registering a Mongo instance using Java based metadata -An example of using Java based bean metadata to register an instance of a `com.mongodb.Mongo` is shown below +An example of using Java based bean metadata to register an instance of a `com.mongodb.MongoClient` is shown below -.Registering a com.mongodb.Mongo object using Java based bean metadata +.Registering a com.mongodb.MongoClient object using Java based bean metadata ==== [source,java] ---- @@ -184,22 +184,20 @@ An example of using Java based bean metadata to register an instance of a `com.m public class AppConfig { /* - * Use the standard Mongo driver API to create a com.mongodb.Mongo instance. + * Use the standard Mongo driver API to create a com.mongodb.MongoClient instance. */ - public @Bean Mongo mongo() throws UnknownHostException { - return new Mongo("localhost"); + public @Bean MongoClient mongoClient() throws UnknownHostException { + return new MongoClient("localhost"); } } ---- ==== -This approach allows you to use the standard `com.mongodb.Mongo` API that you may already be used to using but also pollutes the code with the UnknownHostException checked exception. The use of the checked exception is not desirable as Java based bean metadata uses methods as a means to set object dependencies, making the calling code cluttered. - -An alternative is to register an instance of `com.mongodb.Mongo` instance with the container using Spring's `MongoClientFactoryBean`. As compared to instantiating a `com.mongodb.Mongo` instance directly, the FactoryBean approach does not throw a checked exception and has the added advantage of also providing the container with an ExceptionTranslator implementation that translates MongoDB exceptions to exceptions in Spring's portable `DataAccessException` hierarchy for data access classes annotated with the `@Repository` annotation. This hierarchy and use of `@Repository` is described in http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/dao.html[Spring's DAO support features]. +This approach allows you to use the standard `com.mongodb.MongoClient` instance with the container using Spring's `MongoClientFactoryBean`. As compared to instantiating a `com.mongodb.Mongo` instance directly, the FactoryBean approach does not throw a checked exception and has the added advantage of also providing the container with an ExceptionTranslator implementation that translates MongoDB exceptions to exceptions in Spring's portable `DataAccessException` hierarchy for data access classes annotated with the `@Repository` annotation. This hierarchy and use of `@Repository` is described in http://docs.spring.io/spring/docs/{springVersion}/spring-framework-reference/html/dao.html[Spring's DAO support features]. An example of a Java based bean metadata that supports exception translation on `@Repository` annotated classes is shown below: -.Registering a com.mongodb.Mongo object using Spring's MongoClientFactoryBean and enabling Spring's exception translation support +.Registering a com.mongodb.MongoClient object using Spring's MongoClientFactoryBean and enabling Spring's exception translation support ==== [source,java] ---- @@ -207,7 +205,7 @@ An example of a Java based bean metadata that supports exception translation on public class AppConfig { /* - * Factory bean that creates the com.mongodb.Mongo instance + * Factory bean that creates the com.mongodb.MongoClient instance */ public @Bean MongoClientFactoryBean mongo() { MongoClientFactoryBean mongo = new MongoClientFactoryBean(); @@ -218,12 +216,12 @@ public class AppConfig { ---- ==== -To access the `com.mongodb.Mongo` object created by the `MongoClientFactoryBean` in other `@Configuration` or your own classes, use a "`private @Autowired Mongo mongo;`" field. +To access the `com.mongodb.MongoClient` object created by the `MongoClientFactoryBean` in other `@Configuration` or your own classes, use a "`private @Autowired Mongo mongo;`" field. [[mongo.mongo-xml-config]] === Registering a Mongo instance using XML based metadata -While you can use Spring's traditional `` XML namespace to register an instance of `com.mongodb.Mongo` with the container, the XML can be quite verbose as it is general purpose. XML namespaces are a better alternative to configuring commonly used objects such as the Mongo instance. The mongo namespace allows you to create a Mongo instance server location, replica-sets, and options. +While you can use Spring's traditional `` XML namespace to register an instance of `com.mongodb.MongoClient` with the container, the XML can be quite verbose as it is general purpose. XML namespaces are a better alternative to configuring commonly used objects such as the Mongo instance. The mongo namespace allows you to create a Mongo instance server location, replica-sets, and options. To use the Mongo namespace elements you will need to reference the Mongo schema: @@ -244,22 +242,22 @@ To use the Mongo namespace elements you will need to reference the Mongo schema: http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> - ** + ** ---- ==== -A more advanced configuration with `MongoOptions` is shown below (note these are not recommended values) +A more advanced configuration with `MongoClientOptions` is shown below (note these are not recommended values) -.XML schema to configure a com.mongodb.Mongo object with MongoOptions +.XML schema to configure a com.mongodb.MongoClient object with MongoClientOptions ==== [source,xml] ---- - - + - + ---- @@ -278,33 +276,31 @@ A more advanced configuration with `MongoOptions` is shown below (note these are A configuration using replica sets is shown below. -.XML schema to configure com.mongodb.Mongo object with Replica Sets +.XML schema to configure com.mongodb.MongoClient object with Replica Sets ==== [source,xml] ---- - + ---- ==== [[mongo.mongo-db-factory]] === The MongoDbFactory interface -While `com.mongodb.Mongo` is the entry point to the MongoDB driver API, connecting to a specific MongoDB database instance requires additional information such as the database name and an optional username and password. With that information you can obtain a com.mongodb.DB object and access all the functionality of a specific MongoDB database instance. Spring provides the `org.springframework.data.mongodb.core.MongoDbFactory` interface shown below to bootstrap connectivity to the database. +While `com.mongodb.MongoClient` is the entry point to the MongoDB driver API, connecting to a specific MongoDB database instance requires additional information such as the database name and an optional username and password. With that information you can obtain a com.mongodb.DB object and access all the functionality of a specific MongoDB database instance. Spring provides the `org.springframework.data.mongodb.core.MongoDbFactory` interface shown below to bootstrap connectivity to the database. [source,java] ---- public interface MongoDbFactory { - DB getDb() throws DataAccessException; + MongoDatabase getDb() throws DataAccessException; - DB getDb(String dbName) throws DataAccessException; + MongoDatabase getDb(String dbName) throws DataAccessException; } ---- The following sections show how you can use the container with either Java or the XML based metadata to configure an instance of the `MongoDbFactory` interface. In turn, you can use the `MongoDbFactory` instance to configure `MongoTemplate`. -The class `org.springframework.data.mongodb.core.SimpleMongoDbFactory` provides implements the `MongoDbFactory` interface and is created with a standard `com.mongodb.Mongo` instance, the database name and an optional `org.springframework.data.authentication.UserCredentials` constructor argument. - Instead of using the IoC container to create an instance of MongoTemplate, you can just use them in standard Java code as shown below. [source,java] @@ -344,24 +340,29 @@ public class MongoConfiguration { } ---- -To define the username and password create an instance of `org.springframework.data.authentication.UserCredentials` and pass it into the constructor as shown below. This listing also shows using `MongoDbFactory` register an instance of MongoTemplate with the container. +MongoDB Server generation 3 changed the authentication model when connecting to the DB. Therefore some of the configuration options available for authentication are no longer valid. Please use the `MongoClient` specific options for setting credentials via `MongoCredential` to provide authentication data. [source,java] ---- @Configuration -public class MongoConfiguration { +public class ApplicationContextEventTestsAppConfig extends AbstractMongoConfiguration { - public @Bean MongoDbFactory mongoDbFactory() throws Exception { - UserCredentials userCredentials = new UserCredentials("joe", "secret"); - return new SimpleMongoDbFactory(new Mongo(), "database", userCredentials); + @Override + public String getDatabaseName() { + return "database"; } - public @Bean MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongoDbFactory()); + @Override + @Bean + public Mongo mongo() throws Exception { + return new MongoClient(singletonList(new ServerAddress("127.0.0.1", 27017)), + singletonList(MongoCredential.createCredential("name", "db", "pwd".toCharArray()))); } } ---- +In order to use authentication with XML configuration use the `credentials` attribue on ``. + [[mongo.mongo-db-factory-xml]] === Registering a MongoDbFactory instance using XML based metadata @@ -373,42 +374,14 @@ The mongo namespace provides a convenient way to create a `SimpleMongoDbFactory` ---- -In the above example a `com.mongodb.Mongo` instance is created using the default host and port number. The `SimpleMongoDbFactory` registered with the container is identified by the id 'mongoDbFactory' unless a value for the id attribute is specified. - -You can also provide the host and port for the underlying `com.mongodb.Mongo` instance as shown below, in addition to username and password for the database. - -[source,xml] ----- - ----- - -If your MongoDB authentication database differs from the target database, use the `authentication-dbname` attribute, as shown below. - -[source,xml] ----- - ----- - -If you need to configure additional options on the `com.mongodb.Mongo` instance that is used to create a `SimpleMongoDbFactory` you can refer to an existing bean using the `mongo-ref` attribute as shown below. To show another common usage pattern, this listing shows the use of a property placeholder to parametrise the configuration and creating `MongoTemplate`. +If you need to configure additional options on the `com.mongodb.MongoClient` instance that is used to create a `SimpleMongoDbFactory` you can refer to an existing bean using the `mongo-ref` attribute as shown below. To show another common usage pattern, this listing shows the use of a property placeholder to parametrise the configuration and creating `MongoTemplate`. [source,xml] ---- - - + - + - + @@ -436,7 +409,7 @@ The class `MongoTemplate`, located in the package `org.springframework.data.mong NOTE: Once configured, `MongoTemplate` is thread-safe and can be reused across multiple instances. -The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the interface `MongoConverter`. Spring provides two implementations, `SimpleMappingConverter` and `MappingMongoConverter`, but you can also write your own converter. Please refer to the section on MongoConverters for more detailed information. +The mapping between MongoDB documents and domain classes is done by delegating to an implementation of the interface `MongoConverter`. Spring provides the `MappingMongoConverter`, but you can also write your own converter. Please refer to the section on MongoConverters for more detailed information. The `MongoTemplate` class implements the interface `MongoOperations`. In as much as possible, the methods on `MongoOperations` are named after methods available on the MongoDB driver `Collection` object to make the API familiar to existing MongoDB developers who are used to the driver API. For example, you will find methods such as "find", "findAndModify", "findOne", "insert", "remove", "save", "update" and "updateMulti". The design goal was to make it as easy as possible to transition between the use of the base MongoDB driver and `MongoOperations`. A major difference in between the two APIs is that MongoOperations can be passed domain objects instead of `Document` and there are fluent APIs for `Query`, `Criteria`, and `Update` operations instead of populating a `Document` to specify the parameters for those operations. @@ -444,8 +417,6 @@ NOTE: The preferred way to reference the operations on `MongoTemplate` instance The default converter implementation used by `MongoTemplate` is MappingMongoConverter. While the `MappingMongoConverter` can make use of additional metadata to specify the mapping of objects to documents it is also capable of converting objects that contain no additional metadata by using some conventions for the mapping of IDs and collection names. These conventions as well as the use of mapping annotations is explained in the <>. -NOTE: In the M2 release `SimpleMappingConverter`, was the default and this class is now deprecated as its functionality has been subsumed by the `MappingMongoConverter`. - Another central feature of MongoTemplate is exception translation of exceptions thrown in the MongoDB Java driver into Spring's portable Data Access Exception hierarchy. Refer to the section on <> for more information. While there are many convenience methods on `MongoTemplate` to help you easily perform common tasks if you should need to access the MongoDB driver API directly to access functionality not explicitly exposed by the MongoTemplate you can use one of several Execute callback methods to access underlying driver APIs. The execute callbacks will give you a reference to either a `com.mongodb.Collection` or a `com.mongodb.DB` object. Please see the section mongo.executioncallback[Execution Callbacks] for more information. @@ -457,19 +428,19 @@ Now let's look at an example of how to work with the `MongoTemplate` in the cont You can use Java to create and register an instance of `MongoTemplate` as shown below. -.Registering a com.mongodb.Mongo object and enabling Spring's exception translation support +.Registering a com.mongodb.MongoClient object and enabling Spring's exception translation support ==== [source,java] ---- @Configuration public class AppConfig { - public @Bean Mongo mongo() throws Exception { - return new Mongo("localhost"); + public @Bean MongoClient mongoClient() throws Exception { + return new MongoClient("localhost"); } public @Bean MongoTemplate mongoTemplate() throws Exception { - return new MongoTemplate(mongo(), "mydatabase"); + return new MongoTemplate(mongoClient(), "mydatabase"); } } ---- @@ -477,19 +448,18 @@ public class AppConfig { There are several overloaded constructors of MongoTemplate. These are -* `MongoTemplate(Mongo mongo, String databaseName)` - takes the `com.mongodb.Mongo` object and the default database name to operate against. -* `MongoTemplate(Mongo mongo, String databaseName, UserCredentials userCredentials)` - adds the username and password for authenticating with the database. -* `MongoTemplate(MongoDbFactory mongoDbFactory)` - takes a MongoDbFactory object that encapsulated the `com.mongodb.Mongo` object, database name, and username and password. +* `MongoTemplate(MongoClient mongo, String databaseName)` - takes the `com.mongodb.MongoClient` object and the default database name to operate against. +* `MongoTemplate(MongoDbFactory mongoDbFactory)` - takes a MongoDbFactory object that encapsulated the `com.mongodb.MongoClient` object, database name, and username and password. * `MongoTemplate(MongoDbFactory mongoDbFactory, MongoConverter mongoConverter)` - adds a MongoConverter to use for mapping. You can also configure a MongoTemplate using Spring's XML schema. [source,java] ---- - + - + ---- @@ -506,7 +476,7 @@ When in development it is very handy to either log or throw an exception if the [[mongo-template.writeconcern]] === WriteConcern -You can set the `com.mongodb.WriteConcern` property that the `MongoTemplate` will use for write operations if it has not yet been specified via the driver at a higher level such as `com.mongodb.Mongo`. If MongoTemplate's `WriteConcern` property is not set it will default to the one set in the MongoDB driver's DB or Collection setting. +You can set the `com.mongodb.WriteConcern` property that the `MongoTemplate` will use for write operations if it has not yet been specified via the driver at a higher level such as `com.mongodb.MongoClient`. If MongoTemplate's `WriteConcern` property is not set it will default to the one set in the MongoDB driver's DB or Collection setting. [[mongo-template.writeconcernresolver]] === WriteConcernResolver @@ -595,7 +565,7 @@ import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.SimpleMongoDbFactory; -import com.mongodb.Mongo; +import com.mongodb.MongoClient; public class MongoApp { @@ -603,7 +573,7 @@ public class MongoApp { public static void main(String[] args) throws Exception { - MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "database")); + MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new MongoClient(), "database")); Person p = new Person("Joe", 34); diff --git a/src/main/asciidoc/reference/reactive-mongodb.adoc b/src/main/asciidoc/reference/reactive-mongodb.adoc index 2e9a3720d..8353fe308 100644 --- a/src/main/asciidoc/reference/reactive-mongodb.adoc +++ b/src/main/asciidoc/reference/reactive-mongodb.adoc @@ -145,7 +145,7 @@ One of the first tasks when using MongoDB and Spring is to create a `com.mongodb An example of using Java based bean metadata to register an instance of a `com.mongodb.reactivestreams.client.MongoClient` is shown below -.Registering a com.mongodb.Mongo object using Java based bean metadata +.Registering a com.mongodb.MongoClient object using Java based bean metadata ==== [source,java] ---- @@ -168,7 +168,7 @@ An alternative is to register an instance of `com.mongodb.reactivestreams.client An example of a Java based bean metadata that supports exception translation on `@Repository` annotated classes is shown below: -.Registering a com.mongodb.Mongo object using Spring's MongoClientFactoryBean and enabling Spring's exception translation support +.Registering a com.mongodb.MongoClient object using Spring's MongoClientFactoryBean and enabling Spring's exception translation support ==== [source,java] ---- @@ -331,7 +331,7 @@ public class AppConfig { There are several overloaded constructors of `ReactiveMongoTemplate`. These are -* `ReactiveMongoTemplate(MongoClient mongo, String databaseName)` - takes the `com.mongodb.Mongo` object and the default database name to operate against. +* `ReactiveMongoTemplate(MongoClient mongo, String databaseName)` - takes the `com.mongodb.MongoClient` object and the default database name to operate against. * `ReactiveMongoTemplate(ReactiveMongoDatabaseFactory mongoDatabaseFactory)` - takes a ReactiveMongoDatabaseFactory object that encapsulated the `com.mongodb.reactivestreams.client.MongoClient` object and database name. * `ReactiveMongoTemplate(ReactiveMongoDatabaseFactory mongoDatabaseFactory, MongoConverter mongoConverter)` - adds a `MongoConverter` to use for mapping.