I am programming a user interface where the user should be able to specify the URL and port to check if the mongoDB server is running. In addition, he should be able to provide credentials when necessary.
If the server is not running or the credentials are incorrect, I want to provide a message for each case. Answers to such questions were given:
Verify MongoDB Authentication Using Java 3.0 Driver
how to check the driver if the mongoDB server is working
Unfortunately, they use older versions of the java driver for mongo. I use the version of the MongoDB java driver version 3.2+, where, for example, getDB () is deprecated.
My "solution" for the problem looks something like this:
try {
String database = "test";
MongoClient client = null;
if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
MongoCredential credentials = MongoCredential.createCredential(username, database, password.toCharArray());
client = new MongoClient(new ServerAddress(url, Integer.parseInt(port)), Arrays.asList(credentials));
}
else {
client = new MongoClient(url, Integer.parseInt(port));
}
MongoDatabase db = client.getDatabase(database);
db.listCollectionNames().first();
client.close();
return true;
}
catch (MongoCommandException | MongoSecurityException e) {
}
catch (MongoSocketOpenException | MongoTimeoutException e) {
}
How can I do:
Edit:
( / ), MongoTimeoutException
. , URL- . , , , . , , , MongoCommandException