Skip to content

Instantly share code, notes, and snippets.

@4M01
Last active July 20, 2018 05:50
Show Gist options
  • Save 4M01/dd585039379773b168e32a15f20ebe58 to your computer and use it in GitHub Desktop.
Save 4M01/dd585039379773b168e32a15f20ebe58 to your computer and use it in GitHub Desktop.
Singleton MongoClient for Java Application
import com.mongodb.*;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;
import tests.TestBaseSetup;
import java.util.Arrays;
import java.util.Properties;
/**
* Created by Amol Chavan on 03-06-2016.
*/
public enum DBOps {
INSTANCE;
private MongoClient mongoClient;
Properties DBConfig ;
String serverIP, dbName, dbUsername, dbPassword;
int port;
private DBOps() {
if (mongoClient == null) {
mongoClient = getClient();
}
}
private MongoClient getClient() {
DBConfig = TestBaseSetup.Config;
serverIP = DBConfig.getProperty("ServerIPAddress");
port = Integer.parseInt(DBConfig.getProperty("DBPort"));
dbName = DBConfig.getProperty("DBName");
dbUsername = DBConfig.getProperty("UserName");
dbPassword = DBConfig.getProperty("DBPassword");
MongoCredential credential = MongoCredential.createCredential(dbUsername, dbName, dbPassword.toCharArray());
return new MongoClient(new ServerAddress(serverIP,port), Arrays.asList(credential));
}
public int getCountInCollection(String collectionName, String key, String value) {
try {
MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
Document query = new Document();
query.put(key, value);
MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
return ((int) collection.count(query));
} catch (MongoException e) {
System.out.println("Test");
return 0;
}
}
public boolean removeFromCollection(String collectionName, String key, String value) {
try {
MongoDatabase mongoDatabase = mongoClient.getDatabase(dbName);
Document query= new Document();
query.put(key, value);
MongoCollection<Document> collection = mongoDatabase.getCollection(collectionName);
int count = (int)collection.count(query);
if (count>0 && count <2){
collection.deleteOne(query);
return true;
}
return false;
} catch (MongoException e) {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment