Example usage for com.mongodb Mongo getDatabaseNames

List of usage examples for com.mongodb Mongo getDatabaseNames

Introduction

In this page you can find the example usage for com.mongodb Mongo 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:net.cit.tetrad.rrd.batch.TetradRrdInitializer.java

License:Open Source License

/**
 * TetradRrd ? ?  /*from  www . ja  va  2s.c om*/
 * @throws Exception
 */
public void install() throws Exception {
    try {
        // ?  ?  ?
        List<Device> devices = dataAccessObjectForMongo.readDeviceList();

        for (Device device : devices) {
            // ?  ??  RrdDb ?
            tetradRrdDbService.createTetradRrdDb(device);

            // ?? ??  ???  ?
            ConcurrentMap<Integer, MongoWrapper> mongoGroup = MongoInMemory.getMongoGroup();
            Mongo mongo = mongoGroup.get(device.getIdx()).getMongo();

            List<String> deviceNames = mongo.getDatabaseNames();
            for (String databaseName : deviceNames) {
                // ?  ????  RrdDb ?
                tetradRrdDbService.createTetradRrdDb(device, databaseName);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:net.cit.tetrad.rrd.service.TetradRrdDbServiceImpl.java

License:Open Source License

/**
 *  ?  rrdDb? ?.//  w ww .  ja v  a 2s . co  m
 * @param device
 */
public void insertTetradRrdDb(Mongo mongo, Device device) throws FileNotFoundException {
    logger.info("=====================================");
    logger.info("start insrt rrd, Device Id : " + device.getIdx());
    logger.debug("ip : " + device.getIp() + ", port : " + device.getPort());
    Map<String, Object> dbStatusFromMongo = new HashMap<String, Object>(); // ? ???? status  
    Map<String, Object> serverStatusFromMongo = new HashMap<String, Object>(); // ? ?? status 
    List<DbStatus> dbInfos = new ArrayList<DbStatus>();

    double dbObjects = 0;
    double dbAvgObjSize = 0;
    double dbDataSize = 0;
    double dbStorageSize = 0;
    double dbNumExtents = 0;
    double dbCount = 0;
    double dbIndexes = 0;
    double dbIndexSize = 0;
    double dbFileSize = 0;
    double dbNsSizeMB = 0;
    double dbSumTimeLocked_r = 0;
    double dbSumTimeLocked_w = 0;

    try {
        CommandResult serverResult = mongoStatusToMonitor.getCommandResult(mongo, device, SERVER_STATUS_COMMAND,
                "admin");

        try {
            // ?? ???  ?
            List<String> dbNames = mongo.getDatabaseNames();
            Pattern patt = Pattern.compile(Config.DBNAME_PATTERN);
            for (String databaseName : dbNames) {
                // ?  DB RrdDB ? Mongodb? insert
                Matcher m = patt.matcher(databaseName);
                if (!m.matches()) {
                    continue;
                }

                // ?  ????  RrdDb ??                
                dbStatusFromMongo = insertTetradRrdDb(mongo, device, databaseName, serverResult);
                DbStatus dbstats = new DbStatus();
                BeanUtils.populate(dbstats, dbStatusFromMongo);

                dbstats.setDb(databaseName);
                dbstats.setGroupCode(device.getGroupCode());
                dbstats.setDeviceCode(device.getIdx());
                dbstats.setType(device.getType());

                dbCount++;
                dbObjects += dbstats.getObjects();
                dbAvgObjSize += dbstats.getAvgObjSize();
                dbDataSize += dbstats.getDataSize();
                dbStorageSize += dbstats.getStorageSize();
                dbNumExtents += dbstats.getNumExtents();
                dbIndexes += dbstats.getIndexes();
                dbIndexSize += dbstats.getIndexSize();
                dbFileSize += dbstats.getFileSize();
                dbNsSizeMB += dbstats.getNsSizeMB();
                dbSumTimeLocked_r += dbstats.getLocks_timeLockedMicros_r();
                dbSumTimeLocked_w += dbstats.getLocks_timeLockedMicros_w();

                daoForMongo.insertDbStatusInfo(dbstats);
                dbInfos.add(dbstats);
            }
        } catch (MongoException e) {
            e.printStackTrace();
            logger.error(e, e);
            ReInitializeMongoInMemory.reInit(device, e.toString());
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e, e);
        }

        try {
            // ? ?  ?
            DBObject locks = (DBObject) serverResult.get("locks");

            serverResult.remove("locks");
            JasonUtil.getEntryValue(serverResult, "", serverStatusFromMongo);

            if (locks != null) {
                DBObject systemLock = (DBObject) locks.get(".");
                JasonUtil.getEntryValue(systemLock, "locks_", serverStatusFromMongo);
            }

            // ??? ?  ?  ?   .
            int groupCode = device.getGroupCode();
            String uid = device.getUid();
            String type = device.getType();
            String key = groupCode + "_" + uid + "_" + type;
            String regtime = TimestampUtil.readCurrentTime();
            serverStatusFromMongo.put(SERVERSTATUS_ID, key);
            serverStatusFromMongo.put(SERVERSTATUS_REGTIME, regtime);
            serverStatusFromMongo.put(DEVICE_GROUPCODE, device.getGroupCode());
            serverStatusFromMongo.put(DEVICECODE, device.getIdx());
            serverStatusFromMongo.put(SERVERSTATUS_TYPE, device.getType());
            serverStatusFromMongo.put(SERVERSTATUS_IP, device.getIp());
            serverStatusFromMongo.put(SERVERSTATUS_PORT, device.getPort());
            serverStatusFromMongo.put(SERVERSTATUS_DBOBJECTS, dbObjects);
            serverStatusFromMongo.put(SERVERSTATUS_DBAVGOBJSIZE, dbAvgObjSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBDATASIZE, dbDataSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBSTORAGESIZE, dbStorageSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBNUMEXTENTS, dbNumExtents);
            serverStatusFromMongo.put(SERVERSTATUS_DBCOUNT, dbCount);
            serverStatusFromMongo.put(SERVERSTATUS_DBINDEXES, dbIndexes);
            serverStatusFromMongo.put(SERVERSTATUS_DBINDEXSIZE, dbIndexSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBFILESIZE, dbFileSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBNSSIZEMB, dbNsSizeMB);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_DBDATASIZE, dbDataSize);
            serverStatusFromMongo.put(SERVERSTATUS_DIFF_DBINDEXSIZE, dbIndexSize);
            serverStatusFromMongo.put(SERVERSTATUS_DBSUMLOCKSLOCKED_R, dbSumTimeLocked_r);
            serverStatusFromMongo.put(SERVERSTATUS_DBSUMLOCKSLOCKED_W, dbSumTimeLocked_w);

            InitialRrdService rrdSvc = new InitialRrdService();
            rrdSvc.setDataValues(serverStatusFromMongo);
            rrdSvc.executeServerStatus(device);

            daoForMongo.setGloballLockPageFaults(serverStatusFromMongo);
            daoForMongo.setOpcounter(serverStatusFromMongo);

            // main dashboard ?  ?? 
            ServerStatus serverStatusInfo = new ServerStatus();
            BeanUtils.populate(serverStatusInfo, serverStatusFromMongo);

            // main dashboard ? ? ?? 
            serverStatusInfo.setDbInfos(dbInfos);
            serverStatusInfo.setError(1);
            daoForMongo.insertServerStatusInfo(serverStatusInfo);

            //  ?  ?? 
            String detailKey = key + "_" + regtime;
            serverStatusInfo.setId(detailKey);
            daoForMongo.insertDetailServerStatusInfo(serverStatusInfo);

            // main dashboard  /  ??             
            criticalOperation.settingAlarm(device, serverStatusFromMongo);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e, e);
        }
        exportXmlIfNecessary(device);
    } catch (MongoException e) {
        e.printStackTrace();
        logger.error(e, e);
        insertConnectionTimeoutError(device);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        logger.error(e, e);
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
        logger.error(e, e);
        if (mongo == null) {
            insertConnectionTimeoutError(device);
            throw new MongoException("Mongo Object is null");
        }
    }
    logger.info("end insrt rrd");
}

From source file:org.apache.hadoop.contrib.mongoreduce.MongoInputFormat.java

License:Apache License

public static String[] hostsForShard(String shardName, boolean primaryOk)
        throws UnknownHostException, MongoException {

    ArrayList<String> hosts = new ArrayList<String>();

    String[] parts = shardName.split("/");
    if (parts.length == 1) { // no replicas
        hosts.add(shardName);//from  w w w .j a v a  2s .  c  o m
    } else { // replicas

        // get first or only host listed
        String host = parts[1].split(",")[0];
        Mongo h = new Mongo(host);
        List<ServerAddress> addresses = h.getServerAddressList();
        h.close();
        h = null;

        // only one node in replica set ... - use it
        if (addresses.size() == 1) {
            ServerAddress addr = addresses.get(0);
            hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort()));
        }

        else {
            for (ServerAddress addr : addresses) {

                // use secondaries and primaries
                if (primaryOk) {
                    hosts.add(addr.getHost() + ":" + Integer.toString(addr.getPort()));
                }

                // only use secondaries
                else {
                    String haddr = addr.getHost() + ":" + Integer.toString(addr.getPort());
                    h = new Mongo(haddr);
                    if (!(Boolean) h.getDB(h.getDatabaseNames().get(0)).command(cmd).get("ismaster")) {
                        hosts.add(haddr);
                    }
                }
            }
        }
    }

    return hosts.toArray(new String[0]);
}

From source file:org.apache.isis.objectstore.nosql.db.mongo.DemoMongo.java

License:Apache License

public void installed() throws Exception {

    final Mongo m = new Mongo();

    for (final String s : m.getDatabaseNames()) {
        System.out.println(s);// w  ww. j  a  v a2  s. co  m
    }

    /*
     * Mongo m = new Mongo( "localhost" ); Mongo m = new Mongo( "localhost"
     * , 27017 );
     */
    m.dropDatabase("mydb");

    System.out.println("\n...");
    for (final String s : m.getDatabaseNames()) {
        System.out.println(s);
    }

    final DB db = m.getDB("mydb");
    /*
     * DBCollection coll = db.getCollection("testCollection1"); coll =
     * db.getCollection("testCollection2");
     */

    final DBCollection coll = db.getCollection("testCollection1");

    final BasicDBObject doc = new BasicDBObject();

    doc.put("name", "MongoDB");
    doc.put("type", "database");
    doc.put("count", 1);

    final BasicDBObject info = new BasicDBObject();

    info.put("x", 203);
    info.put("y", 102);

    doc.put("info", info);

    coll.insert(doc);

    final Set<String> colls = db.getCollectionNames();

    for (final String s : colls) {
        System.out.println(s);
    }

}

From source file:org.apache.jackrabbit.oak.upgrade.cli.container.MongoNodeStoreContainer.java

License:Apache License

private static boolean testMongoAvailability() {
    Mongo mongo = null;
    try {// w  ww .  ja  va2 s.com
        MongoClientURI uri = new MongoClientURI(MONGO_URI + "?connectTimeoutMS=3000");
        mongo = new MongoClient(uri);
        mongo.getDatabaseNames();
        return true;
    } catch (Exception e) {
        return false;
    } finally {
        if (mongo != null) {
            mongo.close();
        }
    }
}

From source file:org.broad.igv.plugin.mongocollab.MongoCollabPlugin.java

License:Open Source License

/**
 * Check whether the database/collection specified by the given {@code locator}
 * exists./*  ww  w.  ja  v  a 2s.  c  o  m*/
 * @param locator
 * @return An integer consisting of 2 flags:
 * DB_EXISTS
 * COLLECTION_EXISTS
 *
 * with each set if the DB/COLLECTION exists. !DB_EXISTS && COLLECTION_EXISTS should never happen
 */
public static int checkDestinationExists(Locator locator) {
    Mongo mongo = getMongo(locator.host, locator.port);
    List<String> dbNames = mongo.getDatabaseNames();
    boolean dbExists = dbNames.indexOf(locator.dbName) >= 0;

    if (!dbExists) {
        return 0;
    }

    int result = DB_EXISTS;
    DB db = mongo.getDB(locator.dbName);
    Set<String> collections = db.getCollectionNames();
    result |= collections.contains(locator.collectionName) ? COLLECTION_EXISTS : 0;

    return result;
}

From source file:org.eclipse.birt.data.oda.mongodb.impl.MDbConnection.java

License:Open Source License

private static Boolean existsDatabase(Mongo mongoInstance, String dbName, Properties connProps)
        throws OdaException {
    // check if user authentication is needed
    String username = MongoDBDriver.getUserName(connProps);
    if (username != null && !username.isEmpty()) {
        DB adminDb = mongoInstance.getDB("admin"); //$NON-NLS-1$
        try {/*from   w w w .  j a  va  2 s  .  c o m*/
            // login to admin db, so to get the existing database names
            authenticateDB(adminDb, connProps);
        } catch (OdaException ex) {
            // not able to determine if db exists; specified user is probably not a valid login user in admin db
            return null;
        }
    }

    try {
        return mongoInstance.getDatabaseNames().contains(dbName);
    } catch (MongoException ex) {
        throw new OdaException(ex); // unable to get db names
    }
}

From source file:org.greenmongoquery.db.service.impl.MongoServiceImpl.java

License:Open Source License

@Override
public List<String> getDbs(Mongo mongo) {
    return mongo.getDatabaseNames();

}

From source file:org.iternine.jeppetto.testsupport.db.MongoDatabase.java

License:Apache License

@Override
public void close() {
    if (mongoDbName == null) {
        return;/*w  w w .  ja  v a2  s. c  o  m*/
    }

    try {
        Mongo mongo = new Mongo("127.0.0.1", mongoDbPort);
        DB db = mongo.getDB(mongoDbName);

        db.resetError();
        db.dropDatabase();

        DBObject err = db.getLastError();
        if (err != null && err.get("err") != null) {
            logger.error("Could not drop database {}: {}", mongoDbName, err);
        }

        mongo.dropDatabase(mongoDbName);

        if (mongo.getDatabaseNames().contains(mongoDbName)) {
            logger.error("Database {} will not go away!", mongoDbName);
        }
    } catch (UnknownHostException e) {
        // weird
    } catch (MongoException e) {
        logger.warn("Could not drop database {}: {}", mongoDbName, e.getMessage());
    }
}

From source file:org.jwebsocket.util.ConnectionManager.java

License:Apache License

/**
 * Return TRUE of the given mongodb connection object is valid, FALSE
 * otherwise/*  w w w.  j  a v a  2s .  c om*/
 *
 * @param aConnection
 * @return
 */
public static boolean isValid(Mongo aConnection) {
    try {
        aConnection.getDatabaseNames();
    } catch (Exception lEx) {
        return false;
    }

    return true;
}