56 lines
1.5 KiB
Java
56 lines
1.5 KiB
Java
package eu.univento.commons.database;
|
|
|
|
import com.mongodb.MongoClient;
|
|
import com.mongodb.MongoCredential;
|
|
import com.mongodb.ServerAddress;
|
|
import com.mongodb.client.MongoDatabase;
|
|
|
|
import java.util.Collections;
|
|
|
|
/**
|
|
* @author joethei
|
|
* @version 1.0
|
|
*/
|
|
public class MongoDB {
|
|
|
|
private final MongoClient client;
|
|
private MongoDatabase database;
|
|
|
|
private final String host;
|
|
private final int port;
|
|
private final String username;
|
|
private final String password;
|
|
private final String databaseName;
|
|
|
|
public MongoDB(String host, int port, String username, String password, String databaseName) {
|
|
this.host = host;
|
|
this.port = port;
|
|
this.username = username;
|
|
this.password = password;
|
|
this.databaseName = databaseName;
|
|
|
|
MongoCredential credential = MongoCredential.createCredential(username, databaseName, password.toCharArray());
|
|
client = new MongoClient(new ServerAddress(host, port), Collections.singletonList(credential));
|
|
}
|
|
|
|
private MongoClient getClient() {
|
|
if(client == null)
|
|
new MongoDB(host, port, username, password, databaseName);
|
|
return client;
|
|
}
|
|
|
|
public MongoDatabase getDatabase() {
|
|
if(database == null)
|
|
database = getClient().getDatabase(databaseName);
|
|
return database;
|
|
}
|
|
|
|
public void setDatabase(String database) {
|
|
this.database = getClient().getDatabase(database);
|
|
}
|
|
|
|
public void closeConnection() {
|
|
if(client != null)
|
|
client.close();
|
|
}
|
|
} |