Example usage for com.mongodb MongoClientOptions.Builder requiredReplicaSetName

List of usage examples for com.mongodb MongoClientOptions.Builder requiredReplicaSetName

Introduction

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

Prototype

String requiredReplicaSetName

To view the source code for com.mongodb MongoClientOptions.Builder requiredReplicaSetName.

Click Source Link

Usage

From source file:com.facebook.presto.mongodb.MongoClientModule.java

License:Apache License

@Singleton
@Provides//from w w w.ja  va2 s  .  c  om
public static MongoSession createMongoSession(TypeManager typeManager, MongoClientConfig config) {
    requireNonNull(config, "config is null");

    MongoClientOptions.Builder options = MongoClientOptions.builder();

    options.connectionsPerHost(config.getConnectionsPerHost()).connectTimeout(config.getConnectionTimeout())
            .socketTimeout(config.getSocketTimeout()).socketKeepAlive(config.getSocketKeepAlive())
            .maxWaitTime(config.getMaxWaitTime()).minConnectionsPerHost(config.getMinConnectionsPerHost())
            .readPreference(config.getReadPreference().getReadPreference())
            .writeConcern(config.getWriteConcern().getWriteConcern());

    if (config.getRequiredReplicaSetName() != null) {
        options.requiredReplicaSetName(config.getRequiredReplicaSetName());
    }

    MongoClient client = new MongoClient(config.getSeeds(), config.getCredentials(), options.build());

    return new MongoSession(typeManager, client, config);
}

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  ava2s.co 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:io.prestosql.plugin.mongodb.MongoClientModule.java

License:Apache License

@Singleton
@Provides/*ww w  .j  a v a2s  .c o m*/
public static MongoSession createMongoSession(TypeManager typeManager, MongoClientConfig config) {
    requireNonNull(config, "config is null");

    MongoClientOptions.Builder options = MongoClientOptions.builder();

    options.connectionsPerHost(config.getConnectionsPerHost()).connectTimeout(config.getConnectionTimeout())
            .socketTimeout(config.getSocketTimeout()).socketKeepAlive(config.getSocketKeepAlive())
            .sslEnabled(config.getSslEnabled()).maxWaitTime(config.getMaxWaitTime())
            .minConnectionsPerHost(config.getMinConnectionsPerHost())
            .readPreference(config.getReadPreference().getReadPreference())
            .writeConcern(config.getWriteConcern().getWriteConcern());

    if (config.getRequiredReplicaSetName() != null) {
        options.requiredReplicaSetName(config.getRequiredReplicaSetName());
    }

    MongoClient client = new MongoClient(config.getSeeds(), config.getCredentials(), options.build());

    return new MongoSession(typeManager, client, config);
}

From source file:org.opencb.commons.datastore.mongodb.MongoDataStoreManager.java

License:Apache License

private MongoDataStore create(String database, MongoDBConfiguration mongoDBConfiguration) {
    MongoDataStore mongoDataStore = null;
    MongoClient mc = null;/* w ww.  j  ava  2  s. c om*/
    logger.debug(
            "MongoDataStoreManager: creating a MongoDataStore object for database: '" + database + "' ...");
    long t0 = System.currentTimeMillis();
    if (database != null && !database.trim().equals("")) {
        // read DB configuration for that SPECIES.VERSION, by default
        // PRIMARY_DB is selected
        //            String dbPrefix = applicationProperties.getProperty(speciesVersionPrefix + ".DB", "PRIMARY_DB");
        // We create the MongoClientOptions
        MongoClientOptions mongoClientOptions;
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
                .connectionsPerHost(
                        mongoDBConfiguration.getInt(CONNECTIONS_PER_HOST, CONNECTIONS_PER_HOST_DEFAULT))
                .connectTimeout(mongoDBConfiguration.getInt(CONNECT_TIMEOUT, CONNECT_TIMEOUT_DEFAULT))
                .readPreference(ReadPreference.valueOf(
                        mongoDBConfiguration.getString(READ_PREFERENCE, READ_PREFERENCE_DEFAULT.getValue())));

        if (mongoDBConfiguration.getString(REPLICA_SET) != null
                && !mongoDBConfiguration.getString(REPLICA_SET).isEmpty()) {
            logger.debug("Setting replicaSet to " + mongoDBConfiguration.getString(REPLICA_SET));
            builder = builder.requiredReplicaSetName(mongoDBConfiguration.getString(REPLICA_SET));
        }

        if (mongoDBConfiguration.getBoolean(SSL_ENABLED)) {
            logger.debug("SSL connections enabled for " + database);
            builder = builder.sslEnabled(mongoDBConfiguration.getBoolean(SSL_ENABLED));
        }

        mongoClientOptions = builder.build();

        assert (dataStoreServerAddresses != null);

        // We create the MongoCredential object
        String user = mongoDBConfiguration.getString(USERNAME, "");
        String pass = mongoDBConfiguration.getString(PASSWORD, "");
        MongoCredential mongoCredential = null;
        if ((user != null && !user.equals("")) || (pass != null && !pass.equals(""))) {
            //                final DB authenticationDatabase;
            if (mongoDBConfiguration.get(AUTHENTICATION_DATABASE) != null
                    && !mongoDBConfiguration.getString(AUTHENTICATION_DATABASE).isEmpty()) {
                //                        authenticationDatabase = mc.getDB(mongoDBConfiguration.getString("authenticationDatabase"));
                mongoCredential = MongoCredential.createScramSha1Credential(user,
                        mongoDBConfiguration.getString(AUTHENTICATION_DATABASE), pass.toCharArray());
            } else {
                //                        authenticationDatabase = db;
                mongoCredential = MongoCredential.createScramSha1Credential(user, "", pass.toCharArray());
            }
            //                    authenticationDatabase.authenticate(user, pass.toCharArray());
        }

        mc = newMongoClient(mongoClientOptions, mongoCredential);

        //                mc.setReadPreference(ReadPreference.secondary(new BasicDBObject("dc", "PG")));
        //                mc.setReadPreference(ReadPreference.primary());
        //                System.out.println("Replica Status: "+mc.getReplicaSetStatus());
        logger.debug(mongoDBConfiguration.toString());
        MongoDatabase db = mc.getDatabase(database);
        //                db.setReadPreference(ReadPreference.secondary(new BasicDBObject("dc", "PG")));
        //                db.setReadPreference(ReadPreference.primary());

        long t1 = System.currentTimeMillis();
        logger.debug("MongoDataStoreManager: MongoDataStore object for database: '" + database + "' created in "
                + (t0 - t1) + "ms");
        mongoDataStore = new MongoDataStore(mc, db, mongoDBConfiguration);
    } else {
        logger.debug("MongoDB database is null or empty");
    }
    return mongoDataStore;
}

From source file:org.wso2.extension.siddhi.store.mongodb.util.MongoTableUtils.java

License:Open Source License

/**
 * Utility method which can be used to create MongoClientOptionsBuilder from values defined in the
 * deployment yaml file.//from ww  w. j  av a2s . c o  m
 *
 * @param storeAnnotation the source annotation which contains the needed parameters.
 * @param configReader    {@link ConfigReader} Configuration Reader
 * @return MongoClientOptions.Builder
 */
public static MongoClientOptions.Builder extractMongoClientOptionsBuilder(Annotation storeAnnotation,
        ConfigReader configReader) {

    MongoClientOptions.Builder mongoClientOptionsBuilder = MongoClientOptions.builder();
    try {
        mongoClientOptionsBuilder.connectionsPerHost(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.CONNECTIONS_PER_HOST, "100")));
        mongoClientOptionsBuilder.connectTimeout(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.CONNECT_TIMEOUT, "10000")));
        mongoClientOptionsBuilder.heartbeatConnectTimeout(Integer
                .parseInt(configReader.readConfig(MongoTableConstants.HEARTBEAT_CONNECT_TIMEOUT, "20000")));
        mongoClientOptionsBuilder.heartbeatSocketTimeout(Integer
                .parseInt(configReader.readConfig(MongoTableConstants.HEARTBEAT_SOCKET_TIMEOUT, "20000")));
        mongoClientOptionsBuilder.heartbeatFrequency(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.HEARTBEAT_FREQUENCY, "10000")));
        mongoClientOptionsBuilder.localThreshold(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.LOCAL_THRESHOLD, "15")));
        mongoClientOptionsBuilder.maxWaitTime(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.MAX_WAIT_TIME, "120000")));
        mongoClientOptionsBuilder.minConnectionsPerHost(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.MIN_CONNECTIONS_PER_HOST, "0")));
        mongoClientOptionsBuilder.minHeartbeatFrequency(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.MIN_HEARTBEAT_FREQUENCY, "500")));
        mongoClientOptionsBuilder.serverSelectionTimeout(Integer
                .parseInt(configReader.readConfig(MongoTableConstants.SERVER_SELECTION_TIMEOUT, "30000")));
        mongoClientOptionsBuilder.socketTimeout(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.SOCKET_TIMEOUT, "0")));
        mongoClientOptionsBuilder.threadsAllowedToBlockForConnectionMultiplier(
                Integer.parseInt(configReader.readConfig(MongoTableConstants.THREADS_ALLOWED_TO_BLOCK, "5")));
        mongoClientOptionsBuilder.socketKeepAlive(
                Boolean.parseBoolean(configReader.readConfig(MongoTableConstants.SOCKET_KEEP_ALIVE, "false")));
        mongoClientOptionsBuilder.sslEnabled(
                Boolean.parseBoolean(configReader.readConfig(MongoTableConstants.SSL_ENABLED, "false")));
        mongoClientOptionsBuilder.cursorFinalizerEnabled(Boolean
                .parseBoolean(configReader.readConfig(MongoTableConstants.CURSOR_FINALIZER_ENABLED, "true")));
        mongoClientOptionsBuilder.readPreference(ReadPreference
                .valueOf(configReader.readConfig(MongoTableConstants.READ_PREFERENCE, "primary")));
        mongoClientOptionsBuilder.writeConcern(WriteConcern
                .valueOf(configReader.readConfig(MongoTableConstants.WRITE_CONCERN, "acknowledged")));

        String readConcern = configReader.readConfig(MongoTableConstants.READ_CONCERN, "DEFAULT");
        if (!readConcern.matches("DEFAULT")) {
            mongoClientOptionsBuilder.readConcern(new ReadConcern(ReadConcernLevel.fromString(readConcern)));
        }

        int maxConnectionIdleTime = Integer
                .parseInt(configReader.readConfig(MongoTableConstants.MAX_CONNECTION_IDLE_TIME, "0"));
        if (maxConnectionIdleTime != 0) {
            mongoClientOptionsBuilder.maxConnectionIdleTime(maxConnectionIdleTime);
        }

        int maxConnectionLifeTime = Integer
                .parseInt(configReader.readConfig(MongoTableConstants.MAX_CONNECTION_LIFE_TIME, "0"));
        if (maxConnectionIdleTime != 0) {
            mongoClientOptionsBuilder.maxConnectionLifeTime(maxConnectionLifeTime);
        }

        String requiredReplicaSetName = configReader.readConfig(MongoTableConstants.REQUIRED_REPLICA_SET_NAME,
                "");
        if (!requiredReplicaSetName.equals("")) {
            mongoClientOptionsBuilder.requiredReplicaSetName(requiredReplicaSetName);
        }

        String applicationName = configReader.readConfig(MongoTableConstants.APPLICATION_NAME, "");
        if (!applicationName.equals("")) {
            mongoClientOptionsBuilder.applicationName(applicationName);
        }

        String secureConnectionEnabled = storeAnnotation
                .getElement(MongoTableConstants.ANNOTATION_ELEMENT_SECURE_CONNECTION);
        secureConnectionEnabled = secureConnectionEnabled == null ? "false" : secureConnectionEnabled;

        if (secureConnectionEnabled.equalsIgnoreCase("true")) {
            mongoClientOptionsBuilder.sslEnabled(true);
            String trustStore = storeAnnotation.getElement(MongoTableConstants.ANNOTATION_ELEMENT_TRUSTSTORE);
            trustStore = trustStore == null ? configReader.readConfig("trustStore", DEFAULT_TRUST_STORE_FILE)
                    : trustStore;
            trustStore = resolveCarbonHome(trustStore);

            String trustStorePassword = storeAnnotation
                    .getElement(MongoTableConstants.ANNOTATION_ELEMENT_TRUSTSTOREPASS);
            trustStorePassword = trustStorePassword == null
                    ? configReader.readConfig("trustStorePassword", DEFAULT_TRUST_STORE_PASSWORD)
                    : trustStorePassword;

            String keyStore = storeAnnotation.getElement(MongoTableConstants.ANNOTATION_ELEMENT_KEYSTORE);
            keyStore = keyStore == null ? configReader.readConfig("keyStore", DEFAULT_KEY_STORE_FILE)
                    : keyStore;
            keyStore = resolveCarbonHome(keyStore);

            String keyStorePassword = storeAnnotation
                    .getElement(MongoTableConstants.ANNOTATION_ELEMENT_STOREPASS);
            keyStorePassword = keyStorePassword == null
                    ? configReader.readConfig("keyStorePassword", DEFAULT_KEY_STORE_PASSWORD)
                    : keyStorePassword;

            mongoClientOptionsBuilder.socketFactory(MongoTableUtils.extractSocketFactory(trustStore,
                    trustStorePassword, keyStore, keyStorePassword));
        }
        return mongoClientOptionsBuilder;
    } catch (IllegalArgumentException e) {
        throw new MongoTableException("Values Read from config readers have illegal values : ", e);
    }
}