Example usage for com.mongodb MongoClientOptions.Builder socketFactory

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

Introduction

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

Prototype

SocketFactory socketFactory

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

Click Source Link

Usage

From source file:com.ca.apm.mongo.Collector.java

License:Open Source License

private MongoClient setupDbClient(final String dbHost, final int dbPort) {
    final boolean useSSL = getBooleanProp(USE_SSL_PROP);
    final String clientTrustStore = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_FILE_PROP);
    final String clientPasswd = getOptionalStringProp(SSL_CLIENT_TRUST_STORE_PASSWD_PROP);

    try {//from   ww w  .  j a v  a  2  s.c o  m
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

        if (useSSL) {
            System.setProperty(SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore);
            System.setProperty(SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd);
            builder = builder.socketFactory(SSLSocketFactory.getDefault());
        }

        final MongoClientOptions options = builder.build();
        return new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options);
    } catch (Exception ex) {
        throw new RuntimeException("Can't initialize mongo client", ex);
    }
}

From source file:com.ca.apm.mongo.Topology.java

License:Open Source License

protected MongoClient setupDbClient(final String dbHost, final int dbPort) {
    final boolean useSSL = Collector.getBooleanProp(Collector.USE_SSL_PROP, props);
    final String clientTrustStore = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP,
            props);//  w  w  w.  ja v  a  2  s . co  m
    final String clientPasswd = Collector.getOptionalStringProp(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP,
            props);

    try {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();

        if (useSSL) {
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_FILE_PROP, clientTrustStore);
            System.setProperty(Collector.SSL_CLIENT_TRUST_STORE_PASSWD_PROP, clientPasswd);
            builder = builder.socketFactory(SSLSocketFactory.getDefault());
        }

        final MongoClientOptions options = builder.build();
        MongoClient dbClient = new MongoClient(new ServerAddress(dbHost, dbPort), mongoCreds, options);
        logger.log(Level.FINE, "Connected to mongo at {0}", dbClient.getConnectPoint());
        logger.log(Level.FINE, "Client options: " + dbClient.getMongoClientOptions());
        return dbClient;
    } catch (Exception ex) {
        throw new RuntimeException("Can't initialize mongo client", ex);
    }
}

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);
    }//w w w .j  av  a 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.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());
        }//  www.j  a  va 2s.c o  m
    }
    return optionsBuilder.build();
}

From source file:com.hurence.logisland.service.mongodb.AbstractMongoDBControllerService.java

License:Apache License

protected Builder getClientOptions(final SSLContext sslContext) {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.sslEnabled(true);/*w  w w.j  a v  a 2 s.  c o  m*/
    builder.socketFactory(sslContext.getSocketFactory());
    return builder;
}

From source file:com.redhat.lightblue.mongo.config.metadata.MongoConfiguration.java

License:Open Source License

/**
 * Returns an options object with defaults overriden where there is a valid override.
 *
 * @return//from   www  .java2  s. c  om
 */
public MongoClientOptions getMongoClientOptions() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();

    if (connectionsPerHost != null) {
        builder.connectionsPerHost(connectionsPerHost);
    }

    if (ssl != null && ssl.booleanValue()) {
        // taken from MongoClientURI, written this way so we don't have to construct a URI to connect
        builder.socketFactory(SSLSocketFactory.getDefault());
    }

    return builder.build();
}

From source file:com.redhat.lightblue.mongo.config.MongoConfiguration.java

License:Open Source License

/**
 * Returns an options object with defaults overriden where there is a valid override.
 *
 * @return//from  ww  w  . j av a2  s. c  om
 */
public MongoClientOptions getMongoClientOptions() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();

    if (connectionsPerHost != null) {
        builder.connectionsPerHost(connectionsPerHost);
    }

    if (ssl) {
        // taken from MongoClientURI, written this way so we don't have to
        // construct a URI to connect
        builder.socketFactory(getSocketFactory());
    }

    return builder.build();
}

From source file:com.socialsky.mods.MongoPersistor.java

License:Apache License

@Override
public void start() {
    super.start();

    address = getOptionalStringConfig("address", "vertx.mongopersistor");

    host = getOptionalStringConfig("host", "localhost");
    port = getOptionalIntConfig("port", 27017);
    dbName = getOptionalStringConfig("db_name", "default_db");
    username = getOptionalStringConfig("username", null);
    password = getOptionalStringConfig("password", null);
    readPreference = ReadPreference.valueOf(getOptionalStringConfig("read_preference", "primary"));
    int poolSize = getOptionalIntConfig("pool_size", 10);
    autoConnectRetry = getOptionalBooleanConfig("auto_connect_retry", true);
    socketTimeout = getOptionalIntConfig("socket_timeout", 60000);
    useSSL = getOptionalBooleanConfig("use_ssl", false);

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

    try {//from ww  w.j  a  v a 2s.  c o  m
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        builder.autoConnectRetry(autoConnectRetry);
        builder.socketTimeout(socketTimeout);
        builder.readPreference(readPreference);

        if (useSSL) {
            builder.socketFactory(SSLSocketFactory.getDefault());
        }

        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);
    }
    eb.registerHandler(address, this);
}

From source file:ezbakehelpers.mongoutils.MongoHelper.java

License:Apache License

public MongoClientOptions getMongoClientOptions() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    if (mongoConfigurationHelper.useMongoDBSSL()) {
        try {/* w ww.j a  v  a2s.  co  m*/
            builder.socketFactory(sslConfigurationHelper.getSystemSSLContext().getSocketFactory());
        } catch (IOException | SSLContextException e) {
            logger.warn("Mongo configured with SSL, but failed to load the system SSL context", e);
        }
    }
    return builder.build();
}

From source file:fr.wseduc.gridfs.GridFSPersistor.java

License:Apache License

public void start() {
    super.start();

    address = getOptionalStringConfig("address", "vertx.gridfspersistor");

    host = getOptionalStringConfig("host", "localhost");
    port = getOptionalIntConfig("port", 27017);
    dbName = getOptionalStringConfig("db_name", "default_db");
    username = getOptionalStringConfig("username", null);
    password = getOptionalStringConfig("password", null);
    ReadPreference readPreference = ReadPreference
            .valueOf(getOptionalStringConfig("read_preference", "primary"));
    int poolSize = getOptionalIntConfig("pool_size", 10);
    boolean autoConnectRetry = getOptionalBooleanConfig("auto_connect_retry", true);
    int socketTimeout = getOptionalIntConfig("socket_timeout", 60000);
    boolean useSSL = getOptionalBooleanConfig("use_ssl", false);
    JsonArray seedsProperty = config.getArray("seeds");
    bucket = getOptionalStringConfig("bucket", "fs");

    try {/*www  . j  a  va2 s .  c o  m*/
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.connectionsPerHost(poolSize);
        builder.autoConnectRetry(autoConnectRetry);
        builder.socketTimeout(socketTimeout);
        builder.readPreference(readPreference);

        if (useSSL) {
            builder.socketFactory(SSLSocketFactory.getDefault());
        }

        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);
    }
    eb.registerHandler(address, this);
    eb.registerHandler(address + ".json", new Handler<Message<JsonObject>>() {
        @Override
        public void handle(Message<JsonObject> message) {
            String action = message.body().getString("action", "");
            switch (action) {
            case "write":
                writeTo(message);
                break;
            default:
                sendError(message, "Invalid action");
            }
        }
    });
}