All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.ch.mongo.TemplateDao Maven / Gradle / Ivy

The newest version!
/**
 * 
 */
package com.ch.mongo;

import java.util.ArrayList;
import java.util.List;

import com.ch.config.ConfigProperties;
import com.ch.exception.DAOException;
import com.ch.exception.PropertyNotFoundException;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;

/**
 * @author ravindra
 *
 */
public abstract class TemplateDao implements Dao {

	protected ConfigProperties configProperties = null;
	protected String databaseName = null;
	public MongoClient mongoClient = null;
	
	public TemplateDao(ConfigProperties config) throws PropertyNotFoundException {
		this.configProperties = config;
	}



	public final void saveEntity(T t) throws DAOException {
		openConnection(configProperties);
		save(t);
		closeConnection();
	}

	public final void updateEntity(T t, String str) throws DAOException {
		openConnection(configProperties);
		updateEntity(t, str);
		closeConnection();
	}

	public final void deleteEntity(T t) throws DAOException {
		openConnection(configProperties);
		delete(t);
		closeConnection();
	}

	public final void saveBatchEntity(List testReport) throws DAOException {
		openConnection(configProperties);
		save(testReport);
		closeConnection();
	}

	private void openConnection(ConfigProperties configProperties) throws DAOException {
		mongoClient = getMongoClient(configProperties);
	}

	private void closeConnection() {
		mongoClient.close();
	}

	private MongoClient getMongoClient(ConfigProperties configProperties) throws DAOException {

		MongoConfig config = new MongoConfig(configProperties);
		String mongoURI = config.getMongoURI();
		this.databaseName = config.getMongoDBName();
		if (mongoURI != null && !mongoURI.isEmpty()) {
			MongoClientURI uri = new MongoClientURI(mongoURI);
			mongoClient = new MongoClient(uri);
		} else {
			String mongoHost = config.getMongoHost();
			int mongoPort = config.getMongoPort();
			String mongoUsername = config.getMongoUsername();
			String mongoPassword = config.getMongoPassword();
			String mongoDBName = config.getMongoDBName();
			List seeds = new ArrayList();
			seeds.add(new ServerAddress(mongoHost, mongoPort));
			MongoClientOptions options = MongoClientOptions.builder().socketKeepAlive(true).build();
			if ((mongoUsername != null && !mongoUsername.trim().isEmpty())
					&& (mongoPassword != null && !mongoPassword.trim().isEmpty())) {
				MongoCredential credential = MongoCredential.createCredential(mongoUsername, mongoDBName,
						mongoPassword.toCharArray());
				mongoClient = new MongoClient(seeds, credential, options);
			} else {
				mongoClient = new MongoClient(seeds, options);
			}
		}

		return mongoClient;

	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy