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.pentaho.mongo.MongoProperties.java

License:Open Source License

/**
 * Constructs MongoClientOptions from the relevant set of properties.
 * See the descriptions of each property in {@link MongoProp}
 * @param log/*from  ww w.j  a  v a2  s  .co m*/
 * @return
 * @throws MongoDbException
 */
public MongoClientOptions buildMongoClientOptions(MongoUtilLogger log) throws MongoDbException {
    MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
    MongoPropToOption propToOption = new MongoPropToOption(log);
    for (MongoProp prop : MongoProp.values()) {
        prop.setOption(builder, this, propToOption);
    }
    return builder.build();
}

From source file:org.pentaho.mongo.MongoUtils.java

License:Open Source License

/**
 * Utility method to configure Mongo connection options
 * /*from www. j  a  v  a2  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.pentaho.mongo.MongoUtils.java

License:Open Source License

public static MongoClient initConnection(String hostsPorts, String singlePort, MongoCredential cred,
        boolean useAllReplicaSetMembers, String connTimeout, String socketTimeout, String readPreference,
        String writeConcern, String wTimeout, boolean journaled, List<String> tagSet, VariableSpace vars,
        LogChannelInterface log) throws KettleException {

    hostsPorts = vars.environmentSubstitute(hostsPorts);
    singlePort = vars.environmentSubstitute(singlePort);
    int singlePortI = -1;

    try {/*from   www .j a  v a 2  s  .c  om*/
        singlePortI = Integer.parseInt(singlePort);
    } catch (NumberFormatException n) {
        // don't complain
    }

    if (Const.isEmpty(hostsPorts)) {
        throw new KettleException(BaseMessages.getString(PKG, "MongoUtils.Message.Error.EmptyHostsString")); //$NON-NLS-1$
    }

    List<ServerAddress> repSet = new ArrayList<ServerAddress>();

    // if (useAllReplicaSetMembers) {
    // repSet = getReplicaSetMembers(hostsPorts, singlePort, cred, vars, log);
    //
    // if (repSet.size() == 0) {
    // useAllReplicaSetMembers = false; // drop back and just configure using
    // // what we've been given
    // } else {
    // if (log != null) {
    // StringBuilder builder = new StringBuilder();
    // for (ServerAddress s : repSet) {
    // builder.append(s.toString()).append(" ");
    // }
    // log.logBasic(BaseMessages.getString(PKG,
    // "MongoUtils.Message.UsingTheFollowingReplicaSetMembers")
    // + " "
    // + builder.toString());
    // }
    // }
    // }

    // if (!useAllReplicaSetMembers) {
    String[] parts = hostsPorts.trim().split(","); //$NON-NLS-1$
    for (String part : parts) {
        // host:port?
        int port = singlePortI != -1 ? singlePortI : MONGO_DEFAULT_PORT;
        String[] hp = part.split(":"); //$NON-NLS-1$
        if (hp.length > 2) {
            throw new KettleException(
                    BaseMessages.getString(PKG, "MongoUtils.Message.Error.MalformedHost", part)); //$NON-NLS-1$
        }

        String host = hp[0];
        if (hp.length == 2) {
            // non-default port
            try {
                port = Integer.parseInt(hp[1].trim());
            } catch (NumberFormatException n) {
                throw new KettleException(
                        BaseMessages.getString(PKG, "MongoUtils.Message.Error.UnableToParsePortNumber", hp[1])); //$NON-NLS-1$
            }
        }

        try {
            ServerAddress s = new ServerAddress(host, port);
            repSet.add(s);
        } catch (UnknownHostException u) {
            throw new KettleException(u);
        }
    }
    // }

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

    configureConnectionOptions(mongoOptsBuilder, connTimeout, socketTimeout, readPreference, writeConcern,
            wTimeout, journaled, tagSet, vars, log);

    MongoClientOptions opts = mongoOptsBuilder.build();
    try {
        // Mongo's java driver will discover all replica set or shard
        // members (Mongos) automatically when MongoClient is constructed
        // using a list of ServerAddresses. The javadocs state that MongoClient
        // should be constructed using a SingleServer address instance (rather
        // than a list) when connecting to a stand-alone host - this is why
        // we differentiate here between a list containing one ServerAddress
        // and a single ServerAddress instance via the useAllReplicaSetMembers
        // flag.

        if (cred == null) {
            return (repSet.size() > 1 || (useAllReplicaSetMembers && repSet.size() >= 1)
                    ? new MongoClient(repSet, opts)
                    : (repSet.size() == 1 ? new MongoClient(repSet.get(0), opts)
                            : new MongoClient(new ServerAddress("localhost"), opts))); //$NON-NLS-1$
        }

        List<MongoCredential> credList = new ArrayList<MongoCredential>();
        credList.add(cred);
        return (repSet.size() > 1 || (useAllReplicaSetMembers && repSet.size() >= 1)
                ? new MongoClient(repSet, credList, opts)
                : (repSet.size() == 1 ? new MongoClient(repSet.get(0), credList, opts)
                        : new MongoClient(new ServerAddress("localhost"), credList, opts))); //$NON-NLS-1$
    } catch (UnknownHostException u) {
        throw new KettleException(u);
    }
}

From source file:org.perfcake.message.sender.MongoDBSender.java

License:Apache License

@Override
public void doInit(final Properties messageAttributes) throws PerfCakeException {
    final String t = getTarget(messageAttributes);
    final ServerAddress a;

    if (t.contains(":")) {
        final String[] addr = t.split(":", 2);
        final String host = addr[0];
        final int port = Integer.valueOf(addr[1]);
        a = new ServerAddress(host, port);
    } else {//w  w  w .j av a 2  s  .  c o m
        a = new ServerAddress(t);
    }

    if (dbUsername != null) {
        final MongoCredential c = MongoCredential.createScramSha1Credential(dbUsername, dbName,
                dbPassword.toCharArray());
        mongoClient = new MongoClient(a, Collections.singletonList(c),
                MongoClientOptions.builder().connectionsPerHost(connectionPoolSize).build());
    } else {
        mongoClient = new MongoClient(a,
                MongoClientOptions.builder().connectionsPerHost(connectionPoolSize).build());
    }

    db = mongoClient.getDatabase(dbName);
}

From source file:org.radarcns.connect.mongodb.MongoWrapper.java

License:Apache License

private MongoClient createClient(AbstractConfig config, MongoClientOptions options) {
    String host = config.getString(MONGO_HOST);
    int port = config.getInt(MONGO_PORT);

    try {/*from w w w .  ja  va  2  s.co m*/
        MongoClientOptions actualOptions;
        if (options != null) {
            actualOptions = options;
        } else {
            actualOptions = new MongoClientOptions.Builder().build();
        }
        ServerAddress server = new ServerAddress(host, port);
        if (credentials != null) {
            return new MongoClient(server, credentials, actualOptions);
        } else {
            return new MongoClient(server, actualOptions);
        }
    } catch (MongoException ex) {
        log.error("Failed to create MongoDB client to {}:{} with credentials {}", host, port, credentials, ex);
        throw new ConnectException("MongoDb client cannot be created.", ex);
    }
}

From source file:org.radarcns.listener.MongoFactory.java

License:Apache License

@Override
public MongoClient get() {
    MongoCredential credentials = Properties.getApiConfig().getMongoDbCredentials();
    List<ServerAddress> hosts = Properties.getApiConfig().getMongoDbHosts();

    return new MongoClient(hosts, credentials, MongoClientOptions.builder().build());
}

From source file:org.radarcns.mongodb.MongoWrapper.java

License:Apache License

private MongoClient createClient(AbstractConfig config, MongoClientOptions options) {
    String host = config.getString(MONGO_HOST);
    int port = config.getInt(MONGO_PORT);

    try {//from   w w  w.  j av  a2s .  com
        if (options == null) {
            options = new MongoClientOptions.Builder().build();
        }
        return new MongoClient(new ServerAddress(host, port), credentials, options);
    } catch (com.mongodb.MongoSocketOpenException e) {
        log.error("Failed to create MongoDB client to {}:{} with credentials {}", host, port, credentials, e);
        throw new ConnectException("MongoDb client cannot be created.", e);
    }
}

From source file:org.s1.mongodb.MongoDBConnectionHelper.java

License:Apache License

/**
 *
 * @param instance/*w ww  .ja  v a2s  .c  o  m*/
 */
private static synchronized void initialize(String instance) {
    if (!connections.containsKey(instance)) {

        Map<String, Object> mopt = Options.getStorage().getMap(OPTIONS);
        Map<String, Object> m = Objects.get(mopt, "connections." + instance);
        if (Objects.isNullOrEmpty(m)) {
            m = Objects.get(mopt, "connections." + DEFAULT_INSTANCE);
        }

        MongoClientOptions.Builder b = MongoClientOptions.builder();
        MongoClientOptions def_opt = MongoClientOptions.builder().build();
        b.connectionsPerHost(Objects.get(m, "connectionsPerHost", def_opt.getConnectionsPerHost()));
        b.autoConnectRetry(Objects.get(m, "autoConnectRetry", def_opt.isAutoConnectRetry()));
        b.connectTimeout(Objects.get(m, "connectTimeout", def_opt.getConnectTimeout()));
        b.socketKeepAlive(Objects.get(m, "socketKeepAlive", def_opt.isSocketKeepAlive()));
        b.socketTimeout(Objects.get(m, "socketTimeout", def_opt.getSocketTimeout()));
        b.maxAutoConnectRetryTime(
                Objects.get(m, "maxAutoConnectRetryTime", def_opt.getMaxAutoConnectRetryTime()));
        b.maxWaitTime(Objects.get(m, "maxWaitTime", def_opt.getMaxWaitTime()));
        b.threadsAllowedToBlockForConnectionMultiplier(
                Objects.get(m, "threadsAllowedToBlockForConnectionMultiplier",
                        def_opt.getThreadsAllowedToBlockForConnectionMultiplier()));
        b.writeConcern(WriteConcern.FSYNC_SAFE);
        MongoClientOptions opt = b.build();

        MongoClient cl = null;
        try {
            cl = new MongoClient(
                    new ServerAddress(Objects.get(m, "host", "localhost"), Objects.get(m, "port", 27017)), opt);
        } catch (UnknownHostException e) {
            throw S1SystemError.wrap(e);
        }

        String dbName = Objects.get(m, "name");
        if (Objects.isNullOrEmpty(dbName))
            throw new S1SystemError("Cannot initialize MongoDB connection, because name is not set");

        DB db = cl.getDB(dbName);

        String user = Objects.get(m, "user");
        String password = Objects.get(m, "password");
        if (!Objects.isNullOrEmpty(user)) {
            if (!db.authenticate(user, password.toCharArray())) {
                throw new S1SystemError(
                        "Cannot authenticate MongoDB connection " + dbName + " with user " + user);
            }
        }
        LOG.info("MongoDB connected " + cl.getAddress().getHost() + ":" + cl.getAddress().getPort());

        connections.put(instance, db);
    }
}

From source file:org.socialhistoryservices.dao.MongoDBSingleton.java

License:Open Source License

public MongoDBSingleton(String[] hosts, int connectionsPerHost, int writeConcern) {
    final MongoClientOptions.Builder builder = new MongoClientOptions.Builder()
            .connectionsPerHost(connectionsPerHost).writeConcern(new WriteConcern(writeConcern));
    setMongo(hosts, builder.build());//from w w  w .ja v  a 2  s .  com
}

From source file:org.springframework.boot.autoconfigure.mongo.MongoClientFactory.java

License:Apache License

private MongoClient createEmbeddedMongoClient(MongoClientOptions options, int port) {
    if (options == null) {
        options = MongoClientOptions.builder().build();
    }/*from  www. j  ava2 s.co  m*/
    String host = (this.properties.getHost() != null) ? this.properties.getHost() : "localhost";
    return new MongoClient(Collections.singletonList(new ServerAddress(host, port)), options);
}