Example usage for com.mongodb MongoClientOptions builder

List of usage examples for com.mongodb MongoClientOptions builder

Introduction

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

Prototype

public static Builder builder() 

Source Link

Document

Creates a builder instance.

Usage

From source file:simple.crawler.mongo.CrawlingDB.java

License:Open Source License

public CrawlingDB(String dbName, ServerAddress address) {
    this.dbName = dbName;
    MongoClientOptions options = new MongoClientOptions.Builder().build();
    this.client = new MongoClient(address, options);
}

From source file:streamflow.datastore.mongodb.config.MongoDatastoreModule.java

License:Apache License

@Provides
public Mongo providesMongoClient(DatastoreConfig datastoreConfig) {
    MongoClient mongoClient = null;//from   w  w w  .  j a  v  a  2s  .  co  m
    MongoClientOptions.Builder clientOptions = MongoClientOptions.builder();

    String serverAddressHost = datastoreConfig.getProperty("host", String.class);
    if (serverAddressHost == null) {
        serverAddressHost = "localhost";
    }

    Integer serverAddressPort = datastoreConfig.getProperty("port", Integer.class);
    if (serverAddressPort == null) {
        serverAddressPort = 27017;
    }

    Integer acceptableLatencyDifference = datastoreConfig.getProperty("acceptableLatencyDifference",
            Integer.class);
    if (acceptableLatencyDifference != null) {
        clientOptions.acceptableLatencyDifference(acceptableLatencyDifference);
    }

    Integer connectTimeout = datastoreConfig.getProperty("connectTimeout", Integer.class);
    if (connectTimeout != null) {
        clientOptions.connectTimeout(connectTimeout);
    }

    Integer connectionsPerHost = datastoreConfig.getProperty("connectionsPerHost", Integer.class);
    if (connectionsPerHost != null) {
        clientOptions.connectionsPerHost(connectionsPerHost);
    }

    Boolean cursorFinalizerEnabled = datastoreConfig.getProperty("acceptableLatencyDifference", Boolean.class);
    if (cursorFinalizerEnabled != null) {
        clientOptions.cursorFinalizerEnabled(cursorFinalizerEnabled);
    }

    Integer heartbeatConnectRetryFrequency = datastoreConfig.getProperty("heartbeatConnectRetryFrequency",
            Integer.class);
    if (heartbeatConnectRetryFrequency != null) {
        clientOptions.heartbeatConnectRetryFrequency(heartbeatConnectRetryFrequency);
    }

    Integer heartbeatConnectTimeout = datastoreConfig.getProperty("heartbeatConnectTimeout", Integer.class);
    if (heartbeatConnectTimeout != null) {
        clientOptions.heartbeatConnectTimeout(heartbeatConnectTimeout);
    }

    Integer heartbeatFrequency = datastoreConfig.getProperty("heartbeatFrequency", Integer.class);
    if (heartbeatFrequency != null) {
        clientOptions.heartbeatFrequency(heartbeatFrequency);
    }

    Integer heartbeatSocketTimeout = datastoreConfig.getProperty("heartbeatSocketTimeout", Integer.class);
    if (heartbeatSocketTimeout != null) {
        clientOptions.heartbeatSocketTimeout(heartbeatSocketTimeout);
    }

    Integer heartbeatThreadCount = datastoreConfig.getProperty("heartbeatThreadCount", Integer.class);
    if (heartbeatThreadCount != null) {
        clientOptions.heartbeatThreadCount(heartbeatThreadCount);
    }

    Integer maxConnectionIdleTime = datastoreConfig.getProperty("maxConnectionIdleTime", Integer.class);
    if (maxConnectionIdleTime != null) {
        clientOptions.maxConnectionIdleTime(maxConnectionIdleTime);
    }

    Integer maxConnectionLifeTime = datastoreConfig.getProperty("maxConnectionLifeTime", Integer.class);
    if (maxConnectionLifeTime != null) {
        clientOptions.maxConnectionLifeTime(maxConnectionLifeTime);
    }

    Integer maxWaitTime = datastoreConfig.getProperty("maxWaitTime", Integer.class);
    if (maxWaitTime != null) {
        clientOptions.maxWaitTime(maxWaitTime);
    }

    Integer minConnectionsPerHost = datastoreConfig.getProperty("minConnectionsPerHost", Integer.class);
    if (minConnectionsPerHost != null) {
        clientOptions.minConnectionsPerHost(minConnectionsPerHost);
    }

    Boolean socketKeepAlive = datastoreConfig.getProperty("socketKeepAlive", Boolean.class);
    if (socketKeepAlive != null) {
        clientOptions.socketKeepAlive(socketKeepAlive);
    }

    Integer socketTimeout = datastoreConfig.getProperty("socketTimeout", Integer.class);
    if (socketTimeout != null) {
        clientOptions.socketTimeout(socketTimeout);
    }

    Integer threadsAllowedToBlockForConnectionMultiplier = datastoreConfig
            .getProperty("threadsAllowedToBlockForConnectionMultiplier", Integer.class);
    if (threadsAllowedToBlockForConnectionMultiplier != null) {
        clientOptions
                .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
    }

    try {
        ServerAddress serverAddress = new ServerAddress(serverAddressHost, serverAddressPort);

        // Initialize the Mongo connection with the specified address and options
        mongoClient = new MongoClient(serverAddress, clientOptions.build());
    } catch (UnknownHostException ex) {
        LOG.error("Exception occurred while building Mongo client connection", ex);
    }

    return mongoClient;
}

From source file:test.elasticsearch.plugin.river.mongodb.RiverMongoDBTestAsbtract.java

License:Apache License

private void initMongoInstances() throws Exception {
    logger.debug("*** initMongoInstances ***");
    CommandResult cr;//from w  w w.j a  v a  2 s .  c  o m

    // Create 3 mongod processes
    mongodConfig1 = new MongodConfig(new GenericVersion(mongoVersion),
            new Net(mongoPort1, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20),
            new Timeout());
    MongodStarter starter = MongodStarter.getDefaultInstance();
    mongodExe1 = starter.prepare(mongodConfig1);
    mongod1 = mongodExe1.start();
    mongodConfig2 = new MongodConfig(new GenericVersion(mongoVersion),
            new Net(mongoPort2, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20),
            new Timeout());
    mongodExe2 = starter.prepare(mongodConfig2);
    mongod2 = mongodExe2.start();
    mongodConfig3 = new MongodConfig(new GenericVersion(mongoVersion),
            new Net(mongoPort3, Network.localhostIsIPv6()), new Storage(null, REPLICA_SET_NAME, 20),
            new Timeout());
    mongodExe3 = starter.prepare(mongodConfig3);
    mongod3 = mongodExe3.start();
    String server1 = Network.getLocalHost().getHostName() + ":" + mongodConfig1.net().getPort();
    String server2 = Network.getLocalHost().getHostName() + ":" + mongodConfig2.net().getPort();
    String server3 = Network.getLocalHost().getHostName() + ":" + mongodConfig3.net().getPort();
    logger.debug("Server #1: {}", server1);
    logger.debug("Server #2: {}", server2);
    logger.debug("Server #3: {}", server3);
    Thread.sleep(2000);
    MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000)
            .socketTimeout(60000).build();
    mongo = new MongoClient(
            new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig1.net().getPort()), mco);
    mongoAdminDB = mongo.getDB(ADMIN_DATABASE_NAME);

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

    // Initialize replica set
    cr = mongoAdminDB.command(new BasicDBObject("replSetInitiate",
            (DBObject) JSON.parse("{'_id': '" + REPLICA_SET_NAME + "', 'members': [{'_id': 0, 'host': '"
                    + server1 + "'}, {'_id': 1, 'host': '" + server2 + "'}, {'_id': 2, 'host': '" + server3
                    + "', 'arbiterOnly' : true}]} }")));
    logger.debug("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.debug("Waiting for 3 seconds...");
        Thread.sleep(1000);
        cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
        logger.debug("replSetGetStatus: " + cr);
    }

    mongo.close();
    mongo = null;

    // Initialize a new client using all instances.
    List<ServerAddress> mongoServers = new ArrayList<ServerAddress>();
    mongoServers.add(new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig1.net().getPort()));
    mongoServers.add(new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig2.net().getPort()));
    mongoServers.add(new ServerAddress(Network.getLocalHost().getHostName(), mongodConfig3.net().getPort()));
    mongo = new MongoClient(mongoServers, mco);
    Assert.assertNotNull(mongo);
    mongo.setReadPreference(ReadPreference.secondaryPreferred());
    mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
}

From source file:thingynet.mongo.MongoConfig.java

License:Apache License

@Bean
MongoClient mongoClient() throws IOException {
    ArrayList<ServerAddress> servers = new ArrayList<>();
    for (int i = 0; i < mongoHosts.length; i++) {
        servers.add(new ServerAddress(mongoHosts[i], mongoPorts[i]));
    }// w  ww  . j a va 2 s . c  om
    WriteConcern writeConcern = WriteConcern.valueOf(mongoWriteConcern);
    ReadPreference readPreference = ReadPreference.valueOf(mongoReadPreference);

    MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(mongoConnectionsPerHost)
            .writeConcern(writeConcern).readPreference(readPreference).build();

    return new MongoClient(servers, options);
}

From source file:uk.ac.ebi.eva.dbmigration.mongodb.MongobeeHelper.java

License:Apache License

private static MongoClientOptions getOptions(DatabaseParameters databaseParameters) {
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    builder.readPreference(ReadPreference.valueOf(databaseParameters.getDbReadPreference()));
    return builder.build();
}

From source file:uk.ac.ebi.eva.lib.datastore.DBAdaptorConnector.java

License:Apache License

/**
 * Get a MongoClient using the configuration (credentials) in a given Properties.
 *
 * @param properties can have the next values:
 *                   - eva.mongo.auth.db authentication database
 *                   - eva.mongo.host comma-separated strings of colon-separated host and port strings: host_1:port_1,host_2:port_2
 *                   - eva.mongo.user//from ww  w. j  a v  a 2  s  .  co  m
 *                   - eva.mongo.passwd
 *                   - eva.mongo.read-preference string, "secondaryPreferred" if unspecified. one of:
 *                          [primary, primaryPreferred, secondary, secondaryPreferred, nearest]
 * @return MongoClient with given credentials
 * @throws UnknownHostException
 */
public static MongoClient getMongoClient(Properties properties) throws UnknownHostException {

    String[] hosts = properties.getProperty("eva.mongo.host").split(",");
    List<ServerAddress> servers = new ArrayList<>();

    // Get the list of hosts (optionally including the port number)
    for (String host : hosts) {
        String[] params = host.split(":");
        if (params.length > 1) {
            servers.add(new ServerAddress(params[0], Integer.parseInt(params[1])));
        } else {
            servers.add(new ServerAddress(params[0], 27017));
        }
    }

    List<MongoCredential> mongoCredentialList = null;
    String authenticationDb = properties.getProperty("eva.mongo.auth.db", null);
    if (authenticationDb != null && !authenticationDb.isEmpty()) {
        mongoCredentialList = Collections
                .singletonList(MongoCredential.createCredential(properties.getProperty("eva.mongo.user"),
                        authenticationDb, properties.getProperty("eva.mongo.passwd").toCharArray()));
    }

    String readPreference = properties.getProperty("eva.mongo.read-preference");
    readPreference = readPreference == null || readPreference.isEmpty() ? "secondaryPreferred" : readPreference;

    MongoClientOptions options = MongoClientOptions.builder()
            .readPreference(ReadPreference.valueOf(readPreference)).build();

    return new MongoClient(servers, mongoCredentialList, options);
}

From source file:uk.ac.ebi.eva.vcfdump.server.configuration.DBAdaptorConnector.java

License:Apache License

/**
 * Get a MongoClient using the configuration (credentials) in a given Properties.
 *
 * @param springDataMongoDbProperties can have the next values:
 *                   - eva.mongo.auth.db authentication database
 *                   - eva.mongo.host comma-separated strings of colon-separated host and port strings: host_1:port_1,host_2:port_2
 *                   - eva.mongo.user/*  w ww.j  a v  a  2  s .com*/
 *                   - eva.mongo.passwd
 *                   - eva.mongo.read-preference string, "secondaryPreferred" if unspecified. one of:
 *                          [primary, primaryPreferred, secondary, secondaryPreferred, nearest]
 * @return MongoClient with given credentials
 * @throws UnknownHostException
 */
public static MongoClient getMongoClient(SpringDataMongoDbProperties springDataMongoDbProperties)
        throws UnknownHostException {

    String[] hosts = springDataMongoDbProperties.getHost().split(",");
    List<ServerAddress> servers = new ArrayList<>();

    // Get the list of hosts (optionally including the port number)
    for (String host : hosts) {
        String[] params = host.split(":");
        if (params.length > 1) {
            servers.add(new ServerAddress(params[0], Integer.parseInt(params[1])));
        } else {
            servers.add(new ServerAddress(params[0], 27017));
        }
    }

    List<MongoCredential> mongoCredentialList = new ArrayList<>();
    String authenticationDb = springDataMongoDbProperties.getAuthenticationDatabase();
    if (authenticationDb != null && !authenticationDb.isEmpty()) {
        mongoCredentialList = Collections
                .singletonList(MongoCredential.createCredential(springDataMongoDbProperties.getUsername(),
                        authenticationDb, springDataMongoDbProperties.getPassword().toCharArray()));
    }

    String readPreference = springDataMongoDbProperties.getReadPreference();
    readPreference = readPreference == null || readPreference.isEmpty() ? "secondaryPreferred" : readPreference;

    MongoClientOptions options = MongoClientOptions.builder()
            .readPreference(ReadPreference.valueOf(readPreference)).build();

    return new MongoClient(servers, mongoCredentialList, options);
}

From source file:us.daveread.education.mongo.honeypot.BasicStatistics.java

License:Open Source License

/**
 * Create the instance. This will populate the aggregate count of documents
 * (attacks) and countries.//from   w  w  w.ja  v  a2s. com
 * @see #totalAttacks
 * @see #computeAttackCountryCount()
 */
public BasicStatistics() {
    LOG.info("Connecting to server: " + MONGO_DB_IP + ":" + MONGO_DB_PORT + " and database: "
            + HONEYPOT_DATABASE);

    /**
     * Set a short timeout for connecting so that we don't wait the default 30
     * seconds to detect a problem.
     */
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    optionsBuilder.serverSelectionTimeout(2000);

    MongoClientOptions options = optionsBuilder.build();

    /**
     * Create the MongoClient instance.
     */
    mongoClient = new MongoClient(new ServerAddress(MONGO_DB_IP, MONGO_DB_PORT), options);

    /**
     * Create the MongoDatabase instance.
     */
    mongoDatabase = mongoClient.getDatabase(HONEYPOT_DATABASE);

    /**
     * Get the MongoCollection instance which provides read and write access
     * (bed on permissions) to a specific collection in the database.
     */
    MongoCollection<Document> collection = accessCollection(HONEYPOT_COLLECTION);

    /**
     * Get the count of documents in the collection. If the collection cannot be
     * accessed an exception will the thrown.
     */
    try {
        totalAttacks = collection.count();
    } catch (Throwable throwable) {
        LOG.fatal("Unable to connect to the MongoDB instance at " + MONGO_DB_IP + ":" + MONGO_DB_PORT,
                throwable);
        throw new IllegalStateException("Unable to connect to the MongoDB instance at " + MONGO_DB_IP + ":"
                + MONGO_DB_PORT + ". Are you sure it is running?", throwable);
    }

    /**
     * If no documents were retrieved then apparently the demo collection was
     * not loaded into the database.
     */
    if (totalAttacks == 0) {
        throw new IllegalStateException("Unable to load documents from the collection " + HONEYPOT_COLLECTION
                + " in the database " + HONEYPOT_DATABASE + ". Are you sure it was loaded?");
    }

    computeAttackCountryCount();
}