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.edgytech.umongo.ConnectDialog.java

License:Apache License

MongoClientOptions getMongoClientOptions() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    //        moptions.connectionsPerHost = getIntFieldValue(Item.connectionsPerHost);
    //        moptions.threadsAllowedToBlockForConnectionMultiplier = getIntFieldValue(Item.blockingThreadMultiplier);
    //        moptions.maxWaitTime = getIntFieldValue(Item.maxWaitTime);
    builder.connectTimeout(getIntFieldValue(Item.connectTimeout));
    builder.socketTimeout(getIntFieldValue(Item.socketTimeout));
    //        moptions.autoConnectRetry = getBooleanFieldValue(Item.autoConnectRetry);
    if (!getBooleanFieldValue(Item.safeWrites)) {
        builder.writeConcern(WriteConcern.NONE);
    }//from  w  w w .  ja  va 2  s.  co  m

    //        moptions.slaveOk = getBooleanFieldValue(Item.secondaryReads);
    if (getBooleanFieldValue(Item.secondaryReads)) {
        builder.readPreference(ReadPreference.secondaryPreferred());
    }

    int stype = getIntFieldValue(Item.socketType);
    int proxy = getIntFieldValue(Item.proxyType);
    if (proxy == 1) {
        // SOCKS proxy
        final String host = getStringFieldValue(Item.proxyHost);
        final int port = getIntFieldValue(Item.proxyPort);
        builder.socketFactory(new SocketFactory() {

            @Override
            public Socket createSocket() throws IOException {
                SocketAddress addr = new InetSocketAddress(host, port);
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
                Socket socket = new Socket(proxy);
                return socket;
            }

            @Override
            public Socket createSocket(String string, int i) throws IOException, UnknownHostException {
                SocketAddress addr = new InetSocketAddress(host, port);
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
                Socket socket = new Socket(proxy);
                InetSocketAddress dest = new InetSocketAddress(string, i);
                socket.connect(dest);
                return socket;
            }

            @Override
            public Socket createSocket(String string, int i, InetAddress ia, int i1)
                    throws IOException, UnknownHostException {
                throw new UnsupportedOperationException("Not supported yet.");
            }

            @Override
            public Socket createSocket(InetAddress ia, int i) throws IOException {
                SocketAddress addr = new InetSocketAddress(host, port);
                Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
                Socket socket = new Socket(proxy);
                InetSocketAddress dest = new InetSocketAddress(ia, i);
                socket.connect(dest);
                return socket;
            }

            @Override
            public Socket createSocket(InetAddress ia, int i, InetAddress ia1, int i1) throws IOException {
                throw new UnsupportedOperationException("Not supported yet.");
            }
        });

        //            // authentication.. only supports 1 global for all proxies :(
        //            final String user = getStringFieldValue(Item.proxyUser);
        //            final String pwd = getStringFieldValue(Item.proxyPassword);
        //            if (!user.isEmpty()) {
        //                Authenticator.setDefault(new Authenticator() {
        //                    @Override
        //                    protected PasswordAuthentication getPasswordAuthentication() {
        //                        PasswordAuthentication p = new PasswordAuthentication(user, pwd.toCharArray());
        //                        return p;
        //                    }
        //                });
        //            }
    }

    if (stype == 1) {
        builder.socketFactory(SSLSocketFactory.getDefault());
    } else if (stype == 2) {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
            }
        } };
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            builder.socketFactory(sc.getSocketFactory());
        } catch (Exception e) {
        }
    }

    return builder.build();
}

From source file:com.effektif.mongo.MongoConfiguration.java

License:Apache License

public void setOptionBuilder(MongoClientOptions.Builder optionBuilder) {
    this.optionBuilder = optionBuilder;
}

From source file:com.effektif.mongo.MongoConfiguration.java

License:Apache License

public MongoClientOptions.Builder getOptionBuilder() {
    return optionBuilder;
}

From source file:com.eightkdata.mongowp.client.wrapper.MongoClientWrapper.java

License:Open Source License

private MongoClientOptions toMongoClientOptions(MongoClientConfiguration configuration) {
    MongoClientOptions.Builder optionsBuilder = MongoClientOptions.builder();
    if (configuration.isSslEnabled()) {
        optionsBuilder.sslEnabled(configuration.isSslEnabled());
        if (configuration.getSocketFactory() != null) {
            optionsBuilder.socketFactory(configuration.getSocketFactory());
            optionsBuilder.sslInvalidHostNameAllowed(configuration.isSslAllowInvalidHostnames());
        }/*from w w w  .  j a va  2s  . co  m*/
    }
    return optionsBuilder.build();
}

From source file:com.englishtown.vertx.GridFSModule.java

License:Open Source License

@Override
public void start() {
    eb = vertx.eventBus();//  w  w  w  .  j  a va 2s.c o  m
    logger = container.logger();

    JsonObject config = container.config();
    address = config.getString("address", DEFAULT_ADDRESS);

    host = config.getString("host", "localhost");
    port = config.getInteger("port", 27017);
    dbName = config.getString("db_name", "default_db");
    username = config.getString("username", null);
    password = config.getString("password", null);
    int poolSize = config.getInteger("pool_size", 10);

    JsonArray seedsProperty = config.getArray("seeds");

    try {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        if (seedsProperty == null) {
            ServerAddress address = new ServerAddress(host, port);
            mongo = new MongoClient(address, builder.build());
        } else {
            List<ServerAddress> seeds = makeSeeds(seedsProperty);
            mongo = new MongoClient(seeds, builder.build());
        }
        db = mongo.getDB(dbName);
        if (username != null && password != null) {
            db.authenticate(username, password.toCharArray());
        }
    } catch (UnknownHostException e) {
        logger.error("Failed to connect to mongo server", e);
    }

    // Main Message<JsonObject> handler that inspects an "action" field
    eb.registerHandler(address, this);

    // Message<byte[]> handler to save file chunks
    eb.registerHandler(address + "/saveChunk", new Handler<Message<Buffer>>() {
        @Override
        public void handle(Message<Buffer> message) {
            saveChunk(message);
        }
    });

}

From source file:com.epam.ta.reportportal.config.MongodbConfiguration.java

License:Open Source License

@Bean
@Profile("!unittest")
MongoClient mongo() throws UnknownHostException {
    MongoClientOptions.Builder mongoClientBuilder = MongoClientOptions.builder();
    mongoClientBuilder.connectionsPerHost(mongoProperties.getConnectionsPerHost())
            .threadsAllowedToBlockForConnectionMultiplier(
                    mongoProperties.getThreadsAllowedToBlockForConnectionMultiplier())
            .connectTimeout(mongoProperties.getConnectTimeout())
            .socketTimeout(mongoProperties.getSocketTimeout()).maxWaitTime(mongoProperties.getMaxWaitTime())
            .socketKeepAlive(mongoProperties.getSocketKeepAlive());

    List<MongoCredential> credentials = Collections.emptyList();
    if (!Strings.isNullOrEmpty(mongoProperties.getUser())
            && !Strings.isNullOrEmpty(mongoProperties.getPassword())) {
        credentials = Collections.singletonList(MongoCredential.createCredential(mongoProperties.getUser(),
                mongoProperties.getDbName(), mongoProperties.getPassword().toCharArray()));
    }/*from   ww  w  . j  a  v  a2 s.com*/

    return new MongoClient(new ServerAddress(mongoProperties.getHost(), mongoProperties.getPort()), credentials,
            mongoClientBuilder.build());
}

From source file:com.ewerk.prototype.persistence.PersistenceConfiguration.java

License:Apache License

/**
 * Customize the MongoDB client connection properties.
 *
 * @return A {@link MongoClientOptions} bean that is used by the {@link
 * org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration} when creating the {@link
 * com.mongodb.Mongo} facade/*from w ww.  ja v a 2  s.  c  o  m*/
 * @see com.mongodb.MongoClientOptions
 * @see org.springframework.core.env.Environment
 */
@Bean
public MongoClientOptions mongoClientOptions(
        @Value("${spring.data.mongodb.min-connections:2}") final int minConnections,
        @Value("${spring.data.mongodb.max-connections:10}") final int maxConnections,
        @Value("${spring.data.mongodb.socket-connect.ms:5000}") final int connectTimeout,
        @Value("${spring.data.mongodb.socket-timeout.ms:5000}") final int socketTimeout) {

    return MongoClientOptions.builder().legacyDefaults().minConnectionsPerHost(minConnections)
            .connectionsPerHost(maxConnections).connectTimeout(connectTimeout).socketTimeout(socketTimeout)
            .build();
}

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

License:Apache License

@Singleton
@Provides/*from   w  ww .j a  v  a2  s . 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())
            .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.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

private MongoClient initConnection(MongoDbMeta meta, VariableSpace vars, LogChannelInterface log)
        throws KettleException {
    String hostsPorts = vars.environmentSubstitute(meta.getHostnames());
    String singlePort = vars.environmentSubstitute(meta.getPort());
    String connTimeout = meta.getConnectTimeout();
    String socketTimeout = meta.getSocketTimeout();
    String readPreference = meta.getReadPreference();
    String writeConcern = meta.getWriteConcern();
    String wTimeout = meta.getWTimeout();
    boolean journaled = meta.getJournal();
    List<String> tagSet = meta.getReadPrefTagSets();
    boolean useAllReplicaSetMembers = meta.getUseAllReplicaSetMembers();
    int singlePortI = -1;

    try {// w  w  w.j  a va  2  s .c  o m
        singlePortI = Integer.parseInt(singlePort);
    } catch (NumberFormatException n) {
        // don't complain
    }

    if (Const.isEmpty(hostsPorts)) {
        throw new KettleException(
                BaseMessages.getString(PKG, "MongoNoAuthWrapper.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, "MongoNoAuthWrapper.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,
                        "MongoNoAuthWrapper.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();
    return getClient(meta, vars, log, repSet, useAllReplicaSetMembers, opts);
}

From source file:com.github.maasdi.mongo.wrapper.NoAuthMongoClientWrapper.java

License:Apache License

/**
 * Utility method to configure Mongo connection options
 *
 * @param optsBuilder//from  w w w  . j  av  a  2 s. com
 *          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
 */
private 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, "MongoNoAuthWrapper.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, "MongoNoAuthWrapper.Message.UsingReadPreferenceTagSets", //$NON-NLS-1$
                    builder.toString()));
        }
    } else {
        if (log != null) {
            log.logBasic(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.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,
                    "MongoNoAuthWrapper.Message.ConfiguringWithDefaultWriteConcern")); //$NON-NLS-1$
        }
    } 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);
            } 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);
            }
        } else {
            concern = new WriteConcern(1, wt, false, journaled);
        }

        if (log != null) {
            String lwc = "w = " + concern.getW() + ", wTimeout = " + concern.getWtimeout() + ", journaled = "
                    + concern.getJ();
            log.logBasic(
                    BaseMessages.getString(PKG, "MongoNoAuthWrapper.Message.ConfiguringWithWriteConcern", lwc));
        }
    }
    optsBuilder.writeConcern(concern);
}