MongoDB server validation is running and credentials are valid in Java

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) {
        // program does not get in here when credentials are wrong, 
        // only when no credentials are provided, but necessary
    }
    catch (MongoSocketOpenException | MongoTimeoutException e) {
        // only get in here after db.listCollectionNames().first() caused a     timeout
    }

How can I do:

  • , mongoDB ?
  • , , ?

Edit: ( / ), MongoTimeoutException. , URL- . , , , . , , , MongoCommandException

+4

Source: https://habr.com/ru/post/1613357/


All Articles