Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * 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.springframework.transaction.support.TransactionSynchronizationManager;
 import  org.springframework.util.Assert;
 
 import com.mongodb.DB;
Helper class featuring helper methods for internal MongoDb classes. Mainly intended for internal use within the framework.

Author(s):
Thomas Risberg
Graeme Rocher
Oliver Gierke
Randy Watler
Thomas Darimont
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 DB connection for the given Mongo instance and database name

Parameters:
mongo the Mongo instance, must not be null.
databaseName the database name, must not be null or empty.
Returns:
the DB connection
 
 	public static DB getDB(Mongo mongoString databaseName) {
 		return doGetDB(mongodatabaseName.truedatabaseName);
 	}

Obtains a DB connection for the given Mongo instance and database name

Deprecated:
since 1.7. The MongoClient itself should hold credentials within MongoClient.getCredentialsList().
Parameters:
mongo the Mongo instance, must not be null.
databaseName the database name, must not be null or empty.
credentials the credentials to use, must not be null.
Returns:
the DB connection
 
 	public static DB getDB(Mongo mongoString databaseNameUserCredentials credentials) {
 		return getDB(mongodatabaseNamecredentialsdatabaseName);
 	}

Deprecated:
since 1.7. The MongoClient itself should hold credentials within MongoClient.getCredentialsList().
Parameters:
mongo
databaseName
credentials
authenticationDatabaseName
Returns:
 
 	public static DB getDB(Mongo mongoString databaseNameUserCredentials 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(mongodatabaseNamecredentialstrueauthenticationDatabaseName);
 	}
 
 	private static DB doGetDB(Mongo mongoString databaseNameUserCredentials credentialsboolean 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()) {
				.debug("Registering Spring transaction synchronization for existing MongoDB {}."databaseName);
				TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(dbHoldermongo));
			}
			if (db != null) {
				return db;
			}
		}
		// Lookup fresh database instance
		.debug("Getting Mongo Database name=[{}]"databaseName);
		DB db = mongo.getDB(databaseName);
		if (!(mongo instanceof MongoClient) && requiresAuthDbAuthentication(credentials)) {
			ReflectiveDbInvoker.authenticate(mongodbcredentialsauthenticationDatabaseName);
		}
		// TX sync active, bind new database to thread
		if (TransactionSynchronizationManager.isSynchronizationActive()) {
			.debug("Registering Spring transaction synchronization for MongoDB instance {}."databaseName);
			DbHolder holderToUse = dbHolder;
			if (holderToUse == null) {
				holderToUse = new DbHolder(databaseNamedb);
else {
				holderToUse.addDB(databaseNamedb);
			}
			// synchronize holder only if not yet synchronized
			if (!holderToUse.isSynchronizedWithTransaction()) {
				TransactionSynchronizationManager.registerSynchronization(new MongoSynchronization(holderToUsemongo));
			}
			if (holderToUse != dbHolder) {
				TransactionSynchronizationManager.bindResource(mongoholderToUse);
			}
		}
		// Check whether we are allowed to return the DB.
		if (!allowCreate && !isDBTransactional(dbmongo)) {
			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.

Parameters:
db the DB to check
mongo the Mongo instance that the DB was created with (may be null)
Returns:
whether the DB is transactional
	public static boolean isDBTransactional(DB dbMongo 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.

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.
Parameters:
db the DB to close (may be null)
	public static void closeDB(DB db) {
		if (db != null) {
			.debug("Closing Mongo DB object");
			try {
				ReflectiveDbInvoker.requestDone(db);
catch (Throwable ex) {
				.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

Parameters:
credentials
Returns:
	private static boolean requiresAuthDbAuthentication(UserCredentials credentials) {
		if (credentials == null || !credentials.hasUsername()) {
			return false;
		}
		return !MongoClientVersion.isMongo3Driver();
	}
New to GrepCode? Check out our FAQ X