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:com.stratio.connector.mongodb.core.configuration.MongoClientConfiguration.java

License:Apache License

/**
 * Retrieves the mongo client options. if any option is not specified a default value is set.
 *
 * @return the options for the java MongoDB driver
 * @throws MongoValidationException/*  w  w  w  .  j av  a  2 s  .com*/
 *             the mongo validation exception
 */
public MongoClientOptions getMongoClientOptions() throws MongoValidationException {

    int acceptableLatencyDifference = getIntegerSetting(ACCEPTABLE_LATENCY);
    int maxConnectionsPerHost = getIntegerSetting(MAX_CONNECTIONS_PER_HOST);
    int connectTimeout = getIntegerSetting(CONNECTION_TIMEOUT);
    int maxConnectionIdleTime = getIntegerSetting(MAX_IDLE_TIME);

    ReadPreference readPreference = getReadPreference();

    WriteConcern writeConcern = getWriteConcern();

    MongoClientOptions clientOptions = new MongoClientOptions.Builder()
            .acceptableLatencyDifference(acceptableLatencyDifference).connectionsPerHost(maxConnectionsPerHost)
            .connectTimeout(connectTimeout).maxConnectionIdleTime(maxConnectionIdleTime)
            .readPreference(readPreference).writeConcern(writeConcern).build();

    return clientOptions;
}

From source file:com.stratio.ingestion.morphline.checkpointfilter.handler.MongoCheckpointFilterHandler.java

License:Apache License

private void initMongo(String mongoUri) {
    this.mongoClientURI = new MongoClientURI(mongoUri,
            MongoClientOptions.builder().writeConcern(WriteConcern.SAFE));
    try {// ww  w  . j a v a 2 s.co  m
        this.mongoClient = new MongoClient(mongoClientURI);
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    if (mongoClientURI.getDatabase() != null) {
        this.mongoDb = mongoClient.getDB(mongoClientURI.getDatabase());
    }
    if (mongoClientURI.getCollection() != null) {
        this.mongoCollection = mongoDb.getCollection(mongoClientURI.getCollection());
    }
}

From source file:com.stratio.ingestion.source.rest.url.filter.MongoFilterHandler.java

License:Apache License

protected void initMongo(String mongoUri) {
    try {/*from   www .  ja  va2  s .c om*/
        this.mongoClientURI = new MongoClientURI(mongoUri,
                MongoClientOptions.builder().writeConcern(WriteConcern.SAFE));
        this.mongoClient = new MongoClient(mongoClientURI);
        this.mongoDb = mongoClient
                .getDB(checkNotNull(mongoClientURI.getDatabase(), "Non-null database expected"));
        this.mongoCollection = mongoDb.getCollection(
                checkNotNull(mongoClientURI.getCollection(), "Non-null " + "collection expected"));
    } catch (UnknownHostException e) {
        throw new MongoFilterException("mongo host could not be reached", e);
    } catch (IllegalArgumentException e) {
        throw new MongoFilterException("Valid mongo uri expected.", e);
    } catch (NullPointerException e) {
        throw new MongoFilterException("Non-null db/collection expected", e);
    }
}

From source file:com.streamsets.pipeline.stage.common.mongodb.MongoDBConfig.java

License:Apache License

private MongoClient createClient(Stage.Context context, List<Stage.ConfigIssue> issues,
        ReadPreference readPreference, WriteConcern writeConcern) {
    MongoClientOptions.Builder optionBuilder = new MongoClientOptions.Builder()
            .connectionsPerHost(connectionsPerHost).connectTimeout(connectTimeout)
            .cursorFinalizerEnabled(cursorFinalizerEnabled).heartbeatConnectTimeout(heartbeatConnectTimeout)
            .heartbeatFrequency(heartbeatFrequency).heartbeatSocketTimeout(heartbeatSocketTimeout)
            .localThreshold(localThreshold).maxConnectionIdleTime(maxConnectionIdleTime)
            .maxConnectionLifeTime(maxConnectionLifeTime).maxWaitTime(maxWaitTime)
            .minConnectionsPerHost(minConnectionsPerHost).minHeartbeatFrequency(minHeartbeatFrequency)
            .serverSelectionTimeout(serverSelectionTimeout).socketKeepAlive(socketKeepAlive)
            .socketTimeout(socketTimeout).sslEnabled(sslEnabled)
            .sslInvalidHostNameAllowed(sslInvalidHostNameAllowed)
            .threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);

    // the default value of requiredReplicaSetName is null, so it should be set only if a non-empty string is provided
    if (!requiredReplicaSetName.isEmpty()) {
        optionBuilder = optionBuilder.requiredReplicaSetName(requiredReplicaSetName);
    }//from   w ww  . j a  v  a2  s .c  o m
    // read preference is only set by the source
    if (readPreference != null) {
        optionBuilder = optionBuilder.readPreference(readPreference);
    }
    // write concern is only set by the target
    if (writeConcern != null) {
        optionBuilder = optionBuilder.writeConcern(writeConcern);
    }

    MongoClientURI mongoURI;
    List<ServerAddress> servers = new ArrayList<>();
    try {
        mongoURI = new MongoClientURI(connectionString, optionBuilder);
    } catch (IllegalArgumentException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_00, e.toString()));
        return null;
    }

    validateServerList(context, mongoURI.getHosts(), servers, issues);
    if (!issues.isEmpty()) {
        return null;
    }

    MongoClient mongoClient = null;
    List<MongoCredential> credentials;
    try {
        credentials = createCredentials();
    } catch (StageException ex) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_34, ex.toString()));
        return null;
    }

    if (credentials.isEmpty()) {
        Optional.ofNullable(mongoURI.getCredentials()).ifPresent(credentials::add);
    }

    try {
        if (isSingleMode) {
            mongoClient = new MongoClient(servers.get(0), credentials, mongoURI.getOptions());
        } else {
            mongoClient = new MongoClient(servers, credentials, mongoURI.getOptions());
        }
    } catch (MongoException e) {
        issues.add(context.createConfigIssue(Groups.MONGODB.name(), MONGO_CONFIG_PREFIX + "connectionString",
                Errors.MONGODB_01, e.toString()));
    }

    return mongoClient;
}

From source file:com.streamsets.pipeline.stage.origin.mongodb.MongoDBSource.java

License:Apache License

private boolean createMongoClient(List<ConfigIssue> issues) {
    boolean isOk = true;
    if (null == mongoClient) {
        List<ServerAddress> servers = new ArrayList<>();
        isOk = parseServerList(mongoConnectionString, servers, issues);
        List<MongoCredential> credentials = createCredentials();
        MongoClientOptions options = MongoClientOptions.builder().build();

        if (isOk) {
            try {
                mongoClient = new MongoClient(servers, credentials, options);
            } catch (MongoException e) {
                issues.add(getContext().createConfigIssue(Groups.MONGODB.name(), "mongoConnectionString",
                        Errors.MONGODB_01, e.toString()));
                isOk = false;//from  www.  ja  v  a2 s .c  o m
            }
        }
    }
    return isOk;
}

From source file:com.teamj.distribuidas.ebanking.persistence.PersistenceManager.java

public PersistenceManager() {
    MongoClientOptions mongoOptions = MongoClientOptions.builder().socketTimeout(60000).connectTimeout(60000)
            .build();//from  ww  w .  jav  a2 s.com

    try {

        mongoClient = new MongoClient(new ServerAddress("localhost"), mongoOptions);

    } catch (Exception e) {

        throw new RuntimeException("Error", e);
    }

    mongoClient.setWriteConcern(WriteConcern.SAFE);
    morphia = new Morphia();

    morphia.mapPackage(DB_PACKAGE, true);
    mds = morphia.createDatastore(mongoClient, DB_NAME);
    mds.ensureIndexes();
}

From source file:com.themodernway.server.mongodb.support.spring.MongoDBDescriptor.java

License:Open Source License

private final boolean init() {
    if (null == m_baseprop) {
        m_baseprop = MongoDBContextInstance.getMongoDBContextInstance().getMongoDBProvider()
                .getMongoDBDefaultPropertiesBase();
    }/*from  w w w  .  ja va2  s  .  c o m*/
    final IPropertiesResolver prop = ServerContextInstance.getServerContextInstance().getPropertiesResolver();

    setName(prop.getPropertyByName(m_baseprop + ".name"));

    setDefaultDB(prop.getPropertyByName(m_baseprop + ".db"));

    setReplicas(Boolean.valueOf(prop.getPropertyByName(m_baseprop + ".replicas", "false")));

    setCreateID(Boolean.valueOf(prop.getPropertyByName(m_baseprop + ".createid", "false")));

    final ArrayList<ServerAddress> addrlist = new ArrayList<>();

    for (String name : StringOps.requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host.list"))
            .split(",")) {
        name = StringOps.toTrimOrNull(name);

        if (null != name) {
            final String addr = StringOps
                    .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host." + name + ".addr"));

            final String port = StringOps
                    .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".host." + name + ".port"));

            addrlist.add(new ServerAddress(addr, Integer.parseInt(port)));
        }
    }
    if (addrlist.isEmpty()) {
        throw new IllegalArgumentException("no MongoDB server address");
    }
    m_addrlist = addrlist;

    m_authlist = new ArrayList<>();

    final String temp = StringOps.toTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth.list"));

    if (null != temp) {
        for (String name : temp.split(",")) {
            name = StringOps.toTrimOrNull(name);

            if (null != name) {
                final String user = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".user"));

                final String pass = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".pass"));

                final String data = StringOps
                        .requireTrimOrNull(prop.getPropertyByName(m_baseprop + ".auth." + name + ".db"));

                m_authlist.add(MongoCredential.createCredential(user, data, pass.toCharArray()));
            }
        }
    }
    if (null == getClientOptions()) {
        setClientOptions(MongoClientOptions.builder().connectionsPerHost(getConnectionPoolSize())
                .threadsAllowedToBlockForConnectionMultiplier(getConnectionMultiplier())
                .connectTimeout(getConnectionTimeout()).build());
    }
    m_doptions = new LinkedHashMap<>();

    final String conf = StringOps.toTrimOrNull(prop.getPropertyByName(m_baseprop + ".dbconfig.list"));

    if (null != conf) {
        for (String name : conf.split(",")) {
            name = StringOps.toTrimOrNull(name);

            if ((null != name) && (null == m_doptions.get(name))) {
                boolean doid = isCreateID();

                final ArrayList<IMongoDBCollectionOptions> list = new ArrayList<>();

                final String dbid = StringOps
                        .toTrimOrNull(prop.getPropertyByName(m_baseprop + ".dbconfig." + name + ".createid"));

                if (null != dbid) {
                    doid = Boolean.valueOf(dbid);
                }
                final String base = m_baseprop + ".dbconfig." + name + ".collections";

                final String cols = StringOps.toTrimOrNull(prop.getPropertyByName(base));

                if (null != cols) {
                    for (String coln : cols.split(",")) {
                        coln = StringOps.toTrimOrNull(coln);

                        if (null != coln) {
                            final String icid = StringOps
                                    .toTrimOrNull(prop.getPropertyByName(base + "." + coln + ".createid"));

                            if (null != icid) {
                                list.add(new MongoDBCollectionOptions(coln, Boolean.valueOf(icid)));
                            } else {
                                list.add(new MongoDBCollectionOptions(coln, doid));
                            }
                        }
                    }
                }
                m_doptions.put(name, new MongoDBOptions(name, doid, list));
            }
        }
    }
    return true;
}

From source file:com.tomtom.speedtools.mongodb.MongoConnectionCache.java

License:Apache License

/**
 * Get a MongoDB instance, given its server address(es). The server specification should be formatted as follows:
 * <pre>/*w  w w.  ja  v a  2  s  .c  om*/
 *      hostname:port[,hostname:port]*
 * </pre>
 *
 * @param servers             Server addresses, format see above.
 * @param connectTimeoutMsecs Timeout in seconds.
 * @param userName            User name.
 * @param database            Database.
 * @param password            Password.
 * @return MongoDB instance.
 * @throws UnknownHostException If the MongoDB server cannot be found.
 */
@Nonnull
public static Mongo getMongoDB(@Nonnull final String servers, final int connectTimeoutMsecs,
        @Nonnull final String userName, @Nonnull final String database, @Nonnull final String password)
        throws UnknownHostException {
    assert servers != null;
    assert connectTimeoutMsecs >= 0;
    assert userName != null;
    assert database != null;
    assert password != null;
    try {
        return mongoDBInstances.get(servers, () -> {
            LOG.info("getMongoDB: MongoDB servers: " + servers);

            final List<ServerAddress> replicaSetSeeds = getMongoDBServerAddresses(servers);
            final List<MongoCredential> credentials = new ArrayList<>();
            if (!userName.isEmpty()) {
                LOG.debug("getMongoDB: credentials provided (username/password)");
                final MongoCredential credential = MongoCredential.createCredential(userName, database,
                        password.toCharArray());
                credentials.add(credential);
            }
            return new MongoClient(replicaSetSeeds, credentials,
                    MongoClientOptions.builder().connectTimeout(connectTimeoutMsecs).build());
        });
    } catch (final ExecutionException e) {
        throw new UnknownHostException(
                "Couldn't connect to MongoDB at: " + servers + ", cause: " + e.getCause());
    }
}

From source file:com.torodb.testing.mongodb.docker.AbstractMongod.java

License:Apache License

public AbstractMongod(Version version) {
    this(version, MongoClientOptions.builder().build(),
            new UntilStdLineContains("waiting for connections on port"),
            new ImagePuller(version.getDockerImageRef()));
}

From source file:com.torodb.testing.mongodb.docker.ReplMongod.java

License:Apache License

public ReplMongod(Config config, Version version) {
    super(version, new MongoClientOptions.Builder().build());
    this.config = config;
}