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:org.craftercms.commons.mongo.MongoClientOptionsFactory.java

License:Open Source License

@Override
protected MongoClientOptions createInstance() throws Exception {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.alwaysUseMBeans(this.alwaysUseMBeans);
    builder.connectionsPerHost(this.connectionsPerHost);
    builder.cursorFinalizerEnabled(this.cursorFinalizerEnabled);
    builder.connectTimeout(this.connectTimeout);
    builder.maxWaitTime(this.maxWaitTime);

    switch (this.readPreference) {
    case PRIMARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.primary());
        break;//from   w w  w  . j a v  a  2  s  .c om
    case NEAREST_READ_PREFERENCE:
        builder.readPreference(ReadPreference.nearest());
        break;
    case SECONDARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.secondary());
        break;
    default:
        builder.readPreference(ReadPreference.primary());
        break;
    }
    builder.writeConcern(WriteConcern.valueOf(this.writeConcern));
    builder.threadsAllowedToBlockForConnectionMultiplier(this.threadsAllowedToBlockForConnectionMultiplier);
    return builder.build();

}

From source file:org.craftercms.studio.impl.repository.mongodb.data.ClientOptionsFactory.java

License:Open Source License

public void init() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.alwaysUseMBeans(this.alwaysUseMBeans);
    builder.autoConnectRetry(this.autoConnectRetry);
    builder.connectionsPerHost(this.connectionsPerHost);
    builder.cursorFinalizerEnabled(this.cursorFinalizerEnabled);
    builder.connectTimeout(this.connectTimeout);
    builder.maxAutoConnectRetryTime(this.maxAutoConnectRetryTime);
    builder.maxWaitTime(this.maxWaitTime);

    switch (this.readPreference) {
    case PRIMARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.primary());
        break;/* w w  w  . j a  va 2  s . c om*/
    case NEAREST_READ_PREFERENCE:
        builder.readPreference(ReadPreference.nearest());
        break;
    case SECONDARY_READ_PREFERENCE:
        builder.readPreference(ReadPreference.secondary());
        break;
    default:
        builder.readPreference(ReadPreference.primary());
        break;
    }
    builder.socketKeepAlive(this.socketKeepAlive);
    builder.writeConcern(WriteConcern.valueOf(this.writeConcern));
    builder.threadsAllowedToBlockForConnectionMultiplier(this.threadsAllowedToBlockForConnectionMultiplier);
    this.clientOptions = builder.build();
}

From source file:org.datanucleus.store.mongodb.ConnectionFactoryImpl.java

License:Open Source License

private MongoClientOptions getMongodbOptions(StoreManager storeManager) {
    Object connectionsPerHost = storeManager.getProperty("datanucleus.mongodb.connectionsPerHost");
    Object threadsAllowedToBlockForConnectionMultiplier = storeManager
            .getProperty("datanucleus.mongodb.threadsAllowedToBlockForConnectionMultiplier");
    MongoClientOptions.Builder mongoOptionsBuilder = MongoClientOptions.builder();
    if (connectionsPerHost != null) {
        mongoOptionsBuilder.connectionsPerHost(Integer.parseInt((String) connectionsPerHost));
    }//from   w w  w.  j av a2  s. com
    if (threadsAllowedToBlockForConnectionMultiplier != null) {
        mongoOptionsBuilder.threadsAllowedToBlockForConnectionMultiplier(
                Integer.parseInt((String) threadsAllowedToBlockForConnectionMultiplier));
    }
    return mongoOptionsBuilder.build();
}

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

License:Open Source License

private static MongoOptions createDefaultClientOptions() {
    Builder optionsBuilder = new MongoClientOptions.Builder();
    return new MongoOptions(optionsBuilder.build());
}

From source file:org.eclipselabs.emongo.components.MongoClientProviderComponent.java

License:Open Source License

private MongoClientOptions createMongoClientOptions(Map<String, Object> properties) {
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();

    String description = (String) properties.get(PROP_DESCRIPTION);

    if (description != null)
        optionsBuilder.description(description);

    Integer connectionsPerHost = (Integer) properties.get(PROP_CONNECTIONS_PER_HOST);

    if (connectionsPerHost != null)
        optionsBuilder.connectionsPerHost(connectionsPerHost);

    Integer threadsAllowedToBlockForConnectionMultiplier = (Integer) properties
            .get(PROP_THREADS_ALLOWED_TO_BLOCK_FOR_CONNECTION_MULTIPLIER);

    if (threadsAllowedToBlockForConnectionMultiplier != null)
        optionsBuilder//ww  w .  ja  va2s.co m
                .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);

    Integer maxWaitTime = (Integer) properties.get(PROP_MAX_WAIT_TIME);

    if (maxWaitTime != null)
        optionsBuilder.maxWaitTime(maxWaitTime);

    Integer connectTimeout = (Integer) properties.get(PROP_CONNECT_TIMEOUT);

    if (connectTimeout != null)
        optionsBuilder.connectTimeout(connectTimeout);

    Integer socketTimeout = (Integer) properties.get(PROP_SOCKET_TIMEOUT);

    if (socketTimeout != null)
        optionsBuilder.socketTimeout(socketTimeout);

    Boolean socketKeepAlive = (Boolean) properties.get(PROP_SOCKET_KEEP_ALIVE);

    if (socketKeepAlive != null)
        optionsBuilder.socketKeepAlive(socketKeepAlive);

    Boolean autoConnectRetry = (Boolean) properties.get(PROP_AUTO_CONNECT_RETRY);

    if (autoConnectRetry != null)
        optionsBuilder.autoConnectRetry(autoConnectRetry);

    Long maxAutoConnectRetryTime = (Long) properties.get(PROP_MAX_AUTO_CONNECT_RETRY_TIME);

    if (maxAutoConnectRetryTime != null)
        optionsBuilder.maxAutoConnectRetryTime(maxAutoConnectRetryTime);

    Boolean continueOnInsertError = (Boolean) properties.get(PROP_CONTINUE_ON_INSERT_ERROR);

    if (continueOnInsertError == null)
        continueOnInsertError = Boolean.FALSE;

    Integer w = (Integer) properties.get(PROP_W);

    if (w == null)
        w = Integer.valueOf(1);

    Integer wtimeout = (Integer) properties.get(PROP_WTIMEOUT);

    if (wtimeout == null)
        wtimeout = Integer.valueOf(0);

    Boolean fsync = (Boolean) properties.get(PROP_FSYNC);

    if (fsync == null)
        fsync = Boolean.FALSE;

    Boolean j = (Boolean) properties.get(PROP_J);

    if (j == null)
        j = Boolean.FALSE;

    WriteConcern writeConcern = new WriteConcern(w, wtimeout, fsync, j, continueOnInsertError);
    optionsBuilder.writeConcern(writeConcern);

    return optionsBuilder.build();
}

From source file:org.edgexfoundry.AppConfig.java

License:Apache License

private MongoClientOptions getMongoClientOptions() {
    return MongoClientOptions.builder().connectTimeout(connectTimeout).socketTimeout(socketTimeout)
            .maxWaitTime(maxWaitTime).socketKeepAlive(socketKeepAlive).build();
}

From source file:org.elasticsearch.river.mongodb.RiverMongoDBTestAbstract.java

License:Apache License

private void initMongoInstances(ExecutableType type) throws Exception {
    logger.debug("*** initMongoInstances(" + type + ") ***");
    CommandResult cr;// w ww  . j a  va2s  .c o m
    Settings rsSettings = settings.getByPrefix(type.configKey + '.');
    int[] ports;
    if (rsSettings.getAsBoolean("useDynamicPorts", false)) {
        ports = new int[] { Network.getFreeServerPort(), Network.getFreeServerPort(),
                Network.getFreeServerPort() };
    } else {
        int start = 37017 + 10 * type.ordinal();
        ports = new int[] { start, start + 1, start + 2 };
    }
    String replicaSetName = "es-test-" + type.configKey;
    // Create 3 mongod processes
    Starter<IMongodConfig, MongodExecutable, MongodProcess> starter = type.newStarter();
    ImmutableList.Builder<MongoReplicaSet.Member> builder = ImmutableList.builder();
    for (int i = 1; i <= 3; ++i) {
        Storage storage = new Storage("target/" + replicaSetName + '/' + i, replicaSetName, 20);
        MongoReplicaSet.Member member = new MongoReplicaSet.Member();
        member.config = new MongodConfigBuilder()
                .version(Versions.withFeatures(new GenericVersion(rsSettings.get("version"))))
                .net(new de.flapdoodle.embed.mongo.config.Net(ports[i - 1], Network.localhostIsIPv6()))
                .replication(storage).build();
        logger.trace("replSetName in config: {}", member.config.replication().getReplSetName());
        member.executable = starter.prepare(member.config);
        member.process = member.executable.start();
        member.address = new ServerAddress(Network.getLocalHost().getHostName(), member.config.net().getPort());
        logger.debug("Server #" + i + ": {}", member.address);
        builder.add(member);
    }
    ImmutableList<MongoReplicaSet.Member> members = builder.build();
    Thread.sleep(2000);
    MongoClientOptions mco = MongoClientOptions.builder().autoConnectRetry(true).connectTimeout(15000)
            .socketTimeout(60000).build();
    Mongo mongo = new MongoClient(new ServerAddress(Network.getLocalHost().getHostName(), ports[0]), mco);
    DB 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': '" + replicaSetName + "', 'members': [" + "{'_id': 0, 'host': '"
                    + members.get(0).address.getHost() + ':' + members.get(0).address.getPort() + "'}, "
                    + "{'_id': 1, 'host': '" + members.get(1).address.getHost() + ':'
                    + members.get(1).address.getPort() + "'}, " + "{'_id': 2, 'host': '"
                    + members.get(2).address.getHost() + ':' + members.get(2).address.getPort()
                    + "', 'arbiterOnly' : true}]} }")));
    logger.debug("replSetInitiate result: " + cr);

    Thread.sleep(5000);
    cr = mongoAdminDB.command(new BasicDBObject("replSetGetStatus", 1));
    logger.trace("replSetGetStatus result: {}", cr);

    // Check replica set status before to proceed
    while (!isReplicaSetStarted(cr)) {
        logger.debug("Waiting 3 seconds for replicaset to change status...");
        Thread.sleep(3000);
        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>();
    for (MongoReplicaSet.Member member : members) {
        mongoServers.add(member.address);
    }
    mongo = new MongoClient(mongoServers, mco);
    Assert.assertNotNull(mongo);
    mongo.setReadPreference(ReadPreference.secondaryPreferred());
    mongo.setWriteConcern(WriteConcern.REPLICAS_SAFE);
    replicaSets.put(type, new MongoReplicaSet(type, rsSettings.get("version"), mongo, mongoAdminDB, members));
}

From source file:org.fastmongo.odm.client.MongoClientFactory.java

License:Apache License

public MongoClient createMongoClient() {
    MongoClientOptions.Builder options = MongoClientOptions.builder();
    if (useBsonDecoder) {
        options.dbDecoderFactory(BsonDbDecoderFactory.INSTANCE);
    }//w  ww  .ja  va2 s  .c o  m

    MongoClientURI clientUri = new MongoClientURI(this.uri, options);

    try {
        return new MongoClient(clientUri);
    } catch (UnknownHostException e) {
        throw new RuntimeException("Can't create MongoClient with uri = " + clientUri, e);
    }
}

From source file:org.forgerock.openidm.repo.mongodb.impl.MongoClientSingleton.java

License:Open Source License

public MongoClientSingleton init(JsonValue config) {
    if (client == null) {
        JsonValue connPerHost = config.get(MongoDBRepoService.CONFIG_CONN_PER_HOST);
        JsonValue connMultiple = config.get(MongoDBRepoService.CONFIG_CONN_MULTIPLIER);
        int connectionsPerHost = (connPerHost.isNull() ? 100 : connPerHost.asInteger());
        int connectonMultiple = (connMultiple.isNull() ? 5 : connMultiple.asInteger());

        int w = 1;
        int wtimeout = 0;
        boolean j = false;
        JsonValue wc_conf = config.get(MongoDBRepoService.CONFIG_WRITE_CONCERN);
        if (wc_conf != null) {
            JsonValue jv_w = wc_conf.get("w");
            JsonValue jv_wtimeout = wc_conf.get("wtimeout");
            JsonValue jv_j = wc_conf.get("j");
            w = (jv_w.isNull() ? 1 : jv_w.asInteger());
            wtimeout = (jv_wtimeout.isNull() ? 0 : jv_wtimeout.asInteger());
            j = (jv_j.isNull() ? false : jv_j.asBoolean());
        }//  w  ww. j a  v  a 2s .com
        WriteConcern wc = new WriteConcern(w, wtimeout, false, j);

        MongoClientOptions options = new MongoClientOptions.Builder().connectionsPerHost(connectionsPerHost)
                .threadsAllowedToBlockForConnectionMultiplier(connectonMultiple).writeConcern(wc).build();
        List<ServerAddress> replicaSet = getReplicaSet(config);
        client = new MongoClient(replicaSet, options);
        db = getDB(config);
        logger.info("Create new MongoClient");
    }
    return this;
}

From source file:org.grails.datastore.gorm.mongo.bean.factory.MongoClientFactoryBean.java

License:Apache License

public void afterPropertiesSet() throws UnknownHostException {
    // apply defaults - convenient when used to configure for tests
    // in an application context
    if (mongo != null) {
        return;//from w w  w. j av  a2 s.c  o  m
    }

    ServerAddress defaultOptions = new ServerAddress();
    List<MongoCredential> credentials = new ArrayList<MongoCredential>();
    if (mongoOptions == null) {
        MongoClientOptions.Builder builder = MongoClientOptions.builder();
        builder.codecRegistry(CodecRegistries.fromRegistries(codecRegistries));
        mongoOptions = builder.build();
    }
    // If username/pw exists and we are not authenticated, authenticate now
    if (username != null && password != null) {
        credentials.add(MongoCredential.createCredential(username, database, password.toCharArray()));
    }

    if (replicaPair != null) {
        if (replicaPair.size() < 2) {
            throw new DatastoreConfigurationException("A replica pair must have two server entries");
        }
        mongo = new MongoClient(replicaPair, credentials, mongoOptions);
    } else if (replicaSetSeeds != null) {
        mongo = new MongoClient(replicaSetSeeds, credentials, mongoOptions);
    } else if (clientURI != null) {
        mongo = new MongoClient(clientURI);
    } else if (connectionString != null) {
        mongo = new MongoClient(new MongoClientURI(connectionString));
    } else {
        String mongoHost = host != null ? host : defaultOptions.getHost();
        if (port != null) {
            mongo = new MongoClient(new ServerAddress(mongoHost, port), credentials, mongoOptions);
        } else {
            mongo = new MongoClient(new ServerAddress(host), credentials, mongoOptions);
        }
    }

}