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:brooklyn.entity.nosql.mongodb.MongoDBTestHelper.java

License:Apache License

public static List<String> getDatabaseNames(AbstractMongoDBServer entity) {
    LOG.info("Getting database names from {}", entity);
    MongoClient mongoClient = clientForServer(entity);
    try {/*  ww  w .  j  a  va 2  s  .com*/
        return mongoClient.getDatabaseNames();
    } finally {
        mongoClient.close();
    }
}

From source file:com.ebay.cloud.cms.sysmgmt.monitor.metrics.MongoMetric.java

License:Apache License

private Map<String, Object> listDatabases(final MongoClient client) {
    try {/*from   w ww.j  a v  a2  s  .co m*/
        Future<Map<String, Object>> future = executor.submit(new Callable<Map<String, Object>>() {
            @Override
            public Map<String, Object> call() {
                Map<String, Object> resultMap = new HashMap<String, Object>();
                List<String> databaseNames = client.getDatabaseNames();
                for (String databaseName : databaseNames) {
                    DB db = client.getDB(databaseName);
                    if (db != null) {
                        CommandResult cr = db.getStats();
                        if (cr != null) {
                            Object dataSize = cr.get("dataSize");
                            resultMap.put(databaseName, dataSize);
                        }
                    }
                }
                return resultMap;
            }
        });
        return future.get(listWaitPeroid, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        return Collections.emptyMap();
    }
}

From source file:com.edgytech.umongo.ReplSetPanel.java

License:Apache License

public void compareReplicas(ButtonBase button) {
    final String stat = getStringFieldValue(Item.crStat);
    new DbJob() {

        @Override/*from   w  w  w. java2  s .  c  o  m*/
        public Object doRun() {
            ReplSetNode node = getReplSetNode();
            if (!node.hasChildren())
                return null;

            ArrayList<MongoClient> svrs = new ArrayList<MongoClient>();
            for (XmlUnit unit : node.getChildren()) {
                ServerNode svr = (ServerNode) unit;
                MongoClient svrm = svr.getServerMongoClient();
                try {
                    svrm.getDatabaseNames();
                } catch (Exception e) {
                    continue;
                }
                svrs.add(svrm);
            }

            BasicDBObject res = new BasicDBObject();
            MongoClient m = getReplSetNode().getMongoClient();
            for (String dbname : m.getDatabaseNames()) {
                DB db = m.getDB(dbname);
                BasicDBObject dbres = new BasicDBObject();
                for (String colname : db.getCollectionNames()) {
                    DBCollection col = db.getCollection(colname);
                    BasicDBObject colres = new BasicDBObject();
                    BasicDBObject values = new BasicDBObject();
                    boolean same = true;
                    long ref = -1;
                    for (MongoClient svrm : svrs) {
                        DBCollection svrcol = svrm.getDB(dbname).getCollection(colname);
                        long value = 0;
                        if (stat.startsWith("Count")) {
                            value = svrcol.count();
                        } else if (stat.startsWith("Data Size")) {
                            CommandResult stats = svrcol.getStats();
                            value = stats.getLong("size");
                        }
                        values.append(svrm.getConnectPoint(), value);
                        if (ref < 0)
                            ref = value;
                        else if (ref != value)
                            same = false;
                    }
                    if (!same) {
                        colres.append("values", values);
                        dbres.append(colname, colres);
                    }
                }
                if (!dbres.isEmpty()) {
                    res.append(dbname, dbres);
                }
            }

            return res;
        }

        @Override
        public String getNS() {
            return "*";
        }

        @Override
        public String getShortName() {
            return "Compare Replicas";
        }
    }.addJob();
}

From source file:com.edgytech.umongo.RouterPanel.java

License:Apache License

public void regenConfigDB(ButtonBase button) throws UnknownHostException {
    MongoClient cmongo = getRouterNode().getMongoClient();
    String servers = getStringFieldValue(Item.regenServers);
    final String db = getStringFieldValue(Item.regenDB);
    final String col = getStringFieldValue(Item.regenCollection);
    final String ns = db + "." + col;
    final DBObject shardKey = ((DocBuilderField) getBoundUnit(Item.regenShardKey)).getDBObject();
    final boolean unique = getBooleanFieldValue(Item.regenKeyUnique);
    final BasicDBObject result = new BasicDBObject();
    result.put("ns", ns);
    result.put("shardKey", shardKey);
    result.put("unique", unique);

    // create direct mongo for each replica set
    String[] serverList = servers.split("\n");
    List<ServerAddress> list = new ArrayList<ServerAddress>();
    String txt = "";
    String primaryShard = null;//w w  w.  j  a  v a  2s.c om
    final BasicDBObject shardList = new BasicDBObject();
    HashMap<MongoClient, String> mongoToShard = new HashMap<MongoClient, String>();
    sLoop: for (String server : serverList) {
        server = server.trim();
        String[] tokens = server.split("/");
        if (tokens.length != 2) {
            new InfoDialog(null, "Error", null, "Server format must be like 'hostname:port/shard', one by line")
                    .show();
            return;
        }
        server = tokens[0];
        String shard = tokens[1];
        if (primaryShard == null) {
            primaryShard = shard;
        }
        ServerAddress addr = new ServerAddress(server);

        // filter out if replset already exists
        for (MongoClient replset : mongoToShard.keySet()) {
            if (replset.getServerAddressList().contains(addr)) {
                continue sLoop;
            }
        }

        list.clear();
        list.add(addr);
        MongoClient mongo = new MongoClient(list);
        //            UMongo.instance.addMongoClient(mongo, null);
        // make request to force server detection
        mongo.getDatabaseNames();
        mongoToShard.put(mongo, shard);

        String desc = null;
        if (!mongo.getDatabaseNames().contains(db) || !mongo.getDB(db).getCollectionNames().contains(col)) {
            desc = "Collection not present!";
        } else {
            // try to see if shard key has index
            DBObject index = mongo.getDB(db).getCollection("system.indexes")
                    .findOne(new BasicDBObject("key", shardKey));
            if (index != null) {
                desc = "shard key found";
            } else {
                desc = "shard key NOT found!";
            }
        }
        txt += mongo.toString() + " shard=" + shard + " - " + desc + "\n";
        BasicDBObject shardObj = new BasicDBObject("servers", mongo.toString());
        shardObj.put("status", desc);
        if (shardList.containsField(shard)) {
            new InfoDialog(null, "Error", null, "Duplicate Shard name " + shard).show();
            return;
        }
        shardList.put(shard, shardObj);
    }
    result.put("shards", shardList);

    FormDialog dia = (FormDialog) getBoundUnit(Item.regenRSList);
    dia.setStringFieldValue(Item.regenRSListArea, txt);
    if (!dia.show()) {
        return;
    }

    DB config = cmongo.getDB("config");

    // add database record
    BasicDBObject doc = new BasicDBObject("_id", db);
    doc.put("partitioned", true);
    doc.put("primary", primaryShard);
    config.getCollection("databases").save(doc);

    // add collection record
    doc = new BasicDBObject("_id", ns);
    doc.put("lastmod", new Date());
    doc.put("dropped", false);
    doc.put("key", shardKey);
    doc.put("unique", unique);
    config.getCollection("collections").save(doc);

    final DBCollection chunks = config.getCollection("chunks");
    long count = chunks.count(new BasicDBObject("ns", ns));
    if (count > 0) {
        dia = (FormDialog) getBoundUnit(Item.regenDeleteChunks);
        if (dia.show()) {
            chunks.remove(new BasicDBObject("ns", ns));
        } else {
            return;
        }
    }

    // add temp collection to sort chunks with shard key
    final DBCollection tmpchunks = config.getCollection("_tmpchunks_" + col);
    tmpchunks.drop();
    // should be safe environment, and dup keys should be ignored
    tmpchunks.setWriteConcern(WriteConcern.NORMAL);
    // can use shardKey as unique _id
    //        tmpchunks.ensureIndex(shardKey, "shardKey", true);

    // create filter for shard fields
    final DBObject shardKeyFilter = new BasicDBObject();
    //        final DBObject shardKeyDescend = new BasicDBObject();
    boolean hasId = false;
    for (String key : shardKey.keySet()) {
        shardKeyFilter.put(key, 1);
        if (key.equals("_id")) {
            hasId = true;
        }
    }
    if (!hasId) {
        shardKeyFilter.put("_id", 0);
    }

    dia = (FormDialog) getBoundUnit(Item.regenConfirm);
    if (!dia.show()) {
        return;
    }

    // now fetch all records from each shard
    final AtomicInteger todo = new AtomicInteger(mongoToShard.size());
    for (Map.Entry<MongoClient, String> entry : mongoToShard.entrySet()) {
        final MongoClient mongo = entry.getKey();
        final String shard = entry.getValue();
        new DbJob() {

            @Override
            public Object doRun() throws Exception {
                BasicDBObject shardObj = (BasicDBObject) shardList.get(shard);
                long count = mongo.getDB(db).getCollection(col).count();
                shardObj.put("count", count);
                DBCursor cur = mongo.getDB(db).getCollection(col).find(new BasicDBObject(), shardKeyFilter);
                long i = 0;
                int inserted = 0;
                long start = System.currentTimeMillis();
                while (cur.hasNext() && !isCancelled()) {
                    BasicDBObject key = (BasicDBObject) cur.next();
                    setProgress((int) ((++i * 100.0f) / count));
                    try {
                        BasicDBObject entry = new BasicDBObject("_id", key);
                        entry.put("_shard", shard);
                        tmpchunks.insert(entry);
                        ++inserted;
                    } catch (Exception e) {
                        getLogger().log(Level.WARNING, e.getMessage(), e);
                    }
                }

                if (isCancelled()) {
                    shardObj.put("cancelled", true);
                }
                shardObj.put("inserted", inserted);
                shardObj.put("scanTime", System.currentTimeMillis() - start);
                todo.decrementAndGet();
                return null;
            }

            @Override
            public String getNS() {
                return tmpchunks.getFullName();
            }

            @Override
            public String getShortName() {
                return "Scanning " + shard;
            }

            @Override
            public boolean isDeterminate() {
                return true;
            }
        }.addJob();

    }

    new DbJob() {

        @Override
        public Object doRun() throws Exception {
            // wait for all shards to be done
            long start = System.currentTimeMillis();
            while (todo.get() > 0 && !isCancelled()) {
                Thread.sleep(2000);
            }

            if (isCancelled()) {
                result.put("cancelled", true);
                return result;
            }

            // find highest current timestamp
            DBCursor cur = chunks.find().sort(new BasicDBObject("lastmod", -1)).batchSize(-1);
            BasicDBObject chunk = (BasicDBObject) (cur.hasNext() ? cur.next() : null);
            BSONTimestamp ts = (BSONTimestamp) (chunk != null ? chunk.get("lastmod") : null);

            // now infer chunk ranges
            long count = tmpchunks.count();
            result.put("uniqueKeys", count);
            int numChunks = 0;
            cur = tmpchunks.find().sort(new BasicDBObject("_id", 1));
            BasicDBObject prev = (BasicDBObject) cur.next();
            BasicDBObject next = null;
            // snap prev to minkey
            BasicDBObject theid = (BasicDBObject) prev.get("_id");
            for (String key : shardKey.keySet()) {
                theid.put(key, new MinKey());
            }
            String currentShard = prev.getString("_shard");

            int i = 1;
            while (cur.hasNext()) {
                next = (BasicDBObject) cur.next();
                setProgress((int) ((++i * 100.0f) / count));
                String newShard = next.getString("_shard");
                if (newShard.equals(currentShard))
                    continue;

                // add chunk
                ts = getNextTimestamp(ts);
                chunk = getChunk(ns, shardKey, prev, next, ts);
                chunks.insert(chunk);
                prev = next;
                currentShard = prev.getString("_shard");
                ++numChunks;
            }

            // build max
            next = new BasicDBObject();
            for (String key : shardKey.keySet()) {
                next.put(key, new MaxKey());
            }
            next = new BasicDBObject("_id", next);
            ts = getNextTimestamp(ts);
            chunk = getChunk(ns, shardKey, prev, next, ts);
            chunks.insert(chunk);
            ++numChunks;
            result.put("numChunks", numChunks);
            result.put("totalTime", System.currentTimeMillis() - start);
            return result;
        }

        @Override
        public String getNS() {
            return chunks.getFullName();
        }

        @Override
        public String getShortName() {
            return "Creating Chunks";
        }

        @Override
        public boolean isDeterminate() {
            return true;
        }
    }.addJob();
}

From source file:com.jjorgemoura.hangmanz.db.MongoDBManager.java

public static DB db() {

    MongoClient mc = MongoDBManager.engine();

    List<String> databaseNames = mc.getDatabaseNames();

    return mc.getDB(MONGODB_DB);
}

From source file:de.steilerdev.myVerein.server.controller.init.InitController.java

License:Open Source License

/**
 * This function is validating the provided information of the MongoDB server, by establishing a test connection.
 * @param databaseHost The hostname of the MongoDB server.
 * @param databasePort The port of the MongoDB server.
 * @param databaseUser The user used to authenticate against the MongoDB server (may be empty if not needed).
 * @param databasePassword The password used to authenticate against the MongoDB server (may be empty if not needed).
 * @param databaseCollection The name of the database collection.
 * @return True if the connection was successfully established, false otherwise.
 *///from w w w  . j  a v  a  2  s  .  c  om
private boolean mongoIsAvailable(String databaseHost, int databasePort, String databaseUser,
        String databasePassword, String databaseCollection) {
    logger.trace("Testing MongoDB connection");

    if (!databaseUser.isEmpty() && !databasePassword.isEmpty()) {
        logger.debug("Credentials have been provided");
        mongoCredential = Arrays.asList(MongoCredential.createMongoCRCredential(databaseUser,
                databaseCollection, databasePassword.toCharArray()));
    }

    try {
        logger.debug("Creating server address");
        mongoAddress = new ServerAddress(databaseHost, databasePort);
    } catch (UnknownHostException e) {
        logger.warn("Unable to resolve server host: " + e.getMessage());
        return false;
    }

    logger.debug("Creating mongo client");
    MongoClient mongoClient = new MongoClient(mongoAddress, mongoCredential);
    try {
        //Checking if connection REALLY works
        logger.debug("Establishing connection now.");
        List<String> databases = mongoClient.getDatabaseNames();
        if (databases == null) {
            logger.warn("The returned list of databases is null");
            return false;
        } else if (databases.isEmpty()) {
            logger.info("The databases are empty");
            return true;
        } else {
            logger.debug("The database connection seems okay");
            return true;
        }
    } catch (MongoException e) {
        logger.warn("Unable to receive list of present databases: " + e.getMessage());
        return false;
    } finally {
        logger.debug("Closing mongo client");
        mongoClient.close();
    }
}

From source file:de.steilerdev.myVerein.server.controller.init.InitController.java

License:Open Source License

/**
 * This function is establishing a connection to the new database and storing the new super user as well as the new root division. To correctly execute this function the {@link #mongoIsAvailable} function should be called first.
 * @param user The new super admin.//from  w  ww .  java2 s .  co  m
 * @param division The new root division.
 * @return True if the operation was successfully, false otherwise.
 */
private boolean savingInitialSetup(User user, Division division, Settings settings) {
    if (mongoAddress != null && databaseName != null && !databaseName.isEmpty()) {
        logger.trace("Saving user and division using new MongoDB connection");

        MongoClient mongoClient = new MongoClient(mongoAddress, mongoCredential);

        DB mongoDB = mongoClient.getDB(databaseName);
        if (mongoClient.getDatabaseNames().contains(databaseName)) {
            logger.warn("The database already contains the defined collection, dropping content.");
            mongoDB.dropDatabase();
        }

        try {
            if (user != null) {
                logger.debug("Storing user");
                DBObject userObject = (DBObject) mappingMongoConverter.convertToMongoType(user);
                userObject.put("_class", user.getClass().getCanonicalName());
                mongoDB.getCollection(user.getClass().getSimpleName().toLowerCase()).insert(userObject);
            }

            if (division != null) {
                logger.debug("Storing division");
                DBObject divisionObject = (DBObject) mappingMongoConverter.convertToMongoType(division);
                divisionObject.put("_class", division.getClass().getCanonicalName());
                mongoDB.getCollection(division.getClass().getSimpleName().toLowerCase()).insert(divisionObject);
            }

            if (settings != null) {
                logger.debug("Storing settings");
                settings.saveSettings(user, null);
                DBObject settingsObject = (DBObject) mappingMongoConverter.convertToMongoType(settings);
                settingsObject.put("_class", settings.getClass().getCanonicalName());
                mongoDB.getCollection(settings.getClass().getSimpleName().toLowerCase()).insert(settingsObject);
            }

            logger.info("Successfully saved root division and super admin");
            return true;
        } catch (MongoException e) {
            logger.warn("Unable to store root division and super admin in database");
            return false;
        } finally {
            mongoClient.close();
        }
    } else {
        logger.warn(
                "Unable to save super admin and new root division, because the new MongoDB connection is not available");
        return false;
    }
}

From source file:edu.umass.cs.gnsserver.database.MongoRecords.java

License:Apache License

/**
 * @param nodeID/*  ww  w  .j a v  a 2 s . co m*/
 */
public static void dropNodeDatabase(String nodeID) {
    MongoClient mongoClient;
    try {
        mongoClient = new MongoClient("localhost");
    } catch (UnknownHostException e) {
        DatabaseConfig.getLogger().log(Level.SEVERE, "Unable to open Mongo DB: {0}", e.getMessage());
        return;
    }
    String dbName = DBROOTNAME + sanitizeDBName(nodeID);
    mongoClient.dropDatabase(dbName);

    List<String> names = mongoClient.getDatabaseNames();
    for (String name : names) {
        if (name.startsWith(dbName)) {
            mongoClient.dropDatabase(name);
        }
    }

    System.out.println("Dropped DB " + dbName);
}

From source file:example.QuickTourAdmin.java

License:Apache License

public static void main(String[] args) throws Exception {

    // connect to the local database server 
    MongoClient mongoClient = new MongoClient();

    // Authenticate - optional
    // boolean auth = db.authenticate("foo", "bar");

    // get db names
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);//from   w  w  w  . j ava 2  s  .c o m
    }

    // get a db
    DB db = mongoClient.getDB("com_mongodb_MongoAdmin");

    // do an insert so that the db will really be created.  Calling getDB() doesn't really take any
    // action with the server 
    db.getCollection("testcollection").insert(new BasicDBObject("i", 1));
    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }

    // drop a database
    mongoClient.dropDatabase("com_mongodb_MongoAdmin");

    for (String s : mongoClient.getDatabaseNames()) {
        System.out.println(s);
    }
}

From source file:localdomain.localhost.MongoDbTroubleshooter.java

License:Open Source License

public void run() throws Exception {
    try (PrintWriter writer = new PrintWriter(System.out)) {

        MongoClientURI mongoClientUri = new MongoClientURI(uri);
        writer.println("" + "host=" + mongoClientUri.getHosts() + ",username=" + mongoClientUri.getUsername()
                + ",database=" + mongoClientUri.getDatabase() + ",collection=" + mongoClientUri.getCollection()
                + "");

        writer.println();/*from   ww  w  .j  a v a  2  s.c  o  m*/
        writer.println();

        writer.println("# MongoClient");
        writer.println();

        MongoClient mongoClient = new MongoClient(mongoClientUri);
        writer.println("" + mongoClient + "");

        writer.println();
        writer.println();
        writer.println("# Databases");
        writer.println();

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

        }

        writer.println();
        writer.println();
        writer.println("# Database");
        writer.println();

        DB db = mongoClient.getDB(mongoClientUri.getDatabase());
        writer.println("DB: " + db.getName() + "");

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

        } else {

            for (String collection : myCollections) {
                DBCollection dbCollection = db.getCollection(collection);
                writer.println("* " + dbCollection.getName() + " - " + dbCollection.getCount() + " entries");
            }
        }
    }
}