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.
This commit is contained in:
committed by
Mark Paluch
parent
b5679744e7
commit
db9934c7d8
@@ -20,13 +20,13 @@
|
||||
<mongo:mapping-converter/>
|
||||
|
||||
<!-- Mongo config -->
|
||||
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoClientFactoryBean">
|
||||
<bean id="mongoClient" class="org.springframework.data.mongodb.core.MongoClientFactoryBean">
|
||||
<property name="host" value="localhost"/>
|
||||
<property name="port" value="27017"/>
|
||||
</bean>
|
||||
|
||||
<bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
|
||||
<constructor-arg name="mongo" ref="mongo"/>
|
||||
<constructor-arg name="mongoClient" ref="mongoClient"/>
|
||||
<constructor-arg name="databaseName" value="database"/>
|
||||
</bean>
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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. <br />
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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());
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Mongo> implements PersistenceExceptionTranslator {
|
||||
public class MongoClientFactoryBean extends AbstractFactoryBean<MongoClient> implements PersistenceExceptionTranslator {
|
||||
|
||||
private static final PersistenceExceptionTranslator DEFAULT_EXCEPTION_TRANSLATOR = new MongoExceptionTranslator();
|
||||
|
||||
@@ -108,8 +107,8 @@ public class MongoClientFactoryBean extends AbstractFactoryBean<Mongo> implement
|
||||
* (non-Javadoc)
|
||||
* @see org.springframework.beans.factory.FactoryBean#getObjectType()
|
||||
*/
|
||||
public Class<? extends Mongo> getObjectType() {
|
||||
return Mongo.class;
|
||||
public Class<? extends MongoClient> getObjectType() {
|
||||
return MongoClient.class;
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -125,7 +124,7 @@ public class MongoClientFactoryBean extends AbstractFactoryBean<Mongo> 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<Mongo> 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();
|
||||
}
|
||||
|
||||
|
||||
@@ -249,7 +249,9 @@ public class MongoClientOptionsFactoryBean extends AbstractFactoryBean<MongoClie
|
||||
* @param sslSocketFactory
|
||||
*/
|
||||
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
|
||||
|
||||
this.sslSocketFactory = sslSocketFactory;
|
||||
this.ssl = sslSocketFactory != null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,216 +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 org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.authentication.UserCredentials;
|
||||
import org.springframework.data.mongodb.util.MongoClientVersion;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import com.mongodb.DB;
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoClient;
|
||||
|
||||
/**
|
||||
* Helper class featuring helper methods for internal MongoDb classes. Mainly intended for internal use within the
|
||||
* framework.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
* @author Graeme Rocher
|
||||
* @author Oliver Gierke
|
||||
* @author Randy Watler
|
||||
* @author Thomas Darimont
|
||||
* @author Christoph Strobl
|
||||
* @since 1.0
|
||||
*/
|
||||
public abstract class MongoDbUtils {
|
||||
|
||||
private static final Logger LOGGER = LoggerFactory.getLogger(MongoDbUtils.class);
|
||||
|
||||
/**
|
||||
* Private constructor to prevent instantiation.
|
||||
*/
|
||||
private MongoDbUtils() {}
|
||||
|
||||
/**
|
||||
* Obtains a {@link DB} connection for the given {@link Mongo} instance and database name
|
||||
*
|
||||
* @param mongo the {@link Mongo} instance, must not be {@literal null}.
|
||||
* @param databaseName the database name, must not be {@literal null} or empty.
|
||||
* @return the {@link DB} connection
|
||||
*/
|
||||
public static DB getDB(Mongo mongo, String databaseName) {
|
||||
return doGetDB(mongo, databaseName, UserCredentials.NO_CREDENTIALS, true, databaseName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains a {@link DB} connection for the given {@link Mongo} instance and database name
|
||||
*
|
||||
* @param mongo the {@link Mongo} instance, must not be {@literal null}.
|
||||
* @param databaseName the database name, must not be {@literal null} or empty.
|
||||
* @param credentials the credentials to use, must not be {@literal null}.
|
||||
* @return the {@link DB} connection
|
||||
* @deprecated since 1.7. The {@link MongoClient} itself should hold credentials within
|
||||
* {@link MongoClient#getCredentialsList()}.
|
||||
*/
|
||||
@Deprecated
|
||||
public static DB getDB(Mongo mongo, String databaseName, UserCredentials credentials) {
|
||||
return getDB(mongo, databaseName, credentials, databaseName);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param mongo
|
||||
* @param databaseName
|
||||
* @param credentials
|
||||
* @param authenticationDatabaseName
|
||||
* @return
|
||||
* @deprecated since 1.7. The {@link MongoClient} itself should hold credentials within
|
||||
* {@link MongoClient#getCredentialsList()}.
|
||||
*/
|
||||
@Deprecated
|
||||
public static DB getDB(Mongo mongo, String databaseName, UserCredentials credentials,
|
||||
String authenticationDatabaseName) {
|
||||
|
||||
Assert.notNull(mongo, "No Mongo instance specified!");
|
||||
Assert.hasText(databaseName, "Database name must be given!");
|
||||
Assert.notNull(credentials, "Credentials must not be null, use UserCredentials.NO_CREDENTIALS!");
|
||||
Assert.hasText(authenticationDatabaseName, "Authentication database name must not be null or empty!");
|
||||
|
||||
return doGetDB(mongo, databaseName, credentials, true, authenticationDatabaseName);
|
||||
}
|
||||
|
||||
private static DB doGetDB(Mongo mongo, String databaseName, UserCredentials credentials, boolean allowCreate,
|
||||
String authenticationDatabaseName) {
|
||||
|
||||
DbHolder dbHolder = (DbHolder) TransactionSynchronizationManager.getResource(mongo);
|
||||
|
||||
// Do we have a populated holder and TX sync active?
|
||||
if (dbHolder != null && !dbHolder.isEmpty() && TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
|
||||
DB db = dbHolder.getDB(databaseName);
|
||||
|
||||
// DB found but not yet synchronized
|
||||
if (db != null && !dbHolder.isSynchronizedWithTransaction()) {
|
||||
|
||||
LOGGER.debug("Registering Spring transaction synchronization for existing MongoDB {}.", databaseName);
|
||||
|
||||
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHolder, mongo));
|
||||
dbHolder.setSynchronizedWithTransaction(true);
|
||||
}
|
||||
|
||||
if (db != null) {
|
||||
return db;
|
||||
}
|
||||
}
|
||||
|
||||
// Lookup fresh database instance
|
||||
LOGGER.debug("Getting Mongo Database name=[{}]", databaseName);
|
||||
|
||||
DB db = mongo.getDB(databaseName);
|
||||
|
||||
if (!(mongo instanceof MongoClient) && requiresAuthDbAuthentication(credentials)) {
|
||||
ReflectiveDbInvoker.authenticate(mongo, db, credentials, authenticationDatabaseName);
|
||||
}
|
||||
|
||||
// TX sync active, bind new database to thread
|
||||
if (TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
|
||||
LOGGER.debug("Registering Spring transaction synchronization for MongoDB instance {}.", databaseName);
|
||||
|
||||
DbHolder holderToUse = dbHolder;
|
||||
|
||||
if (holderToUse == null) {
|
||||
holderToUse = new DbHolder(databaseName, db);
|
||||
} else {
|
||||
holderToUse.addDB(databaseName, db);
|
||||
}
|
||||
|
||||
// synchronize holder only if not yet synchronized
|
||||
if (!holderToUse.isSynchronizedWithTransaction()) {
|
||||
TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUse, mongo));
|
||||
holderToUse.setSynchronizedWithTransaction(true);
|
||||
}
|
||||
|
||||
if (holderToUse != dbHolder) {
|
||||
TransactionSynchronizationManager.bindResource(mongo, holderToUse);
|
||||
}
|
||||
}
|
||||
|
||||
// Check whether we are allowed to return the DB.
|
||||
if (!allowCreate && !isDBTransactional(db, mongo)) {
|
||||
throw new IllegalStateException("No Mongo DB bound to thread, "
|
||||
+ "and configuration does not allow creation of non-transactional one here");
|
||||
}
|
||||
|
||||
return db;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return whether the given DB instance is transactional, that is, bound to the current thread by Spring's transaction
|
||||
* facilities.
|
||||
*
|
||||
* @param db the DB to check
|
||||
* @param mongo the Mongo instance that the DB was created with (may be <code>null</code>)
|
||||
* @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 <code>null</code>)
|
||||
* @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();
|
||||
}
|
||||
}
|
||||
@@ -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<Mongo> 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<ServerAddress> replicaSetSeeds;
|
||||
private List<ServerAddress> 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<? extends Mongo> 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 <T>
|
||||
* @return a new unmodifiable {@link List#} from the given elements without nulls
|
||||
*/
|
||||
private static <T> List<T> filterNonNullElementsAsList(T[] elements) {
|
||||
|
||||
if (elements == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
List<T> candidateElements = new ArrayList<T>();
|
||||
|
||||
for (T element : elements) {
|
||||
if (element != null) {
|
||||
candidateElements.add(element);
|
||||
}
|
||||
}
|
||||
|
||||
return Collections.unmodifiableList(candidateElements);
|
||||
}
|
||||
}
|
||||
@@ -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<MongoOptions> {
|
||||
|
||||
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.
|
||||
* <ul>
|
||||
* <li>-1 = don't even report network errors</li>
|
||||
* <li>0 = default, don't call getLastError by default</li>
|
||||
* <li>1 = basic, call getLastError, but don't wait for slaves</li>
|
||||
* <li>2 += wait for slaves</li>
|
||||
* </ul>
|
||||
*
|
||||
* @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 <code>write (true)<code>, 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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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<Document> 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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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> T getFlushingData(String key, Class<T> 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;
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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> T getConnectionData(String key, Class<T> targetClass) {
|
||||
DBObject mem = (DBObject) getServerStatus().get("connections");
|
||||
Document mem = (Document) getServerStatus().get("connections");
|
||||
// Class c = mem.get(key).getClass();
|
||||
return (T) mem.get(key);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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> T getMemData(String key, Class<T> targetClass) {
|
||||
DBObject mem = (DBObject) getServerStatus().get("mem");
|
||||
Document mem = (Document) getServerStatus().get("mem");
|
||||
// Class c = mem.get(key).getClass();
|
||||
return (T) mem.get(key);
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -56,47 +56,6 @@ The name of the database to connect to. Default is 'db'.
|
||||
]]></xsd:documentation>
|
||||
</xsd:annotation>
|
||||
</xsd:attribute>
|
||||
<xsd:attribute name="authentication-dbname" type="xsd:string" use="optional">
|
||||
<xsd:annotation>
|
||||
<xsd:documentation><![CDATA[
|
||||
Deprecated since 1.7 - Please use MongoClient internal authentication. The name of the authentication database to connect to. Default is 'db'.
|
||||
]]></xsd:documentation>
|
||||
</xsd:annotation>
|
||||
</xsd:attribute>
|
||||
<xsd:attribute name="port" type="xsd:string" use="optional">
|
||||
<xsd:annotation>
|
||||
<xsd:documentation><![CDATA[
|
||||
The port to connect to MongoDB server. Default is 27017
|
||||
]]></xsd:documentation>
|
||||
</xsd:annotation>
|
||||
</xsd:attribute>
|
||||
<xsd:attribute name="host" type="xsd:string" use="optional">
|
||||
<xsd:annotation>
|
||||
<xsd:documentation><![CDATA[
|
||||
The host to connect to a MongoDB server. Default is localhost
|
||||
]]></xsd:documentation>
|
||||
</xsd:annotation>
|
||||
</xsd:attribute>
|
||||
<xsd:attribute name="username" type="xsd:string" use="optional">
|
||||
<xsd:annotation>
|
||||
<xsd:documentation><![CDATA[
|
||||
Deprecated since 1.7 - Please use MongoClient internal authentication. The username to use when connecting to a MongoDB server.
|
||||
]]></xsd:documentation>
|
||||
</xsd:annotation>
|
||||
</xsd:attribute>
|
||||
<xsd:attribute name="password" type="xsd:string" use="optional">
|
||||
<xsd:annotation>
|
||||
<xsd:documentation><![CDATA[
|
||||
Deprecated since 1.7 - Please use MongoClient internal authentication. The password to use when connecting to a MongoDB server.
|
||||
]]></xsd:documentation>
|
||||
</xsd:annotation>
|
||||
</xsd:attribute>
|
||||
<xsd:attribute name="uri" type="xsd:string" use="optional">
|
||||
<xsd:annotation>
|
||||
<xsd:documentation><![CDATA[
|
||||
Deprecated since 1.8 - Please use client-uri instead. The Mongo URI string.]]></xsd:documentation>
|
||||
</xsd:annotation>
|
||||
</xsd:attribute>
|
||||
<xsd:attribute name="client-uri" type="xsd:string" use="optional">
|
||||
<xsd:annotation>
|
||||
<xsd:documentation><![CDATA[
|
||||
|
||||
@@ -41,7 +41,7 @@ public class ConfigClassInDefaultPackage extends AbstractMongoConfiguration {
|
||||
* @see org.springframework.data.mongodb.config.AbstractMongoConfiguration#mongo()
|
||||
*/
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/*
|
||||
* Copyright 2013 the original author or authors.
|
||||
* Copyright 2013-2017 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
@@ -51,7 +51,7 @@ public abstract class AbstractIntegrationTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,9 @@ package org.springframework.data.mongodb.config;
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import example.first.First;
|
||||
import example.second.Second;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
@@ -40,12 +43,8 @@ import org.springframework.data.mongodb.core.mapping.MongoMappingContext;
|
||||
import org.springframework.expression.spel.support.StandardEvaluationContext;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoClient;
|
||||
|
||||
import example.first.First;
|
||||
import example.second.Second;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link AbstractMongoConfiguration}.
|
||||
*
|
||||
@@ -86,7 +85,7 @@ public class AbstractMongoConfigurationUnitTests {
|
||||
assertThat(context.getBean(MongoDbFactory.class), is(notNullValue()));
|
||||
|
||||
exception.expect(NoSuchBeanDefinitionException.class);
|
||||
context.getBean(Mongo.class);
|
||||
context.getBean(MongoClient.class);
|
||||
context.close();
|
||||
}
|
||||
|
||||
@@ -125,11 +124,6 @@ public class AbstractMongoConfigurationUnitTests {
|
||||
context.close();
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-789
|
||||
public void authenticationDatabaseShouldDefaultToNull() {
|
||||
assertThat(new SampleMongoConfiguration().getAuthenticationDatabaseName(), is(nullValue()));
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-1470
|
||||
@SuppressWarnings("unchecked")
|
||||
public void allowsMultipleEntityBasePackages() throws ClassNotFoundException {
|
||||
@@ -163,7 +157,7 @@ public class AbstractMongoConfigurationUnitTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
|
||||
@@ -191,7 +185,7 @@ public class AbstractMongoConfigurationUnitTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
|
||||
|
||||
@@ -64,7 +64,7 @@ public class AuditingViaJavaConfigRepositoriesTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ public class AuditingViaJavaConfigRepositoriesTests {
|
||||
static class SimpleConfig extends AbstractMongoConfiguration {
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
|
||||
|
||||
@@ -90,7 +90,7 @@ public class MongoClientParserIntegrationTests {
|
||||
context.refresh();
|
||||
|
||||
try {
|
||||
MongoClient client = context.getBean("mongo", MongoClient.class);
|
||||
MongoClient client = context.getBean("mongoClient", MongoClient.class);
|
||||
|
||||
assertThat(client.getAddress().getHost(), is("127.0.0.1"));
|
||||
assertThat(client.getAddress().getPort(), is(27017));
|
||||
@@ -120,8 +120,6 @@ public class MongoClientParserIntegrationTests {
|
||||
@Test // DATAMONGO-1620
|
||||
public void createsMongoClientWithServerSelectionTimeoutCorrectly() {
|
||||
|
||||
assumeThat(MongoClientVersion.isMongo3Driver(), is(true));
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongoClient-bean.xml"));
|
||||
|
||||
AbstractApplicationContext context = new GenericApplicationContext(factory);
|
||||
|
||||
@@ -17,11 +17,8 @@ package org.springframework.data.mongodb.config;
|
||||
|
||||
import static org.hamcrest.Matchers.*;
|
||||
import static org.junit.Assert.*;
|
||||
import static org.junit.Assume.*;
|
||||
import static org.springframework.data.mongodb.util.MongoClientVersion.*;
|
||||
|
||||
import org.junit.Before;
|
||||
import org.junit.BeforeClass;
|
||||
import org.junit.Test;
|
||||
import org.springframework.beans.factory.config.BeanDefinition;
|
||||
import org.springframework.beans.factory.config.ConstructorArgumentValues;
|
||||
@@ -34,11 +31,9 @@ import org.springframework.context.support.AbstractApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.data.mongodb.MongoDbFactory;
|
||||
import org.springframework.data.mongodb.core.ReflectiveMongoOptionsInvokerTestUtil;
|
||||
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
|
||||
import org.springframework.test.util.ReflectionTestUtils;
|
||||
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.MongoClientURI;
|
||||
import com.mongodb.MongoURI;
|
||||
@@ -57,11 +52,6 @@ public class MongoDbFactoryParserIntegrationTests {
|
||||
DefaultListableBeanFactory factory;
|
||||
BeanDefinitionReader reader;
|
||||
|
||||
@BeforeClass
|
||||
public static void validateMongoDriver() {
|
||||
assumeFalse(isMongo3Driver());
|
||||
}
|
||||
|
||||
@Before
|
||||
public void setUp() {
|
||||
factory = new DefaultListableBeanFactory();
|
||||
@@ -119,27 +109,6 @@ public class MongoDbFactoryParserIntegrationTests {
|
||||
factory.getBean("first");
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-280
|
||||
@SuppressWarnings("deprecation")
|
||||
public void parsesMaxAutoConnectRetryTimeCorrectly() {
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/db-factory-bean.xml"));
|
||||
Mongo mongo = factory.getBean(Mongo.class);
|
||||
assertThat(ReflectiveMongoOptionsInvokerTestUtil.getMaxAutoConnectRetryTime(mongo.getMongoOptions()), is(27L));
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-295
|
||||
public void setsUpMongoDbFactoryUsingAMongoUri() {
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri.xml"));
|
||||
BeanDefinition definition = factory.getBeanDefinition("mongoDbFactory");
|
||||
ConstructorArgumentValues constructorArguments = definition.getConstructorArgumentValues();
|
||||
|
||||
assertThat(constructorArguments.getArgumentCount(), is(1));
|
||||
ValueHolder argument = constructorArguments.getArgumentValue(0, MongoURI.class);
|
||||
assertThat(argument, is(notNullValue()));
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-306
|
||||
public void setsUpMongoDbFactoryUsingAMongoUriWithoutCredentials() {
|
||||
|
||||
@@ -156,11 +125,6 @@ public class MongoDbFactoryParserIntegrationTests {
|
||||
assertThat(db.getName(), is("database"));
|
||||
}
|
||||
|
||||
@Test(expected = BeanDefinitionParsingException.class) // DATAMONGO-295
|
||||
public void rejectsUriPlusDetailedConfiguration() {
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-uri-and-details.xml"));
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-1218
|
||||
public void setsUpMongoDbFactoryUsingAMongoClientUri() {
|
||||
|
||||
@@ -173,11 +137,6 @@ public class MongoDbFactoryParserIntegrationTests {
|
||||
assertThat(argument, is(notNullValue()));
|
||||
}
|
||||
|
||||
@Test(expected = BeanDefinitionParsingException.class) // DATAMONGO-1218
|
||||
public void rejectsClientUriPlusDetailedConfiguration() {
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-client-uri-and-details.xml"));
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-1293
|
||||
public void setsUpClientUriWithId() {
|
||||
|
||||
@@ -202,16 +161,6 @@ public class MongoDbFactoryParserIntegrationTests {
|
||||
assertThat(argument, is(notNullValue()));
|
||||
}
|
||||
|
||||
@Test(expected = BeanDefinitionParsingException.class) // DATAMONGO-1293
|
||||
public void rejectsClientUriPlusDetailedConfigurationAndWriteConcern() {
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-client-uri-write-concern-and-details.xml"));
|
||||
}
|
||||
|
||||
@Test(expected = BeanDefinitionParsingException.class) // DATAMONGO-1293
|
||||
public void rejectsUriPlusDetailedConfigurationAndWriteConcern() {
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-client-uri-write-concern-and-details.xml"));
|
||||
}
|
||||
|
||||
private static void assertWriteConcern(ClassPathXmlApplicationContext ctx, WriteConcern expectedWriteConcern) {
|
||||
|
||||
SimpleMongoDbFactory dbFactory = ctx.getBean("first", SimpleMongoDbFactory.class);
|
||||
|
||||
@@ -31,7 +31,6 @@ import org.junit.runner.RunWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
|
||||
import org.springframework.data.mongodb.core.MongoFactoryBean;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
@@ -30,15 +30,13 @@ import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.data.authentication.UserCredentials;
|
||||
import org.springframework.data.mongodb.MongoDbFactory;
|
||||
import org.springframework.data.mongodb.core.MongoClientFactoryBean;
|
||||
import org.springframework.data.mongodb.core.MongoFactoryBean;
|
||||
import org.springframework.data.mongodb.core.MongoOperations;
|
||||
import org.springframework.data.mongodb.core.ReflectiveMongoOptionsInvokerTestUtil;
|
||||
import org.springframework.data.mongodb.core.convert.MongoConverter;
|
||||
import org.springframework.data.mongodb.gridfs.GridFsOperations;
|
||||
import org.springframework.test.context.ContextConfiguration;
|
||||
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
|
||||
|
||||
import com.mongodb.Mongo;
|
||||
import com.mongodb.MongoClient;
|
||||
import com.mongodb.MongoClientOptions;
|
||||
import com.mongodb.MongoOptions;
|
||||
import com.mongodb.WriteConcern;
|
||||
@@ -58,16 +56,11 @@ public class MongoNamespaceTests {
|
||||
|
||||
@Autowired ApplicationContext ctx;
|
||||
|
||||
@BeforeClass
|
||||
public static void validateMongoDriver() {
|
||||
assumeFalse(isMongo3Driver());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMongoSingleton() throws Exception {
|
||||
|
||||
assertTrue(ctx.containsBean("noAttrMongo"));
|
||||
MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&noAttrMongo");
|
||||
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&noAttrMongo");
|
||||
|
||||
assertNull(getField(mfb, "host"));
|
||||
assertNull(getField(mfb, "port"));
|
||||
@@ -77,7 +70,7 @@ public class MongoNamespaceTests {
|
||||
public void testMongoSingletonWithAttributes() throws Exception {
|
||||
|
||||
assertTrue(ctx.containsBean("defaultMongo"));
|
||||
MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&defaultMongo");
|
||||
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&defaultMongo");
|
||||
|
||||
String host = (String) getField(mfb, "host");
|
||||
Integer port = (Integer) getField(mfb, "port");
|
||||
@@ -85,7 +78,7 @@ public class MongoNamespaceTests {
|
||||
assertEquals("localhost", host);
|
||||
assertEquals(new Integer(27017), port);
|
||||
|
||||
MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions");
|
||||
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
|
||||
assertFalse("By default socketFactory should not be a SSLSocketFactory",
|
||||
options.getSocketFactory() instanceof SSLSocketFactory);
|
||||
}
|
||||
@@ -94,9 +87,9 @@ public class MongoNamespaceTests {
|
||||
public void testMongoSingletonWithSslEnabled() throws Exception {
|
||||
|
||||
assertTrue(ctx.containsBean("mongoSsl"));
|
||||
MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongoSsl");
|
||||
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSsl");
|
||||
|
||||
MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions");
|
||||
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
|
||||
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
|
||||
}
|
||||
|
||||
@@ -114,10 +107,10 @@ public class MongoNamespaceTests {
|
||||
public void testMongoSingletonWithSslEnabledAndCustomSslSocketFactory() throws Exception {
|
||||
|
||||
assertTrue(ctx.containsBean("mongoSslWithCustomSslFactory"));
|
||||
MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory");
|
||||
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoSslWithCustomSslFactory");
|
||||
|
||||
SSLSocketFactory customSslSocketFactory = ctx.getBean("customSslSocketFactory", SSLSocketFactory.class);
|
||||
MongoOptions options = (MongoOptions) getField(mfb, "mongoOptions");
|
||||
MongoClientOptions options = (MongoClientOptions) getField(mfb, "mongoClientOptions");
|
||||
|
||||
assertTrue("socketFactory should be a SSLSocketFactory", options.getSocketFactory() instanceof SSLSocketFactory);
|
||||
assertSame(customSslSocketFactory, options.getSocketFactory());
|
||||
@@ -129,10 +122,9 @@ public class MongoNamespaceTests {
|
||||
assertTrue(ctx.containsBean("secondMongoDbFactory"));
|
||||
MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("secondMongoDbFactory");
|
||||
|
||||
Mongo mongo = (Mongo) getField(dbf, "mongo");
|
||||
assertEquals("localhost", mongo.getAddress().getHost());
|
||||
MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
|
||||
assertEquals("127.0.0.1", mongo.getAddress().getHost());
|
||||
assertEquals(27017, mongo.getAddress().getPort());
|
||||
assertEquals(new UserCredentials("joe", "secret"), getField(dbf, "credentials"));
|
||||
assertEquals("database", getField(dbf, "databaseName"));
|
||||
}
|
||||
|
||||
@@ -142,13 +134,11 @@ public class MongoNamespaceTests {
|
||||
assertTrue(ctx.containsBean("thirdMongoDbFactory"));
|
||||
|
||||
MongoDbFactory dbf = (MongoDbFactory) ctx.getBean("thirdMongoDbFactory");
|
||||
Mongo mongo = (Mongo) getField(dbf, "mongo");
|
||||
MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
|
||||
|
||||
assertEquals("localhost", mongo.getAddress().getHost());
|
||||
assertEquals("127.0.0.1", mongo.getAddress().getHost());
|
||||
assertEquals(27017, mongo.getAddress().getPort());
|
||||
assertEquals(new UserCredentials("joe", "secret"), getField(dbf, "credentials"));
|
||||
assertEquals("database", getField(dbf, "databaseName"));
|
||||
assertEquals("admin", getField(dbf, "authenticationDatabaseName"));
|
||||
}
|
||||
|
||||
@Test // DATAMONGO-140
|
||||
@@ -222,8 +212,8 @@ public class MongoNamespaceTests {
|
||||
@SuppressWarnings("deprecation")
|
||||
public void testMongoSingletonWithPropertyPlaceHolders() throws Exception {
|
||||
|
||||
assertTrue(ctx.containsBean("mongo"));
|
||||
MongoFactoryBean mfb = (MongoFactoryBean) ctx.getBean("&mongo");
|
||||
assertTrue(ctx.containsBean("mongoClient"));
|
||||
MongoClientFactoryBean mfb = (MongoClientFactoryBean) ctx.getBean("&mongoClient");
|
||||
|
||||
String host = (String) getField(mfb, "host");
|
||||
Integer port = (Integer) getField(mfb, "port");
|
||||
@@ -231,23 +221,19 @@ public class MongoNamespaceTests {
|
||||
assertEquals("127.0.0.1", host);
|
||||
assertEquals(new Integer(27017), port);
|
||||
|
||||
Mongo mongo = mfb.getObject();
|
||||
MongoOptions mongoOpts = mongo.getMongoOptions();
|
||||
MongoClient mongo = mfb.getObject();
|
||||
MongoClientOptions mongoOpts = mongo.getMongoClientOptions();
|
||||
|
||||
assertEquals(8, mongoOpts.connectionsPerHost);
|
||||
assertEquals(1000, mongoOpts.connectTimeout);
|
||||
assertEquals(1500, mongoOpts.maxWaitTime);
|
||||
assertEquals(8, mongoOpts.getConnectionsPerHost());
|
||||
assertEquals(1000, mongoOpts.getConnectTimeout());
|
||||
assertEquals(1500, mongoOpts.getMaxWaitTime());
|
||||
|
||||
assertEquals(1500, mongoOpts.socketTimeout);
|
||||
assertEquals(4, mongoOpts.threadsAllowedToBlockForConnectionMultiplier);
|
||||
assertEquals(true, mongoOpts.socketKeepAlive);
|
||||
assertEquals(1500, mongoOpts.getSocketTimeout());
|
||||
assertEquals(4, mongoOpts.getThreadsAllowedToBlockForConnectionMultiplier());
|
||||
|
||||
assertEquals(1, mongoOpts.getWriteConcern().getW());
|
||||
assertEquals(0, mongoOpts.getWriteConcern().getWtimeout());
|
||||
assertEquals(true, mongoOpts.getWriteConcern().fsync());
|
||||
|
||||
assertEquals(true, mongoOpts.fsync);
|
||||
assertEquals(true, ReflectiveMongoOptionsInvokerTestUtil.getAutoConnectRetry(mongoOpts));
|
||||
assertEquals(true, ReflectiveMongoOptionsInvokerTestUtil.getSlaveOk(mongoOpts));
|
||||
// TODO: check the damned defaults
|
||||
// assertEquals("w", mongoOpts.getWriteConcern().getW());
|
||||
// assertEquals(0, mongoOpts.getWriteConcern().getWtimeout());
|
||||
// assertEquals(true, mongoOpts.getWriteConcern().fsync());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ public class MongoParserIntegrationTests {
|
||||
public void readsMongoAttributesCorrectly() {
|
||||
|
||||
reader.loadBeanDefinitions(new ClassPathResource("namespace/mongo-bean.xml"));
|
||||
BeanDefinition definition = factory.getBeanDefinition("mongo");
|
||||
BeanDefinition definition = factory.getBeanDefinition("mongoClient");
|
||||
|
||||
List<PropertyValue> 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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
*
|
||||
@@ -38,23 +38,24 @@ public class MongoAdminIntegrationTests {
|
||||
|
||||
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());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void datanaseStats() {
|
||||
logger.info(mongoAdmin.getDatabaseStats("testAdminDb"));
|
||||
}
|
||||
}
|
||||
@@ -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<Void>() {
|
||||
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<Void>() {
|
||||
public Void doInDB(MongoDatabase db) throws MongoException, DataAccessException {
|
||||
|
||||
// ReflectiveDbInvoker.addUser(db, "admin", "admin".toCharArray());
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
Callable<Void> callable = new Callable<Void>() {
|
||||
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<Callable<Void>> callables = new ArrayList<Callable<Void>>();
|
||||
|
||||
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<Void>() {
|
||||
public Void doInDB(MongoDatabase db) throws MongoException, DataAccessException {
|
||||
|
||||
// ReflectiveDbInvoker.addUser(db.getSisterDB("admin"), "admin", "admin".toCharArray());
|
||||
return null;
|
||||
}
|
||||
});
|
||||
|
||||
Callable<Void> callable = new Callable<Void>() {
|
||||
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<Callable<Void>> callables = new ArrayList<Callable<Void>>();
|
||||
|
||||
for (int i = 0; i < 10; i++) {
|
||||
callables.add(callable);
|
||||
}
|
||||
|
||||
service.invokeAll(callables);
|
||||
|
||||
if (exception != null) {
|
||||
fail("Exception occurred!" + exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<TransactionSynchronization> synchronizations = TransactionSynchronizationManager.getSynchronizations();
|
||||
for (TransactionSynchronization synchronization : synchronizations) {
|
||||
synchronization.beforeCompletion();
|
||||
}
|
||||
|
||||
// triggerAfterCompletion() implementation without swallowed exceptions
|
||||
List<TransactionSynchronization> remainingSynchronizations = TransactionSynchronizationManager
|
||||
.getSynchronizations();
|
||||
if (remainingSynchronizations != null) {
|
||||
for (TransactionSynchronization remainingSynchronization : remainingSynchronizations) {
|
||||
remainingSynchronization.afterCompletion(TransactionSynchronization.STATUS_ROLLED_BACK);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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<Document> collection;
|
||||
@Mock MongoCursor<Document> cursor;
|
||||
|
||||
@@ -56,7 +56,7 @@ public class NoExplicitIdTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
|
||||
@@ -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<Document> collectionMock;
|
||||
@Mock FindIterable<Document> 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);
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,7 @@ public abstract class AbstractGeoSpatialTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@ public class GeoJsonTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +80,7 @@ public class PerformanceTests {
|
||||
private static final int COLLECTION_SIZE = 1024 * 1024 * 256; // 256 MB
|
||||
private static final Collection<String> COLLECTION_NAMES = Arrays.asList("template", "driver", "person");
|
||||
|
||||
Mongo mongo;
|
||||
MongoClient mongo;
|
||||
MongoTemplate operations;
|
||||
PersonRepository repository;
|
||||
MongoConverter converter;
|
||||
|
||||
@@ -57,7 +57,7 @@ public class ComplexIdRepositoryIntegrationTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
|
||||
|
||||
@@ -207,7 +207,7 @@ public class MongoRepositoryTextSearchIntegrationTests {
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mongo mongo() throws Exception {
|
||||
public MongoClient mongoClient() throws Exception {
|
||||
return new MongoClient();
|
||||
}
|
||||
|
||||
|
||||
@@ -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">
|
||||
|
||||
<bean id="mongo" class="org.springframework.data.mongodb.core.MongoClientFactoryBean">
|
||||
<bean id="mongoClient" class="org.springframework.data.mongodb.core.MongoClientFactoryBean">
|
||||
<property name="host" value="127.0.0.1"/>
|
||||
<property name="port" value="27017"/>
|
||||
</bean>
|
||||
|
||||
<bean id="mongoDbFactory" class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
|
||||
<constructor-arg name="mongo" ref="mongo"/>
|
||||
<constructor-arg name="mongoClient" ref="mongoClient"/>
|
||||
<constructor-arg name="databaseName" value="database"/>
|
||||
</bean>
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<mongo:db-factory id="first" mongo-ref="mongo" write-concern="rack1" />
|
||||
|
||||
<mongo:mongo-client id="mongo">
|
||||
<mongo:options max-auto-connect-retry-time="27" />
|
||||
<mongo:client-options />
|
||||
</mongo:mongo-client>
|
||||
|
||||
<mongo:db-factory id="second" write-concern="REPLICAS_SAFE" />
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<mongo:db-factory id="first" mongo-ref="mongo" write-concern="SAFE" />
|
||||
|
||||
<mongo:mongo-client id="mongo">
|
||||
<mongo:options max-auto-connect-retry-time="27" />
|
||||
<mongo:client-options />
|
||||
</mongo:mongo-client>
|
||||
|
||||
<!-- now part of the namespace
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:mongo-client id="mongo" host="localhost" port="42">
|
||||
<mongo:mongo-client id="mongoClient" host="localhost" port="42">
|
||||
<mongo:client-options write-concern="SAFE"/>
|
||||
</mongo:mongo-client>
|
||||
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:db-factory client-uri="mongodb://username:password@localhost/database" username="username" />
|
||||
|
||||
</beans>
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:db-factory client-uri="mongodb://username:password@localhost/database" write-concern="NORMAL" username="username" />
|
||||
|
||||
</beans>
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:db-factory uri="mongodb://username:password@localhost/database" username="username" />
|
||||
|
||||
</beans>
|
||||
@@ -5,6 +5,6 @@
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:db-factory id="testMongo" uri="mongodb://username:password@localhost/database" />
|
||||
<mongo:db-factory id="testMongo" client-uri="mongodb://username:password@localhost/database" />
|
||||
|
||||
</beans>
|
||||
|
||||
@@ -5,6 +5,6 @@
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:db-factory uri="mongodb://localhost/database.myCollection"/>
|
||||
<mongo:db-factory client-uri="mongodb://localhost/database.myCollection"/>
|
||||
|
||||
</beans>
|
||||
|
||||
@@ -5,6 +5,6 @@
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:db-factory uri="mongodb://username:password@localhost/database" write-concern="NORMAL" username="username" />
|
||||
<mongo:db-factory client-uri="mongodb://username:password@localhost/database" write-concern="NORMAL" />
|
||||
|
||||
</beans>
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<beans xmlns="http://www.springframework.org/schema/beans"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
|
||||
xsi:schemaLocation="http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
|
||||
|
||||
<mongo:db-factory uri="mongodb://username:password@localhost/database" />
|
||||
|
||||
</beans>
|
||||
@@ -7,9 +7,12 @@
|
||||
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
|
||||
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
|
||||
|
||||
<mongo:mongo-client id="mongo" host="127.0.0.1" port="27117">
|
||||
<mongo:client-options server-selection-timeout="1000" />
|
||||
</mongo:mongo-client>
|
||||
|
||||
<mongo:db-factory id="mongoDbFactory"
|
||||
host="localhost"
|
||||
port="27117"
|
||||
mongo-ref="mongo"
|
||||
dbname="database"/>
|
||||
|
||||
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
|
||||
|
||||
@@ -12,56 +12,42 @@
|
||||
<context:property-placeholder
|
||||
location="classpath:/org/springframework/data/mongodb/config/mongo.properties"/>
|
||||
|
||||
<mongo:mongo host="${mongo.host}" port="${mongo.port}">
|
||||
<mongo:options
|
||||
<mongo:mongo-client host="${mongo.host}" port="${mongo.port}">
|
||||
<mongo:client-options
|
||||
connections-per-host="${mongo.connectionsPerHost}"
|
||||
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
|
||||
connect-timeout="${mongo.connectTimeout}"
|
||||
max-wait-time="${mongo.maxWaitTime}"
|
||||
auto-connect-retry="${mongo.autoConnectRetry}"
|
||||
socket-keep-alive="${mongo.socketKeepAlive}"
|
||||
socket-timeout="${mongo.socketTimeout}"
|
||||
slave-ok="${mongo.slaveOk}"
|
||||
write-number="1"
|
||||
write-timeout="0"
|
||||
write-fsync="true"/>
|
||||
</mongo:mongo>
|
||||
socket-timeout="${mongo.socketTimeout}" />
|
||||
</mongo:mongo-client>
|
||||
|
||||
<mongo:db-factory dbname="database" mongo-ref="mongo"/>
|
||||
<mongo:db-factory dbname="database" mongo-ref="mongoClient"/>
|
||||
|
||||
<mongo:mongo-client id="mongoClientSsl">
|
||||
<mongo:client-options ssl="${mongoSsl.ssl}" />
|
||||
</mongo:mongo-client>
|
||||
|
||||
<mongo:db-factory id="secondMongoDbFactory"
|
||||
host="localhost"
|
||||
port="27017"
|
||||
dbname="database"
|
||||
username="joe"
|
||||
password="secret"/>
|
||||
dbname="database" />
|
||||
|
||||
<mongo:db-factory id="thirdMongoDbFactory"
|
||||
host="localhost"
|
||||
port="27017"
|
||||
dbname="database"
|
||||
username="joe"
|
||||
password="secret"
|
||||
authentication-dbname="admin"/>
|
||||
dbname="database" />
|
||||
|
||||
<mongo:mongo id="defaultMongo" host="localhost" port="27017"/>
|
||||
<mongo:mongo-client id="defaultMongo" host="localhost" port="27017"/>
|
||||
|
||||
<mongo:mongo id="mongoSsl" host="localhost" port="27017">
|
||||
<mongo:options ssl="${mongoSsl.ssl}"/>
|
||||
</mongo:mongo>
|
||||
<mongo:mongo-client id="mongoSsl" host="localhost" port="27017">
|
||||
<mongo:client-options ssl="${mongoSsl.ssl}"/>
|
||||
</mongo:mongo-client>
|
||||
|
||||
<mongo:mongo id="mongoSslWithCustomSslFactory" host="localhost" port="27017">
|
||||
<mongo:mongo-client id="mongoSslWithCustomSslFactory" host="localhost" port="27017">
|
||||
<!-- setting a non-null ssl-socket-factory implicitly sets ssl=true -->
|
||||
<mongo:options ssl-socket-factory-ref="customSslSocketFactory"/>
|
||||
</mongo:mongo>
|
||||
<mongo:client-options ssl-socket-factory-ref="customSslSocketFactory"/>
|
||||
</mongo:mongo-client>
|
||||
|
||||
<bean id="customSslSocketFactory" class="javax.net.ssl.SSLSocketFactory" factory-method="getDefault" scope="singleton"/>
|
||||
|
||||
<mongo:mongo id="noAttrMongo"/>
|
||||
<mongo:mongo-client id="noAttrMongo"/>
|
||||
|
||||
<mongo:mapping-converter>
|
||||
<mongo:custom-converters>
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
<constructor-arg ref="factory2" />
|
||||
</bean>
|
||||
|
||||
<mongo:db-factory id="factory1" host="127.0.0.1" dbname="mongo-index-db1" />
|
||||
<mongo:db-factory id="factory2" host="127.0.0.1" dbname="mongo-index-db2" />
|
||||
<mongo:db-factory id="factory1" dbname="mongo-index-db1" />
|
||||
<mongo:db-factory id="factory2" dbname="mongo-index-db2" />
|
||||
|
||||
</beans>
|
||||
|
||||
@@ -127,10 +127,10 @@ Finally, you need to configure your project to use MongoDB and also configure th
|
||||
...
|
||||
|
||||
<!-- Mongo config -->
|
||||
<mongo:mongo host="localhost" port="27017"/>
|
||||
<mongo:mongo-client host="localhost" port="27017"/>
|
||||
|
||||
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
|
||||
<constructor-arg name="mongo" ref="mongo"/>
|
||||
<constructor-arg name="mongoClient" ref="mongoClient"/>
|
||||
<constructor-arg name="databaseName" value="test"/>
|
||||
<constructor-arg name="defaultCollectionName" value="cross-store"/>
|
||||
</bean>
|
||||
|
||||
@@ -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">
|
||||
|
||||
<!-- Default bean name is 'mongo' -->
|
||||
<mongo:mongo host="localhost" port="27017"/>
|
||||
<mongo:mongo-client host="localhost" port="27017"/>
|
||||
|
||||
<!-- by default look for a Mongo object named 'mongo' -->
|
||||
<mongo:jmx/>
|
||||
|
||||
@@ -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">
|
||||
|
||||
<!-- Default bean name is 'mongo' -->
|
||||
<mongo:mongo host="localhost" port="27017"/>
|
||||
<mongo:mongo-client host="localhost" port="27017"/>
|
||||
|
||||
<mongo:db-factory dbname="database" mongo-ref="mongo"/>
|
||||
<mongo:db-factory dbname="database" mongo-ref="mongoClient"/>
|
||||
|
||||
<!-- by default look for a Mongo object named 'mongo' - default name used for the converter is 'mappingConverter' -->
|
||||
<mongo:mapping-converter base-package="com.bigbank.domain">
|
||||
|
||||
@@ -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">
|
||||
|
||||
<mongo:mongo id="mongo" />
|
||||
<mongo:mongo-client id="mongoClient" />
|
||||
|
||||
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
|
||||
<constructor-arg ref="mongo" />
|
||||
<constructor-arg ref="mongoClient" />
|
||||
<constructor-arg value="databaseName" />
|
||||
</bean>
|
||||
|
||||
|
||||
@@ -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, <<mongo-template,`MongoTemplate`>>, 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, <<mongo-template,`MongoTemplate`>>, 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 <<mongo.mapping,here>>.).
|
||||
* 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 `<beans/>` 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 `<beans/>` 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">
|
||||
|
||||
<!-- Default bean name is 'mongo' -->
|
||||
*<mongo:mongo host="localhost" port="27017"/>*
|
||||
*<mongo:mongo-client host="localhost" port="27017"/>*
|
||||
|
||||
</beans>
|
||||
----
|
||||
====
|
||||
|
||||
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]
|
||||
----
|
||||
<beans>
|
||||
|
||||
<mongo:mongo host="localhost" port="27017">
|
||||
<mongo:options connections-per-host="8"
|
||||
<mongo:mongo-client host="localhost" port="27017">
|
||||
<mongo:client-options connections-per-host="8"
|
||||
threads-allowed-to-block-for-connection-multiplier="4"
|
||||
connect-timeout="1000"
|
||||
max-wait-time="1500}"
|
||||
@@ -270,7 +268,7 @@ A more advanced configuration with `MongoOptions` is shown below (note these are
|
||||
write-number="1"
|
||||
write-timeout="0"
|
||||
write-fsync="true"/>
|
||||
</mongo:mongo/>
|
||||
</mongo:mongo-client>
|
||||
|
||||
</beans>
|
||||
----
|
||||
@@ -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 id="replicaSetMongo" replica-set="127.0.0.1:27017,localhost:27018"/>
|
||||
<mongo:mongo-client id="replicaSetMongo" replica-set="127.0.0.1:27017,localhost:27018"/>
|
||||
----
|
||||
====
|
||||
|
||||
[[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-client>`.
|
||||
|
||||
|
||||
[[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`
|
||||
<mongo:db-factory dbname="database">
|
||||
----
|
||||
|
||||
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]
|
||||
----
|
||||
<mongo:db-factory id="anotherMongoDbFactory"
|
||||
host="localhost"
|
||||
port="27017"
|
||||
dbname="database"
|
||||
username="joe"
|
||||
password="secret"/>
|
||||
----
|
||||
|
||||
If your MongoDB authentication database differs from the target database, use the `authentication-dbname` attribute, as shown below.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<mongo:db-factory id="anotherMongoDbFactory"
|
||||
host="localhost"
|
||||
port="27017"
|
||||
dbname="database"
|
||||
username="joe"
|
||||
password="secret"
|
||||
authentication-dbname="admin"
|
||||
/>
|
||||
----
|
||||
|
||||
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]
|
||||
----
|
||||
<context:property-placeholder location="classpath:/com/myapp/mongodb/config/mongo.properties"/>
|
||||
|
||||
<mongo:mongo host="${mongo.host}" port="${mongo.port}">
|
||||
<mongo:options
|
||||
<mongo:mongo-client host="${mongo.host}" port="${mongo.port}">
|
||||
<mongo:client-options
|
||||
connections-per-host="${mongo.connectionsPerHost}"
|
||||
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
|
||||
connect-timeout="${mongo.connectTimeout}"
|
||||
@@ -420,9 +393,9 @@ If you need to configure additional options on the `com.mongodb.Mongo` instance
|
||||
write-number="1"
|
||||
write-timeout="0"
|
||||
write-fsync="true"/>
|
||||
</mongo:mongo>
|
||||
</mongo:mongo-client>
|
||||
|
||||
<mongo:db-factory dbname="database" mongo-ref="mongo"/>
|
||||
<mongo:db-factory dbname="database" mongo-ref="mongoClient"/>
|
||||
|
||||
<bean id="anotherMongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
|
||||
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory"/>
|
||||
@@ -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 <<mongo.mapping,Mapping chapter>>.
|
||||
|
||||
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 <<mongo.exception,exception translation>> 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 <beans/> schema.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
<mongo:mongo host="localhost" port="27017"/>
|
||||
<mongo:mongo-client host="localhost" port="27017"/>
|
||||
|
||||
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
|
||||
<constructor-arg ref="mongo"/>
|
||||
<constructor-arg ref="mongoClient"/>
|
||||
<constructor-arg name="databaseName" value="geospatial"/>
|
||||
</bean>
|
||||
----
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user