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.graylog2.database.MongoConnection.java

License:Open Source License

/**
 * Connect the instance./*from  w  w w  .j  a v a  2 s.c  om*/
 */
public synchronized MongoClient connect() {
    if (m == null) {
        Builder options = new MongoClientOptions.Builder();
        options.connectionsPerHost(maxConnections);
        options.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockMultiplier);

        try {

            // Connect to replica servers if given. Else the standard way to one server.
            if (replicaServers != null && replicaServers.size() > 0) {
                m = new MongoClient(replicaServers, options.build());
            } else {
                ServerAddress address = new ServerAddress(host, port);
                m = new MongoClient(address, options.build());
            }
            db = m.getDB(database);
            db.setWriteConcern(WriteConcern.SAFE);

            // Try to authenticate if configured.
            if (useAuth) {
                if (!db.authenticate(username, password.toCharArray())) {
                    throw new RuntimeException("Could not authenticate to database '" + database
                            + "' with user '" + username + "'.");
                }
            }
        } catch (UnknownHostException e) {
            throw new RuntimeException("Cannot resolve host name for MongoDB", e);
        }
    }
    return m;
}

From source file:org.hbr.session.store.MongoStore.java

License:Apache License

/**
 * Create the {@link MongoClient}./* ww w . j av a  2 s. c  om*/
 * @throws LifecycleException
 */
private void getConnection() throws LifecycleException {
    try {
        /* create our MongoClient */
        if (this.connectionUri != null) {
            manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName()
                    + "]: Connecting to MongoDB [" + this.connectionUri + "]");
            this.mongoClient = new MongoClient(this.connectionUri);
        } else {
            /* create the client using the Mongo options */
            ReadPreference readPreference = ReadPreference.primaryPreferred();
            if (this.useSlaves) {
                readPreference = ReadPreference.secondaryPreferred();
            }
            MongoClientOptions options = MongoClientOptions.builder().connectTimeout(connectionTimeoutMs)
                    .maxWaitTime(connectionWaitTimeoutMs).connectionsPerHost(maxPoolSize)
                    .writeConcern(writeConcern).readPreference(readPreference).build();

            /* build up the host list */
            List<ServerAddress> hosts = new ArrayList<ServerAddress>();
            String[] dbHosts = this.hosts.split(",");
            for (String dbHost : dbHosts) {
                String[] hostInfo = dbHost.split(":");
                ServerAddress address = new ServerAddress(hostInfo[0], Integer.parseInt(hostInfo[1]));
                hosts.add(address);
            }

            this.manager.getContainer().getLogger().info(
                    getStoreName() + "[" + this.getName() + "]: Connecting to MongoDB [" + this.hosts + "]");

            /* connect */
            this.mongoClient = new MongoClient(hosts, options);
        }

        /* get a connection to our db */
        this.manager.getContainer().getLogger()
                .info(getStoreName() + "[" + this.getName() + "]: Using Database [" + this.dbName + "]");
        this.db = this.mongoClient.getDB(this.dbName);

        /* see if we need to authenticate */
        if (this.username != null || this.password != null) {
            this.manager.getContainer().getLogger().info(
                    getStoreName() + "[" + this.getName() + "]: Authenticating using [" + this.username + "]");
            if (!this.db.authenticate(this.username, this.password.toCharArray())) {
                throw new RuntimeException("MongoDB Authentication Failed");
            }
        }

        /* get a reference to the collection */
        this.collection = this.db.getCollection(this.collectionName);
        this.manager.getContainer().getLogger()
                .info(getStoreName() + "[" + this.getName() + "]: Preparing indexes");

        /* drop any existing indexes */
        try {
            this.collection.dropIndex(new BasicDBObject(lastModifiedProperty, 1));
            this.collection.dropIndex(new BasicDBObject(appContextProperty, 1));
        } catch (Exception e) {
            /* these indexes may not exist, so ignore */
        }

        /* make sure the last modified and app name indexes exists */
        this.collection.ensureIndex(new BasicDBObject(appContextProperty, 1));

        /* determine if we need to expire our db sessions */
        if (this.timeToLive != -1) {
            /* use the time to live set */
            this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1),
                    new BasicDBObject("lastModifiedProperty", this.timeToLive));
        } else {
            /* no custom time to live specified, use the manager's settings */
            if (this.manager.getMaxInactiveInterval() != -1) {
                /* create a ttl index on the app property */
                this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1),
                        new BasicDBObject("lastModifiedProperty", this.manager.getMaxInactiveInterval()));
            } else {
                /* create a regular index */
                this.collection.ensureIndex(new BasicDBObject(lastModifiedProperty, 1));
            }
        }

        this.manager.getContainer().getLogger().info(getStoreName() + "[" + this.getName() + "]: Store ready.");
    } catch (UnknownHostException uhe) {
        this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", uhe);
        throw new LifecycleException(uhe);
    } catch (MongoException me) {
        this.manager.getContainer().getLogger().error("Unable to Connect to MongoDB", me);
        throw new LifecycleException(me);
    }
}

From source file:org.hibernate.ogm.datastore.mongodb.configuration.impl.MongoDBConfiguration.java

License:LGPL

/**
 * Create a {@link MongoClientOptions} using the {@link MongoDBConfiguration}.
 *
 * @return the {@link MongoClientOptions} corresponding to the {@link MongoDBConfiguration}
 *//*from  w ww. j a  va  2 s. co  m*/
public MongoClientOptions buildOptions() {
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();

    optionsBuilder.connectTimeout(timeout);
    optionsBuilder.writeConcern(writeConcern);
    optionsBuilder.readPreference(readPreference);
    return optionsBuilder.build();
}

From source file:org.hibernate.ogm.datastore.mongodb.impl.configuration.MongoDBConfiguration.java

License:LGPL

/**
 * Create a {@link MongoClientOptions} using the {@link MongoDBConfiguration}.
 *
 * @return the {@link MongoClientOptions} corresponding to the {@link MongoDBConfiguration}
 *//*from www  .  ja va2  s.  c o  m*/
public MongoClientOptions buildOptions() {
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();

    optionsBuilder.connectTimeout(timeout);
    optionsBuilder.writeConcern(writeConcern);
    optionsBuilder.readPreference(readPreference);

    return optionsBuilder.build();
}

From source file:org.hibernate.ogm.perftest.mongodb.nativeapi.NativeApiBenchmarkBase.java

License:LGPL

protected static MongoClient getMongoClient() throws UnknownHostException {
    ServerAddress serverAddress = new ServerAddress(properties.getProperty("host"), 27017);

    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();

    optionsBuilder.connectTimeout(1000);
    optionsBuilder.writeConcern(WriteConcern.ACKNOWLEDGED);
    optionsBuilder.readPreference(ReadPreference.primary());

    MongoClientOptions clientOptions = optionsBuilder.build();

    MongoClient mongo = new MongoClient(serverAddress, clientOptions);

    return mongo;
}

From source file:org.hillview.storage.MongoDBLoader.java

License:Open Source License

public MongoDBLoader(JdbcConnectionInformation info) {
    super(Converters.checkNull(info.table), null);
    this.info = info;
    assert info.database != null;
    assert info.password != null;

    MongoCredential credential = MongoCredential.createCredential(info.user, info.database,
            info.password.toCharArray());
    ServerAddress address = new ServerAddress(info.host, info.port);
    MongoClientOptions options = MongoClientOptions.builder().build();
    MongoClient client = new MongoClient(address); //, credential, options);

    this.database = client.getDatabase(info.database);
    //this.oldDatabase = client.getDB(info.database);
}

From source file:org.infinispan.loaders.mongodb.MongoDBCacheStore.java

License:Open Source License

@Override
public void start() throws CacheLoaderException {
    super.start();
    try {//from   w w w . ja v  a  2  s .  c o m
        MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder();
        optionBuilder.connectTimeout(this.cfg.getTimeout());

        WriteConcern writeConcern = new WriteConcern(this.cfg.getAcknowledgment());
        optionBuilder.writeConcern(writeConcern);

        log.connectingToMongo(this.cfg.getHost(), this.cfg.getPort(), this.cfg.getTimeout(),
                this.cfg.getAcknowledgment());

        ServerAddress serverAddress = new ServerAddress(this.cfg.getHost(), this.cfg.getPort());

        this.mongo = new MongoClient(serverAddress, optionBuilder.build());
    } catch (UnknownHostException e) {
        throw log.mongoOnUnknownHost(this.cfg.getHost());
    } catch (RuntimeException e) {
        throw log.unableToInitializeMongoDB(e);
    }
    mongoDb = extractDatabase();
    this.collection = mongoDb.getCollection(this.cfg.getCollectionName());

}

From source file:org.jmingo.mongo.MongoDBFactory.java

License:Apache License

/**
 * Creates new instance of {@link MongoClientOptions}.
 * Finds a method in {@link MongoClientOptions.Builder} that matches with a option name from {@link org.jmingo.config.MongoConfig#getOptions()}
 * and has same number of arguments and tries invoke satisfied method using reflection with args for appropriate option name.
 *
 * @param config the mongo configuration
 * @return the created {@link MongoClientOptions}
 * @throws MongoConfigurationException//w  ww . j a  va 2  s .  c o m
 */
private MongoClientOptions createOptions(MongoConfig config) throws MongoConfigurationException {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    if (MapUtils.isEmpty(config.getOptions())) {
        return builder.build();
    } else {
        for (Map.Entry<String, String> option : config.getOptions().entrySet()) {
            try {
                if (isUnsupportedOption(option.getKey())) {
                    LOGGER.warn(
                            "mongo option: {} cannot be set because isn't supported and should be set directly using MongoClientOptions");
                    continue;
                }
                String[] values = StringUtils.split(option.getValue(), ",");
                Method method = findMethod(MongoClientOptions.Builder.class,
                        (m) -> StringUtils.equalsIgnoreCase(m.getName(), option.getKey())
                                && (m.getParameterCount() == values.length));

                if (method != null) {
                    Class<?>[] pTypes = method.getParameterTypes();

                    Object[] args = new Object[values.length];
                    for (int i = 0; i < values.length; i++) {
                        args[i] = getValue(values[i], pTypes[i]);
                    }
                    method.invoke(builder, args);
                } else {
                    LOGGER.error(
                            "no method has been found in MongoClientOptions.Builder with name: '{}' and args: {}",
                            option.getKey(), Arrays.asList(values));
                }
            } catch (Throwable th) {
                throw new MongoConfigurationException(
                        "failed to set mongo option: " + option.getKey() + " value: " + option.getValue(), th);
            }
        }
    }
    return builder.build();
}

From source file:org.jooby.mongodb.Mongodb.java

License:Apache License

private MongoClientOptions.Builder options(final Config config) {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();

    builder.connectionsPerHost(config.getInt("connectionsPerHost"));
    builder.threadsAllowedToBlockForConnectionMultiplier(
            config.getInt("threadsAllowedToBlockForConnectionMultiplier"));
    builder.maxWaitTime((int) config.getDuration("maxWaitTime", TimeUnit.MILLISECONDS));
    builder.connectTimeout((int) config.getDuration("connectTimeout", TimeUnit.MILLISECONDS));
    builder.socketTimeout((int) config.getDuration("socketTimeout", TimeUnit.MILLISECONDS));
    builder.socketKeepAlive(config.getBoolean("socketKeepAlive"));
    builder.cursorFinalizerEnabled(config.getBoolean("cursorFinalizerEnabled"));
    builder.alwaysUseMBeans(config.getBoolean("alwaysUseMBeans"));
    builder.heartbeatFrequency(config.getInt("heartbeatFrequency"));
    builder.minHeartbeatFrequency(config.getInt("minHeartbeatFrequency"));
    builder.heartbeatConnectTimeout((int) config.getDuration("heartbeatConnectTimeout", TimeUnit.MILLISECONDS));
    builder.heartbeatSocketTimeout((int) config.getDuration("heartbeatSocketTimeout", TimeUnit.MILLISECONDS));

    return builder;
}

From source file:org.jooby.mongodb.Mongodb.java

License:Apache License

protected void configure(final Env env, final Config config, final Binder binder,
        final BiConsumer<MongoClientURI, MongoClient> callback) {
    MongoClientOptions.Builder options = options(mongodb(config));

    if (this.options != null) {
        this.options.accept(options, config);
    }//from www.  j a  v a 2  s .co  m

    MongoClientURI uri = new MongoClientURI(config.getString(db), options);
    String database = uri.getDatabase();
    checkArgument(database != null, "Database not found: " + uri);
    MongoClient client = new MongoClient(uri);

    ServiceKey serviceKey = env.serviceKey();
    serviceKey.generate(MongoClientURI.class, database, k -> binder.bind(k).toInstance(uri));

    serviceKey.generate(MongoClient.class, database, k -> binder.bind(k).toInstance(client));

    MongoDatabase mongodb = client.getDatabase(database);
    serviceKey.generate(MongoDatabase.class, database, k -> binder.bind(k).toInstance(mongodb));

    env.onStop(client::close);

    callback.accept(uri, client);
}