-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
70 additions
and
0 deletions.
There are no files selected for viewing
70 changes: 70 additions & 0 deletions
70
src/main/java/com/milav/jaguar/database/manager/DBManager.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
package com.milav.jaguar.database.errors.manager; | ||
|
||
import com.milav.jaguar.database.errors.DBException; | ||
import com.mongodb.ConnectionString; | ||
import com.mongodb.MongoClientSettings; | ||
import com.mongodb.ServerApi; | ||
import com.mongodb.ServerApiVersion; | ||
import com.mongodb.client.MongoClient; | ||
import com.mongodb.client.MongoClients; | ||
import com.mongodb.client.MongoDatabase; | ||
import org.apache.logging.log4j.LogManager; | ||
|
||
import java.net.UnknownHostException; | ||
|
||
/** | ||
* Manages the database. | ||
* | ||
* @author Jigar Shah | ||
*/ | ||
public class DBManager { | ||
|
||
/** The logger. */ | ||
private static final org.apache.logging.log4j.Logger LOGGER = | ||
LogManager.getLogger(DBManager.class); | ||
/** The database. */ | ||
private static MongoDatabase mongoDB = null; | ||
/** The database manager */ | ||
private static DBManager dbManager = null; | ||
|
||
/** | ||
* Initialize the db manager. | ||
* | ||
* @throws UnknownHostException if we cannot determine the IP address of the host. | ||
*/ | ||
private DBManager() throws UnknownHostException { | ||
init(); | ||
} | ||
|
||
/** | ||
* Gets the database. | ||
* | ||
* @return MongoDatabase | ||
* @throws DBException since we are dealing with the database. | ||
*/ | ||
public static MongoDatabase getMongoDB() throws DBException { | ||
if (dbManager == null) { | ||
try { | ||
dbManager = new DBManager(); | ||
} catch (UnknownHostException ex) { | ||
LOGGER.error(ex); | ||
throw new DBException(ex.getMessage(), ex.fillInStackTrace()); | ||
} | ||
} | ||
return mongoDB; | ||
} | ||
|
||
private void init() { | ||
|
||
ConnectionString connectionString = | ||
new ConnectionString( | ||
"mongodb+srv://<username>:<password>@<hostname>/jaguar?retryWrites=true&w=majority"); | ||
MongoClientSettings settings = | ||
MongoClientSettings.builder() | ||
.applyConnectionString(connectionString) | ||
.serverApi(ServerApi.builder().version(ServerApiVersion.V1).build()) | ||
.build(); | ||
MongoClient mongoClient = MongoClients.create(settings); | ||
mongoDB = mongoClient.getDatabase("jaguar"); | ||
} | ||
} |