Example usage for com.mongodb MongoClientOptions.Builder readPreference

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

Introduction

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

Prototype

ReadPreference readPreference

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

Click Source Link

Usage

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}
 *///  ww  w .ja v  a  2s  . 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.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}
 *//*  ww w  .j a  va2 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.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.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Utility method to configure Mongo connection options
 * // w  ww. ja va2 s. c om
 * @param optsBuilder an options builder
 * @param connTimeout the connection timeout to use (can be null)
 * @param socketTimeout the socket timeout to use (can be null)
 * @param readPreference the read preference to use (can be null)
 * @param writeConcern the writeConcern to use (can be null)
 * @param wTimeout the w timeout to use (can be null)
 * @param journaled whether to use journaled writes
 * @param tagSet the tag set to use in conjunction with the read preference
 *          (can be null)
 * @param vars variables to use
 * @param log for logging
 * @throws KettleException if a problem occurs
 */
public static void configureConnectionOptions(MongoClientOptions.Builder optsBuilder, String connTimeout,
        String socketTimeout, String readPreference, String writeConcern, String wTimeout, boolean journaled,
        List<String> tagSet, VariableSpace vars, LogChannelInterface log) throws KettleException {

    // connection timeout
    if (!Const.isEmpty(connTimeout)) {
        String connS = vars.environmentSubstitute(connTimeout);
        try {
            int cTimeout = Integer.parseInt(connS);
            if (cTimeout > 0) {
                optsBuilder.connectTimeout(cTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    // socket timeout
    if (!Const.isEmpty(socketTimeout)) {
        String sockS = vars.environmentSubstitute(socketTimeout);
        try {
            int sockTimeout = Integer.parseInt(sockS);
            if (sockTimeout > 0) {
                optsBuilder.socketTimeout(sockTimeout);
            }
        } catch (NumberFormatException n) {
            throw new KettleException(n);
        }
    }

    if (log != null) {
        String rpLogSetting = NamedReadPreference.PRIMARY.getName();

        if (!Const.isEmpty(readPreference)) {
            rpLogSetting = readPreference;
        }
        log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.UsingReadPreference", rpLogSetting)); //$NON-NLS-1$
    }
    DBObject firstTagSet = null;
    DBObject[] remainingTagSets = new DBObject[0];
    if (tagSet != null && tagSet.size() > 0) {
        if (tagSet.size() > 1) {
            remainingTagSets = new DBObject[tagSet.size() - 1];
        }

        firstTagSet = (DBObject) JSON.parse(tagSet.get(0).trim());
        for (int i = 1; i < tagSet.size(); i++) {
            remainingTagSets[i - 1] = (DBObject) JSON.parse(tagSet.get(i).trim());
        }
        if (log != null && (!Const.isEmpty(readPreference)
                && !readPreference.equalsIgnoreCase(NamedReadPreference.PRIMARY.getName()))) {
            StringBuilder builder = new StringBuilder();
            for (String s : tagSet) {
                builder.append(s).append(" "); //$NON-NLS-1$
            }
            log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.UsingReadPreferenceTagSets", //$NON-NLS-1$
                    builder.toString()));
        }
    } else {
        if (log != null) {
            log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.NoReadPreferenceTagSetsDefined")); //$NON-NLS-1$
        }
    }

    // read preference
    if (!Const.isEmpty(readPreference)) {

        String rp = vars.environmentSubstitute(readPreference);

        NamedReadPreference preference = NamedReadPreference.byName(rp);

        if ((firstTagSet != null) && (preference.getPreference() instanceof TaggableReadPreference)) {
            optsBuilder.readPreference(preference.getTaggableReadPreference(firstTagSet, remainingTagSets));
        } else {
            optsBuilder.readPreference(preference.getPreference());
        }

    }

    // write concern
    writeConcern = vars.environmentSubstitute(writeConcern);
    wTimeout = vars.environmentSubstitute(wTimeout);

    WriteConcern concern = null;

    if (Const.isEmpty(writeConcern) && Const.isEmpty(wTimeout) && !journaled) {
        // all defaults - timeout 0, journal = false, w = 1
        concern = new WriteConcern();
        concern.setWObject(new Integer(1));

        if (log != null) {
            log.logBasic(BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithDefaultWriteConcern"));
        }
    } else {
        int wt = 0;
        if (!Const.isEmpty(wTimeout)) {
            try {
                wt = Integer.parseInt(wTimeout);
            } catch (NumberFormatException n) {
                throw new KettleException(n);
            }
        }

        if (!Const.isEmpty(writeConcern)) {
            // try parsing as a number first
            try {
                int wc = Integer.parseInt(writeConcern);
                concern = new WriteConcern(wc, wt, false, journaled);

                if (log != null) {
                    String lwc = "w = " + writeConcern + ", wTimeout = " + wt + ", journaled = "
                            + (new Boolean(journaled).toString());
                    log.logBasic(
                            BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
                }
            } catch (NumberFormatException n) {
                // assume its a valid string - e.g. "majority" or a custom
                // getLastError label associated with a tag set
                concern = new WriteConcern(writeConcern, wt, false, journaled);

                if (log != null) {
                    String lwc = "w = " + writeConcern + ", wTimeout = " + wt + ", journaled = "
                            + (new Boolean(journaled).toString());
                    log.logBasic(
                            BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
                }
            }
        } else {
            concern = new WriteConcern(1, wt, false, journaled);

            if (log != null) {
                String lwc = "w = 1" + ", wTimeout = " + wt + ", journaled = "
                        + (new Boolean(journaled).toString());
                log.logBasic(
                        BaseMessages.getString(PKG, "MongoUtils.Message.ConfiguringWithWriteConcern", lwc));
            }
        }
    }
    optsBuilder.writeConcern(concern);
}

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./*  w ww .j  a v  a 2  s .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);
    }
}

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();
}