Example usage for com.mongodb MongoClient getDatabaseNames

List of usage examples for com.mongodb MongoClient getDatabaseNames

Introduction

In this page you can find the example usage for com.mongodb MongoClient getDatabaseNames.

Prototype

@Deprecated
public List<String> getDatabaseNames() 

Source Link

Document

Gets a list of the names of all databases on the connected server.

Usage

From source file:localdomain.localhost.MyServlet.java

License:Apache License

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    PrintWriter writer = resp.getWriter();

    writer.println("<html>");
    writer.println("<head><title>MyServlet</title></head>");
    writer.println("<body><h1>MyServlet</h1>");

    writer.println("<h2>MongoDB</h2>");

    String uriAsString = System.getProperty("MONGOHQ_URL_MYDB", "mongodb://localhost/local");

    MongoClient mongoClient = null;
    try {/*from   www .jav a2s .co  m*/
        writer.println("<h4>MongoClientURI</h4>");

        MongoClientURI uri = new MongoClientURI(uriAsString);
        writer.println("<p>" + "host=" + uri.getHosts() + ",username=" + uri.getUsername() + ",database="
                + uri.getDatabase() + ",collection=" + uri.getCollection() + "</p>");

        writer.println("<h4>MongoClient</h4>");

        mongoClient = new MongoClient(uri);
        writer.println("<p>" + mongoClient + "</p>");

        writer.println("<h4>Databases</h4>");

        try {
            List<String> databaseNames = mongoClient.getDatabaseNames();
            writer.println("<ul>");
            for (String databaseName : databaseNames) {
                writer.println("<li>" + databaseName
                        + (databaseName.equals(uri.getDatabase()) ? " - default database" : ""));
            }
            writer.println("</ul>");
        } catch (Exception e) {
            writer.println("<p>Could not list the databases of the MongoDB instance: <code>" + e.getMessage()
                    + "</code></p>");

        }

        writer.println("<h4>Database</h4>");

        DB db = mongoClient.getDB(uri.getDatabase());
        writer.println("<p>DB: " + db.getName() + "</p>");

        writer.println("<h4>Collections</h4>");
        Set<String> myCollections = db.getCollectionNames();
        if (myCollections.isEmpty()) {
            writer.println("<p>NO COLLECTIONS!</p>");

        } else {

            writer.println("<ul>");
            for (String collection : myCollections) {
                DBCollection dbCollection = db.getCollection(collection);
                writer.println(
                        "<li>" + dbCollection.getName() + " - " + dbCollection.getCount() + " entries</li>");
            }
            writer.println("</ul>");
        }
        writer.println("<h4>Success!</h4>");
        writer.println("SUCCESS to access the mongodb database");

    } catch (Exception e) {
        writer.println("<code><pre>");
        e.printStackTrace(writer);
        writer.println("</pre></code>");

        e.printStackTrace();
    } finally {
        if (mongoClient != null) {
            try {
                mongoClient.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    writer.println("</body></html>");

}

From source file:mongodb1.Mongodb1.java

/**
 * @param args the command line arguments
 *///from  w w w  .  j  a  va  2  s .  c  o m
public static void main(String[] args) {

    try { //Connect

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("labbd2016");
        System.out.println("Connect to database successfully");

        DBCollection table = db.getCollection("alunos");
        System.out.println("Collection retrieved successfully");

        List<String> dbs = mongo.getDatabaseNames();
        System.out.println(dbs);

        Set<String> collections = db.getCollectionNames();
        System.out.println(collections);
        //Insert
        BasicDBObject document = new BasicDBObject();
        document.put("nome", "Adao");
        document.put("idade", 30);
        table.insert(WriteConcern.SAFE, document);
        for (DBObject doc : table.find()) {
            System.out.println(doc);
        }
        //Find
        BasicDBObject searchQuery = new BasicDBObject();
        searchQuery.put("idade", new BasicDBObject("$gt", 1));
        DBCursor cursor = table.find(searchQuery);
        while (cursor.hasNext()) {
            System.out.println(cursor.next());
        }
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
    }
}

From source file:org.aw20.mongoworkbench.command.DBserverStatsMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    String db;/*from ww w  . j a  v a  2s.  c  o m*/
    List<String> listDBs = mdb.getDatabaseNames();
    if (listDBs.size() > 0)
        db = listDBs.get(0);
    else
        db = "admin";

    DB dbM = mdb.getDB(db);

    Object obj = dbM.eval("db.serverStatus()", (Object[]) null);
    if (obj instanceof Map) {
        map = (Map) obj;
        setMessage("Server Status - version=" + map.get("version") + "; localTime=" + map.get("localTime"));
    } else {
        map = null;
        setMessage("invalid result returned");
    }
}

From source file:org.aw20.mongoworkbench.command.EvalMongoCommand.java

License:Open Source License

@Override
public void execute() throws Exception {
    MongoClient mdb = MongoFactory.getInst().getMongo(sName);

    if (mdb == null)
        throw new Exception("no server selected");

    String db;/*from   w ww  . j a  v  a  2  s.c om*/
    List<String> listDBs = mdb.getDatabaseNames();
    if (listDBs.size() > 0)
        db = listDBs.get(0);
    else
        db = "admin";

    DB dbM = mdb.getDB(db);

    Object obj = dbM.eval(eval, (Object[]) null);
    if (obj instanceof Map) {
        map = (Map) obj;
    }

    setMessage("eval() ran");
}

From source file:org.aw20.mongoworkbench.command.ShowDbsMongoCommand.java

License:Open Source License

protected void setDBNames(MongoClient mdb) {
    try {/*www .j  av  a 2 s .  c  o  m*/
        dbNames = new ArrayList<String>(mdb.getDatabaseNames());
        Collections.sort(dbNames);
    } catch (com.mongodb.MongoException e) {
        if (e.getMessage().indexOf("unauthorized") > 0) {
            // Check to see if they have given us a mongo database
            Map m = Activator.getDefault().getServerMap(sName);
            if (m != null) {
                String db = (String) m.get("database");
                if (db != null && db.length() > 0) {
                    dbNames = new ArrayList<String>(1);
                    dbNames.add(db);
                    return;
                }
            }
        }
        throw e;
    }
}

From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java

License:Apache License

List<MongoDatabase> loadDatabaseCollections(ServerConfiguration configuration) {
    MongoClient mongo = null;
    List<MongoDatabase> mongoDatabases = new LinkedList<MongoDatabase>();
    try {/*from w w w. java 2 s .  com*/
        String userDatabase = configuration.getUserDatabase();

        mongo = createMongoClient(configuration);

        if (StringUtils.isNotEmpty(userDatabase) && configuration.isUserDatabaseAsMySingleDatabase()) {
            DB database = mongo.getDB(userDatabase);
            mongoDatabases.add(createMongoDatabaseAndItsCollections(database));
        } else {
            List<String> databaseNames = mongo.getDatabaseNames();
            Collections.sort(databaseNames);
            for (String databaseName : databaseNames) {
                DB database = mongo.getDB(databaseName);
                mongoDatabases.add(createMongoDatabaseAndItsCollections(database));
            }
        }

        return mongoDatabases;
    } catch (Exception ex) {
        LOG.error("Error when collecting Mongo databases", ex);
        throw new ConfigurationException(ex);
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.exist.mongodb.xquery.mongodb.client.ListDatabases.java

License:Open Source License

@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {

    try {//from   w w  w.  j ava  2 s .  com
        // Stream parameters
        String mongodbClientId = args[0].itemAt(0).getStringValue();

        // Check id
        MongodbClientStore.getInstance().validate(mongodbClientId);

        // Stream appropriate Mongodb client
        MongoClient client = MongodbClientStore.getInstance().get(mongodbClientId);

        ValueSequence seq = new ValueSequence();
        for (String name : client.getDatabaseNames()) {
            seq.add(new StringValue(name));
        }
        return seq;

    } catch (XPathException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, ex.getMessage(), ex);

    } catch (MongoException ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0002, ex.getMessage());

    } catch (Throwable ex) {
        LOG.error(ex.getMessage(), ex);
        throw new XPathException(this, MongodbModule.MONG0003, ex.getMessage());
    }

}

From source file:org.forgerock.openidm.repo.mongodb.impl.DBHelper.java

License:Open Source License

/**
 * Get the MongoDB for given config./*from   w w w.  j a v  a2  s .  c om*/
 * 
 * @param config the full configuration for the DB
 * @param setupDB true if it create default users.
 * @return DB
 * @throws InvalidException
 */
public synchronized static DB getDB(JsonValue config, boolean setupDB) throws InvalidException {
    String dbName = config.get(MongoDBRepoService.CONFIG_DBNAME).asString();
    String user = config.get(MongoDBRepoService.CONFIG_USER).defaultTo("openidm").asString();
    char[] pass = config.get(MongoDBRepoService.CONFIG_PASSWORD).defaultTo("openidm").asString().toCharArray();

    clientSingle = MongoClientSingleton.INSTANCE.init(config);
    MongoClient client = clientSingle.getClient();
    DB db = clientSingle.getDB();

    if (setupDB) {
        if (!client.getDatabaseNames().contains(dbName)) {
            db.addUser(user, pass);
        }
        ensureIndexes(db, config);
        DBCollection collection = db.getCollection("internal_user");
        populateDefaultUsers(collection, config);
    }
    if (!db.authenticate(user, pass)) {
        logger.warn("Database Connection refused.");
        MongoClientSingleton.INSTANCE.close();
        throw new InvalidException();
    }
    return db;
}

From source file:org.hibernate.ogm.datastore.mongodb.impl.MongoDBDatastoreProvider.java

License:LGPL

private DB extractDatabase(MongoClient mongo, MongoDBConfiguration config) {
    try {//from  w  w  w.  j ava  2 s .  c o  m
        String databaseName = config.getDatabaseName();
        log.connectingToMongoDatabase(databaseName);

        Boolean containsDatabase;
        try {
            containsDatabase = mongo.getDatabaseNames().contains(databaseName);
        } catch (MongoException me) {
            // we don't have enough privileges, ignore the database creation
            containsDatabase = null;
        }

        if (containsDatabase != null && containsDatabase == Boolean.FALSE) {
            if (config.isCreateDatabase()) {
                log.creatingDatabase(databaseName);
            } else {
                throw log.databaseDoesNotExistException(config.getDatabaseName());
            }
        }
        DB db = mongo.getDB(databaseName);
        if (containsDatabase == null) {
            // force a connection to make sure we do have read access
            // otherwise the connection failure happens during the first flush
            db.collectionExists("WeDoNotCareWhatItIsWeNeedToConnect");
        }
        return mongo.getDB(databaseName);
    } catch (MongoException me) {
        switch (me.getCode()) {
        case AUTHENTICATION_FAILED_CODE:
            throw log.authenticationFailed(config.getUsername());
        default:
            throw log.unableToConnectToDatastore(config.getHost(), config.getPort(), me);
        }
    }
}

From source file:org.netbeans.modules.mongodb.ui.explorer.OneConnectionChildren.java

License:Open Source License

@Override
protected boolean createKeys(final List<DbInfo> list) {
    if (parentNode == null) {
        return true;
    }/*from  w  w  w.  j a  v a  2 s  .  c  o m*/
    final ConnectionProblems problems = lookup.lookup(ConnectionProblems.class);
    final ConnectionInfo connectionInfo = lookup.lookup(ConnectionInfo.class);
    final MongoClient client = lookup.lookup(MongoClient.class);

    if (client != null && client.getConnector().isOpen() && parentNode.isProblem() == false) {
        problems.invoke(new Callable<Void>() {
            @Override
            public Void call() throws Exception {
                final String connectionDBName = connectionInfo.getMongoURI().getDatabase();
                if (connectionDBName != null) {
                    list.add(new DbInfo(connectionDBName, lookup));
                } else {
                    for (String dbName : client.getDatabaseNames()) {
                        list.add(new DbInfo(dbName, lookup));
                    }
                }
                return null;
            }
        });
    }
    return true;
}