private Mongo getMongoAndAuthenticate(ConnectionDetails connectionDetails) throws ApplicationException {
Mongo mongo;
try {
mongo = new Mongo(connectionDetails.getHostIp(), connectionDetails.getHostPort());
} catch (UnknownHostException e) {
throw new ApplicationException(ErrorCodes.HOST_UNKNOWN, "Could not connect to mongo instance with the given host and port");
}
String dbNames = connectionDetails.getDbNames();
String[] dbNamesList = dbNames.split(",");
String username = connectionDetails.getUsername();
String password = connectionDetails.getPassword();
for (String dbName : dbNamesList) {
dbName = dbName.trim();
DB db = mongo.getDB(dbName);
boolean loginStatus = false;
try {
// Hack. Checking server connectivity status by fetching collection names on selected db
db.getCollectionNames();//this line will throw exception in two cases.1)On Invalid mongo host Address,2)Invalid authorization to fetch collection names
loginStatus = true;
} catch (MongoException me) {
loginStatus = db.authenticate(username, password.toCharArray());//login using given username and password.This line will throw exception if invalid mongo host address
}
if (loginStatus) {
connectionDetails.addToAuthenticatedDbNames(dbName);
}
}
if (connectionDetails.getAuthenticatedDbNames().isEmpty()) {
throw new ApplicationException(("".equals(username) && "".equals(password)) ?
ErrorCodes.NEED_AUTHORISATION : ErrorCodes.INVALID_USERNAME, "Invalid UserName or Password");
}
return mongo;
}