Check MongoDB server is running and credentials are valid in Java

て烟熏妆下的殇ゞ 提交于 2020-01-01 01:14:14

问题


I am programming an UI where a user should be able to put in the URL and port to check whether a mongoDB server is running. Furthermore he should be able to provide credentials when necessary.

If the server is not running or the credentials are wrong, I want to provide a message for each case. Similar questions have been answered here:

Check MongoDB authentication with Java 3.0 driver

how to check from a driver, if mongoDB server is running

Unfortunately they use older versions of the Java driver for mongo. I'm using the 3.2+ version of the MongoDB java driver, where i.e. getDB() is deprecated.

My "solution" for the problem looks somewhat 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 manage to:

  1. Find out when mongoDB server is not running?
  2. Find out that credentials are correct, when necessary?

Edit: When credentials are wrong (username and/or password) the method catches only the MongoTimeoutException. It's the same when the the wrong URL or port or database is provided. To be clear there are other exceptions printed out, but not caught. Only difference is, when providing no password and no username, even though the database requires them, then the MongoCommandException is caught

来源:https://stackoverflow.com/questions/33369905/check-mongodb-server-is-running-and-credentials-are-valid-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!