Created
February 3, 2019 12:35
-
-
Save pcrunn/1949ee445c09f0b35c6be3b4b751b653 to your computer and use it in GitHub Desktop.
MongoHelper is a simple library for easy connections to MongoDB Databases.
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
package me.pcrunn.mongohelper; | |
import com.mongodb.DB; | |
import com.mongodb.MongoClient; | |
import com.mongodb.MongoCredential; | |
import com.mongodb.ServerAddress; | |
import lombok.Data; | |
import java.util.Collections; | |
@Data | |
public class MongoHelper { | |
private String host; | |
private int port; | |
private String database,username,password; | |
private boolean auth; | |
DB DB; | |
MongoClient client; | |
public MongoHelper(String host, int port, String database){ | |
this(host,port,database,"",""); | |
} | |
public MongoHelper(String host, int port, String database, String username, String password) { | |
setHost(host); | |
setPort(port); | |
setDatabase(database); | |
setUsername(username); | |
setPassword(password); | |
connect(); | |
} | |
private boolean connect(){ | |
if(username==""&&password==""){ | |
setAuth(false); | |
}else{ | |
setAuth(true); | |
} | |
try{ | |
if(auth){ | |
MongoCredential credentials = MongoCredential.createCredential(username,database,password.toCharArray()); | |
setClient(new MongoClient(new ServerAddress(host,port), Collections.singletonList(credentials))); | |
}else { | |
setClient(new MongoClient(new ServerAddress(host,port))); | |
} | |
setDB(client.getDB(database)); | |
return true; | |
}catch (Exception exception){ | |
exception.printStackTrace(); | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment