Example usage for com.mongodb MongoClient MongoClient

List of usage examples for com.mongodb MongoClient MongoClient

Introduction

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

Prototype

public MongoClient(final MongoClientURI uri, final MongoDriverInformation mongoDriverInformation) 

Source Link

Document

Creates a Mongo described by a URI.

Usage

From source file:com.br.tales.mongo.MongoDBConnection.java

private MongoDBConnection() {
    client = new MongoClient(ipServer, port);
    dataBase = client.getDatabase(dbName);
}

From source file:com.bugull.mongo.BuguConnection.java

License:Apache License

private void doConnect() throws UnknownHostException, DBConnectionException {
    if (host != null && port != 0) {
        ServerAddress sa = new ServerAddress(host, port);
        if (options != null) {
            mc = new MongoClient(sa, options);
        } else {/*from  w w  w  .  j  a va 2 s. com*/
            mc = new MongoClient(sa);
        }
    } else if (replicaSet != null) {
        if (options != null) {
            mc = new MongoClient(replicaSet, options);
        } else {
            mc = new MongoClient(replicaSet);
        }
        if (readPreference != null) {
            mc.setReadPreference(readPreference);
        }
    }
    if (mc != null) {
        db = mc.getDB(database);
    } else {
        throw new DBConnectionException(
                "Can not get database instance! Please ensure connected to mongoDB correctly.");
    }
}

From source file:com.buzz.buzzdata.MongoBuzz.java

public MongoBuzz(String host, int port, String db, String userName, String passwd) throws UnknownHostException {
    MongoCredential credential = MongoCredential.createMongoCRCredential(userName, db, passwd.toCharArray());
    mongoClient = new MongoClient(new ServerAddress(host, port), Arrays.asList(credential));
    mongoDB = mongoClient.getDB(db);/*w w w .ja  v a 2  s .c  o  m*/
}

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 ww.  j a v  a  2  s . co  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.camel.realtimelog.PersistenceMongoAccessor.java

License:Open Source License

private void setMongoClient() {
    if (mongo == null) {
        try {/*from ww  w .j  a v  a 2s  .  c  om*/
            ServerAddress sa = new ServerAddress(serverAddress);
            MongoCredential mc = MongoCredential.createMongoCRCredential(username, dbName,
                    password.toCharArray());
            List<MongoCredential> mcs = new ArrayList<MongoCredential>();
            mcs.add(mc);
            mongo = new MongoClient(sa, mcs);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        db = mongo.getDB(dbName);
        logs = db.getCollection(collectionName);
    }
}

From source file:com.camillepradel.movierecommender.model.DataManager.java

public static MongoClient getMongoClient() {
    if (DataManager.mongoClient == null) {
        DataManager.mongoClient = new MongoClient("localhost", 27017);
    }//w  w  w  .  j  a  va2  s . c  o  m
    return DataManager.mongoClient;
}

From source file:com.centurylink.mdw.dataaccess.DatabaseAccess.java

License:Apache License

private static synchronized void openMongoDbClient() {
    if (mongoClient == null) {
        String mongoHost = PropertyManager.getProperty(PropertyNames.MDW_MONGODB_HOST);
        int mongoPort = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_PORT, 27017);
        int maxConnections = PropertyManager.getIntegerProperty(PropertyNames.MDW_MONGODB_POOLSIZE,
                PropertyManager.getIntegerProperty(PropertyNames.MDW_DB_POOLSIZE, 100));

        MongoClientOptions.Builder options = MongoClientOptions.builder();
        options.socketKeepAlive(true);//from w  w  w.  j a  va 2 s  .  co  m
        if (maxConnections > 100) // MongoClient default is 100 max connections per host
            options.connectionsPerHost(maxConnections);

        mongoClient = new MongoClient(new ServerAddress(mongoHost, mongoPort), options.build());
        LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString());
    }
}

From source file:com.centurylink.mdw.mongo.MongoDocumentDb.java

License:Apache License

@Override
public void initializeDbClient() {
    if (mongoClient == null) {
        MongoClientOptions.Builder options = MongoClientOptions.builder();
        if (maxConnections > 100) // MongoClient default is 100 max connections per host
            options.connectionsPerHost(maxConnections);

        mongoClient = new MongoClient(new ServerAddress(dbHost, dbPort), options.build());

        for (String name : mongoClient.getDatabase("mdw").listCollectionNames()) {
            createMongoDocIdIndex(name);
        }/*from w w w.  j  a va2s  . c  om*/
        LoggerUtil.getStandardLogger().info(mongoClient.getMongoClientOptions().toString());
    }
}

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 . ja  v a2s. c o  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.chdi.kundenverwaltung.db.MongoConnectioFactory.java

public MongoConnectioFactory() {

    try {//from   w  w  w  .  j a  va  2 s  . c om
        mongoClient = new MongoClient(hostName, port);
    } catch (UnknownHostException ex) {
        System.err.println("---> " + ex.getMessage());
    }

}