Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2010-2013 the original author or authors.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *      http://www.apache.org/licenses/LICENSE-2.0
   *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
 package org.springframework.data.mongodb.core;
 
 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
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

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);
 	}
 
 	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);
		boolean credentialsGiven = credentials.hasUsername() && credentials.hasPassword();
		DB authDb = databaseName.equals(authenticationDatabaseName) ? db : mongo.getDB(authenticationDatabaseName);
		synchronized (authDb) {
			if (credentialsGiven && !authDb.isAuthenticated()) {
				String username = credentials.getUsername();
				String password = credentials.hasPassword() ? credentials.getPassword() : null;
				if (!authDb.authenticate(usernamepassword == null ? null : password.toCharArray())) {
					throw new CannotGetMongoDbConnectionException("Failed to authenticate to database [" + databaseName + "], "
credentials.toString(), databaseNamecredentials);
				}
			}
		}
		// 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.

Parameters:
db the DB to close (may be null)
	public static void closeDB(DB db) {
		if (db != null) {
			.debug("Closing Mongo DB object");
			try {
catch (Throwable ex) {
				.debug("Unexpected exception on closing Mongo DB object"ex);
			}
		}
	}
New to GrepCode? Check out our FAQ X