Example usage for com.mongodb MongoClient getDB

List of usage examples for com.mongodb MongoClient getDB

Introduction

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

Prototype

@Deprecated 
public DB getDB(final String dbName) 

Source Link

Document

Gets a database object.

Usage

From source file:com.bryanreinero.purchase.PurchaseDAO.java

License:Open Source License

public PurchaseDAO(MongoClient mongo) {
    principals = mongo.getDB("twophase").getCollection("principals");
    transactions = mongo.getDB("twophase").getCollection("transactions");
}

From source file:com.btmatthews.atlas.core.dao.mongo.MongoDAO.java

License:Apache License

/**
 * Initialise the Mongo data access object setting concrete class to
 * {@code clazz}./*from w w  w .j a v  a  2s .c o  m*/
 */
public MongoDAO(final MongoClient mongoClient, final ObjectMapper objectMapper, final Class<ID> keyClass,
        final Class<T> objectClass, final String databaseName, final String collectionName) {
    if (mongoClient == null) {
        throw new IllegalArgumentException("mongoClient must not be null");
    }
    if (objectMapper == null) {
        throw new IllegalArgumentException("objectMapper must not be null");
    }
    if (keyClass == null) {
        throw new IllegalArgumentException("keyClass must not be null");
    }
    if (objectClass == null) {
        throw new IllegalArgumentException("objectClass must not be null");
    }
    if (databaseName == null && databaseName.length() > 0) {
        throw new IllegalArgumentException("databseName must not be null or empty");
    }
    if (collectionName == null && collectionName.length() > 0) {
        throw new IllegalArgumentException("collectionName must not be null or empty");
    }

    this.databaseName = databaseName;
    this.collectionName = collectionName;

    final DB db = mongoClient.getDB(databaseName);
    final DBCollection collection = db.getCollection(collectionName);
    this.collection = (JacksonDBCollection<I, ID>) JacksonDBCollection.wrap(collection, objectClass, keyClass,
            objectMapper);
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private CommandResult runDBCmd(final String host, final int port, final String database, final String cmd)
        throws Exception {
    MongoClient dbClient = null;
    try {//from w  w  w.  j a v a 2 s  .c om
        dbClient = setupDbClient(host, port);
        DB db = dbClient.getDB(database);
        return db.command(cmd);
    } finally {
        if (dbClient != null) {
            dbClient.close();
        }
    }
}

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

final boolean isConfigServer(final String host, final int port) {

    boolean isConfigServer = false;

    MongoClient dbClient = null;

    try {//  ww  w  .  ja  va  2  s .  c  o m
        dbClient = setupDbClient(host, port);
        final DB configDB = dbClient.getDB("config");
        if (configDB.getCollectionFromString("mongos").find().hasNext()) {
            isConfigServer = true;
        }
    } finally {
        if (dbClient != null) {
            dbClient.close();
        }
    }
    return isConfigServer;
}

From source file:com.ca.apm.mongo.ShardCluster.java

License:Open Source License

private List<String> getShardsFromConfig(final String host, final int port) {

    final List<String> shardList = new ArrayList<String>();

    MongoClient dbClient = null;

    try {//w ww.ja va 2  s . co m
        dbClient = setupDbClient(host, port);

        final DB configDB = dbClient.getDB("config");
        final DBCursor shardsCursor = configDB.getCollectionFromString("shards").find();
        while (shardsCursor.hasNext()) {
            final DBObject dbo = shardsCursor.next();
            String shards = (String) dbo.get("host");
            String[] shardMembers = getShardMembers(shards);
            for (String member : shardMembers) {
                shardList.add(member);
            }
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception getting shards from cfg servers: {0}", e);
    } finally {
        if (dbClient != null) {
            dbClient.close();
        }
    }
    return shardList;
}

From source file:com.ca.apm.mongo.ShardCluster.java

License:Open Source License

private List<String> getMongosFromConfig(final String host, final int port) {

    final List<String> shardRouters = new ArrayList<String>();

    MongoClient dbClient = null;

    try {//from   w w w  .j  a va 2  s . c  om
        dbClient = setupDbClient(host, port);
        final DB configDB = dbClient.getDB("config");
        final DBCursor mongosCursor = configDB.getCollectionFromString("mongos").find();
        while (mongosCursor.hasNext()) {
            final DBObject dbo = mongosCursor.next();
            final String mongos = (String) dbo.get("_id");
            shardRouters.add(mongos);
        }
    } catch (Exception e) {
        logger.log(Level.WARNING, "Exception getting mongos from cfg server(s): {0}", e);
    } finally {
        if (dbClient != null) {
            dbClient.close();
        }
    }
    return shardRouters;
}

From source file:com.ca.apm.mongo.test.MongoReplicaSetForTestFactory.java

License:Open Source License

private void initializeReplicaSet(Entry<String, List<IMongodConfig>> entry) throws Exception {
    String replicaName = entry.getKey();
    List<IMongodConfig> mongoConfigList = entry.getValue();

    if (mongoConfigList.size() < 3) {
        throw new Exception("A replica set must contain at least 3 members.");
    }//from w  w  w.j  a  v  a  2s  . c o  m
    // Create 3 mongod processes
    for (IMongodConfig mongoConfig : mongoConfigList) {
        if (!mongoConfig.replication().getReplSetName().equals(replicaName)) {
            throw new Exception("Replica set name must match in mongo configuration");
        }
        MongodStarter starter = MongodStarter.getDefaultInstance();
        MongodExecutable mongodExe = starter.prepare(mongoConfig);
        MongodProcess process = mongodExe.start();
        mongodProcessList.add(process);
    }
    Thread.sleep(1000);
    MongoClientOptions mo = MongoClientOptions.builder().autoConnectRetry(true).build();
    MongoClient mongo = new MongoClient(
            new ServerAddress(mongoConfigList.get(0).net().getServerAddress().getHostName(),
                    mongoConfigList.get(0).net().getPort()),
            mo);
    DB mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

    CommandResult cr = mongoAdminDB.command(new BasicDBObject("isMaster", 1));
    logger.info("isMaster: " + cr);

    // Build BSON object replica set settings
    DBObject replicaSetSetting = new BasicDBObject();
    replicaSetSetting.put("_id", replicaName);
    BasicDBList members = new BasicDBList();
    int i = 0;
    for (IMongodConfig mongoConfig : mongoConfigList) {
        DBObject host = new BasicDBObject();
        host.put("_id", i++);
        host.put("host",
                mongoConfig.net().getServerAddress().getHostName() + ":" + mongoConfig.net().getPort());
        members.add(host);
    }

    replicaSetSetting.put("members", members);
    logger.info(replicaSetSetting.toString());
    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate", replicaSetSetting));
    logger.info("replSetInitiate: " + cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.info("replSetGetStatus: " + cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.info("Waiting for 3 seconds...");
        Thread.sleep(1000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        logger.info("replSetGetStatus: " + cr);
    }

    mongo.close();
    mongo = null;
}

From source file:com.cetsoft.caudit.observers.MongoObserver.java

License:Apache License

/**
 * This method is called when information about an Mongo
 * which was previously requested using an asynchronous
 * interface becomes available./*w  ww .  j av a 2s.  co  m*/
 *
 * @param connectionString the connection string
 * @param dbName the db name
 * @param port the port
 * @param collectionName the collection name
 */
public MongoObserver(String connectionString, String dbName, String port, String collectionName) {
    try {
        MongoClient mongo = new MongoClient(connectionString, Integer.parseInt(port));
        DB db = mongo.getDB(dbName);
        collection = db.getCollection(collectionName);
    } catch (NumberFormatException e) {
        throw new RuntimeException(e);
    } catch (UnknownHostException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.crosstreelabs.cognitio.service.mongo.MongoCatalogueService.java

License:Apache License

public MongoCatalogueService(final MongoClient client, final HostService hostService) {
    this.client = client;
    this.hostService = hostService;
    db = client.getDB("cognitio");
    if (!db.collectionExists("catalogue")) {
        catalogue = db.createCollection("catalogue", null);
        catalogue.createIndex(new BasicDBObject("location_hash", 1), new BasicDBObject("unique", true));
    } else {/*from   w  ww . j a  v  a 2 s.co m*/
        catalogue = db.getCollection("catalogue");
    }
}

From source file:com.crosstreelabs.cognitio.service.mongo.MongoHostService.java

License:Apache License

public MongoHostService(final MongoClient client) {
    this.client = client;
    db = client.getDB("cognitio");
    if (!db.collectionExists("hosts")) {
        hosts = db.createCollection("hosts", null);
        hosts.createIndex(new BasicDBObject("host", 1), new BasicDBObject("unique", true));
    } else {/*from  w w  w. j  a  va2 s. co  m*/
        hosts = db.getCollection("hosts");
    }
}