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:hulop.hokoukukan.utils.MongoAdapter.java

License:Open Source License

private static MongoClientOptions.Builder optionsBuilder(String cert) throws Exception {
    if (!cert.startsWith("-----BEGIN CERTIFICATE-----")) {
        cert = new String(Base64.getDecoder().decode(cert));
    }/*from   w  w w  .j a  va  2 s . co  m*/

    KeyStore keystore = KeyStore.getInstance("PKCS12");
    keystore.load(null);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(cert.getBytes()));
    for (int i = 0; bis.available() > 0; i++) {
        try {
            keystore.setCertificateEntry("alias" + i, cf.generateCertificate(bis));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    bis.close();

    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keystore);
    SSLContext sc = SSLContext.getInstance("TLSv1.2");
    sc.init(null, tmf.getTrustManagers(), new SecureRandom());
    return MongoClientOptions.builder().socketFactory(sc.getSocketFactory()).socketKeepAlive(true);
    //      return MongoClientOptions.builder().sslEnabled(true).sslContext(sc);
}

From source file:in.mtap.iincube.mongoser.config.MongoConfig.java

License:Apache License

private com.mongodb.MongoClient getMongo() {
    if (mongo != null)
        return mongo;
    try {//from   www .j  a  va 2 s.c  o m
        List<ServerAddress> serverAddresses = toAddress(servers);
        MongoClientOptions.Builder opts = new MongoClientOptions.Builder();

        if (threadNo < 100) {
            opts.connectionsPerHost(threadNo);
        } else {
            opts.connectionsPerHost(100);
        }
        opts.threadsAllowedToBlockForConnectionMultiplier(10);
        opts.maxWaitTime(10000);
        mongo = new com.mongodb.MongoClient(serverAddresses, opts.build());
        return mongo;
    } catch (UnknownHostException e) {
        throw new IllegalArgumentException("Unknown host : " + servers);
    }
}

From source file:io.gravitee.repository.mongodb.common.MongoFactory.java

License:Apache License

private MongoClientOptions.Builder builder() {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();

    builder.writeConcern(WriteConcern.SAFE);

    Integer connectionsPerHost = readPropertyValue(propertyPrefix + "connectionsPerHost", Integer.class);
    Integer connectTimeout = readPropertyValue(propertyPrefix + "connectTimeout", Integer.class, 500);
    Integer maxWaitTime = readPropertyValue(propertyPrefix + "maxWaitTime", Integer.class);
    Integer socketTimeout = readPropertyValue(propertyPrefix + "socketTimeout", Integer.class, 500);
    Boolean socketKeepAlive = readPropertyValue(propertyPrefix + "socketKeepAlive", Boolean.class);
    Integer maxConnectionLifeTime = readPropertyValue(propertyPrefix + "maxConnectionLifeTime", Integer.class);
    Integer maxConnectionIdleTime = readPropertyValue(propertyPrefix + "maxConnectionIdleTime", Integer.class);

    // We do not want to wait for a server
    Integer serverSelectionTimeout = readPropertyValue(propertyPrefix + "serverSelectionTimeout", Integer.class,
            0);/*from www . ja v  a2 s  . c  om*/
    Integer minHeartbeatFrequency = readPropertyValue(propertyPrefix + "minHeartbeatFrequency", Integer.class);
    String description = readPropertyValue(propertyPrefix + "description", String.class, "gravitee.io");
    Integer heartbeatConnectTimeout = readPropertyValue(propertyPrefix + "heartbeatConnectTimeout",
            Integer.class, 1000);
    Integer heartbeatFrequency = readPropertyValue(propertyPrefix + "heartbeatFrequency", Integer.class);
    Integer heartbeatSocketTimeout = readPropertyValue(propertyPrefix + "heartbeatSocketTimeout",
            Integer.class);
    Integer localThreshold = readPropertyValue(propertyPrefix + "localThreshold", Integer.class);
    Integer minConnectionsPerHost = readPropertyValue(propertyPrefix + "minConnectionsPerHost", Integer.class);
    Boolean sslEnabled = readPropertyValue(propertyPrefix + "sslEnabled", Boolean.class);
    Integer threadsAllowedToBlockForConnectionMultiplier = readPropertyValue(
            propertyPrefix + "threadsAllowedToBlockForConnectionMultiplier", Integer.class);
    Boolean cursorFinalizerEnabled = readPropertyValue(propertyPrefix + "cursorFinalizerEnabled",
            Boolean.class);

    if (connectionsPerHost != null)
        builder.connectionsPerHost(connectionsPerHost);
    if (maxWaitTime != null)
        builder.maxWaitTime(maxWaitTime);
    if (connectTimeout != null)
        builder.connectTimeout(connectTimeout);
    if (socketTimeout != null)
        builder.socketTimeout(socketTimeout);
    if (socketKeepAlive != null)
        builder.socketKeepAlive(socketKeepAlive);
    if (maxConnectionLifeTime != null)
        builder.maxConnectionLifeTime(maxConnectionLifeTime);
    if (maxConnectionIdleTime != null)
        builder.maxConnectionIdleTime(maxConnectionIdleTime);
    if (minHeartbeatFrequency != null)
        builder.minHeartbeatFrequency(minHeartbeatFrequency);
    if (description != null)
        builder.description(description);
    if (heartbeatConnectTimeout != null)
        builder.heartbeatConnectTimeout(heartbeatConnectTimeout);
    if (heartbeatFrequency != null)
        builder.heartbeatFrequency(heartbeatFrequency);
    if (heartbeatSocketTimeout != null)
        builder.heartbeatSocketTimeout(heartbeatSocketTimeout);
    if (localThreshold != null)
        builder.localThreshold(localThreshold);
    if (minConnectionsPerHost != null)
        builder.minConnectionsPerHost(minConnectionsPerHost);
    if (sslEnabled != null)
        builder.sslEnabled(sslEnabled);
    if (threadsAllowedToBlockForConnectionMultiplier != null)
        builder.threadsAllowedToBlockForConnectionMultiplier(threadsAllowedToBlockForConnectionMultiplier);
    if (cursorFinalizerEnabled != null)
        builder.cursorFinalizerEnabled(cursorFinalizerEnabled);
    if (serverSelectionTimeout != null)
        builder.serverSelectionTimeout(serverSelectionTimeout);

    return builder;
}

From source file:io.gravitee.repository.mongodb.common.MongoFactory.java

License:Apache License

@Override
public Mongo getObject() throws Exception {
    MongoClientOptions.Builder builder = builder();

    // Trying to get the MongoClientURI if uri property is defined
    String uri = readPropertyValue(propertyPrefix + "uri");

    if (uri != null && !uri.isEmpty()) {
        // The builder can be configured with default options, which may be overridden by options specified in
        // the URI string.
        return new MongoClient(new MongoClientURI(uri, builder));
    } else {/* w  w w. j  a va 2 s. co m*/

        String databaseName = readPropertyValue(propertyPrefix + "dbname", String.class, "gravitee");

        String username = readPropertyValue(propertyPrefix + "username");
        String password = readPropertyValue(propertyPrefix + "password");

        List<MongoCredential> credentials = null;
        if (username != null || password != null) {
            credentials = Collections.singletonList(
                    MongoCredential.createMongoCRCredential(username, databaseName, password.toCharArray()));
        }

        List<ServerAddress> seeds;
        int serversCount = getServersCount();

        if (serversCount == 0) {
            String host = readPropertyValue(propertyPrefix + "host", String.class, "localhost");
            int port = readPropertyValue(propertyPrefix + "port", int.class, 27017);
            seeds = Collections.singletonList(new ServerAddress(host, port));
        } else {
            seeds = new ArrayList<>(serversCount);
            for (int i = 0; i < serversCount; i++) {
                seeds.add(buildServerAddress(i));
            }
        }

        MongoClientOptions options = builder.build();
        if (credentials == null) {
            return new MongoClient(seeds, options);
        }

        return new MongoClient(seeds, credentials, options);
    }
}

From source file:io.lumeer.storage.mongodb.MongoDbStorage.java

License:Open Source License

@Override
public void connect(final List<StorageConnection> connections, final String database, final Boolean useSsl) {
    final List<ServerAddress> addresses = new ArrayList<>();

    connections.forEach(c -> {// w  w w.j  a  v a2  s .co  m
        addresses.add(new ServerAddress(c.getHost(), c.getPort()));
    });

    MongoCredential credential = null;
    if (connections.size() > 0 && connections.get(0).getUserName() != null
            && !connections.get(0).getUserName().isEmpty()) {
        credential = MongoCredential.createScramSha1Credential(connections.get(0).getUserName(), database,
                connections.get(0).getPassword());
    }

    final MongoClientOptions.Builder optionsBuilder = (new MongoClientOptions.Builder()).connectTimeout(30000);

    if (useSsl) {
        optionsBuilder.sslEnabled(true).socketFactory(NaiveTrustManager.getSocketFactory())
                .sslInvalidHostNameAllowed(true);
    }

    final CodecRegistry defaultRegistry = MongoClient.getDefaultCodecRegistry();
    final CodecRegistry codecRegistry = CodecRegistries.fromCodecs(new BigDecimalCodec(), new RoleCodec());
    final CodecRegistry providersRegistry = CodecRegistries.fromProviders(new PermissionsCodecProvider(),
            new PermissionCodecProvider(), new QueryCodecProvider(), new ViewCodecProvider(),
            new AttributeCodecProvider(), new LinkInstanceCodecProvider(), new LinkTypeCodecProvider(),
            new UserCodecProvider(), new GroupCodecProvider(), new PaymentCodecProvider(),
            new CompanyContactCodedProvider(), new UserLoginEventCodecProvider(), new FeedbackCodecProvider());
    final CodecRegistry registry = CodecRegistries.fromRegistries(defaultRegistry, codecRegistry,
            providersRegistry);

    if (credential != null) {
        this.mongoClient = new MongoClient(addresses, credential,
                optionsBuilder.codecRegistry(registry).build());
    } else {
        this.mongoClient = new MongoClient(addresses, optionsBuilder.codecRegistry(registry).build());
    }

    this.database = mongoClient.getDatabase(database);
    this.datastore = (AdvancedDatastore) morphia.createDatastore(this.mongoClient, database);
}

From source file:io.mandrel.config.MongoConfiguration.java

License:Apache License

@Bean
public Builder options() {
    CodecRegistry codecRegistry = CodecRegistries.fromRegistries(MongoClient.getDefaultCodecRegistry(),
            CodecRegistries.fromCodecs(new LocalDateTimeCodec(), new HostAndPortCodec(),
                    new LocalDateTimeCodec()));
    return MongoClientOptions.builder().codecRegistry(codecRegistry);
}

From source file:io.opentracing.contrib.mongo.TracingMongoClient.java

License:Apache License

public TracingMongoClient(Tracer tracer, final ServerAddress addr) {
    this(tracer, addr, new MongoClientOptions.Builder().build());
}

From source file:io.opentracing.contrib.mongo.TracingMongoClient.java

License:Apache License

public TracingMongoClient(Tracer tracer, final ServerAddress addr,
        final List<MongoCredential> credentialsList) {
    this(tracer, addr, credentialsList, new MongoClientOptions.Builder().build());
}

From source file:io.opentracing.contrib.mongo.TracingMongoClient.java

License:Apache License

public TracingMongoClient(Tracer tracer, final List<ServerAddress> seeds) {
    this(tracer, seeds, new MongoClientOptions.Builder().build());
}

From source file:io.opentracing.contrib.mongo.TracingMongoClient.java

License:Apache License

public TracingMongoClient(Tracer tracer, final List<ServerAddress> seeds,
        final List<MongoCredential> credentialsList) {
    this(tracer, seeds, credentialsList, new MongoClientOptions.Builder().build());
}