Example usage for com.mongodb.connection ClusterSettings builder

List of usage examples for com.mongodb.connection ClusterSettings builder

Introduction

In this page you can find the example usage for com.mongodb.connection ClusterSettings builder.

Prototype

public static Builder builder() 

Source Link

Document

Get a builder for this class.

Usage

From source file:com.github.frapontillo.pulse.crowd.data.repository.Repository.java

License:Apache License

/**
 * Create a new Repository using the default configuration in `database.properties` and
 * overriding the db name/*from  w ww .j  a  v a 2  s.  co  m*/
 * with the one in input.
 *
 * @param db The database name to use for this Repository instance.
 */
@SuppressWarnings({ "unchecked", "deprecation" })
public Repository(String db) {
    DBConfig config = new DBConfig(getClass(), db);

    MongoClient client = new MongoClient(config.getServerAddress(), config.getCredentials());

    // map all Morphia classes
    morphia = new Morphia();
    morphia.mapPackageFromClass(Message.class);

    ClusterSettings clusterSettings = ClusterSettings.builder()
            .hosts(Collections.singletonList(config.getServerAddress())).build();
    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings)
            .credentialList(config.getCredentials()).build();
    com.mongodb.reactivestreams.client.MongoClient rxClient = MongoClients.create(settings);

    // create and/or get the datastore
    datastore = morphia.createDatastore(client, config.getDBName());
    // init the DAO
    initDAO(datastore);
    ensureIndexes();

    // create the reactive database
    rxDatastore = rxClient.getDatabase(config.getDBName());

}

From source file:com.github.krr.mongodb.aggregate.support.config.ReactiveMongoClientTestConfiguration.java

License:Apache License

@Bean
public MongoClient mongoClient() throws IOException {
    ServerAddress serverAddress = getServerAddress();
    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(ClusterSettings.builder()
            .hosts(singletonList(serverAddress)).requiredClusterType(STANDALONE).build()).build();
    return MongoClients.create(settings);
}

From source file:com.supermy.im.mongo.MongoRepository.java

License:Apache License

@Bean(name = "mongoClient")
public MongoClient mongoClient() {
    System.out.println("*******************" + mongoAddress);

    ClusterSettings clusterSettings = ClusterSettings.builder()
            .hosts(Arrays.asList(new ServerAddress(mongoAddress))).build();
    MongoCredential credential = MongoCredential.createCredential(mongoUser, mydb, mongoPasswd.toCharArray());

    MongoClientSettings settings = MongoClientSettings.builder()
            .streamFactoryFactory(new NettyStreamFactoryFactory()).clusterSettings(clusterSettings)
            .credentialList(Arrays.asList(credential)).build();

    //        MongoClient mongoClient = new MongoClient(new ServerAddress(), Arrays.asList(credential));

    MongoClient mongoClient = MongoClients.create(settings);
    return mongoClient;
}

From source file:io.gravitee.am.identityprovider.mongo.authentication.spring.MongoAuthenticationProviderConfiguration.java

License:Apache License

@Bean
public MongoClient mongoClient() {
    MongoClient mongoClient;//www . j av  a2s  .  c o m
    if ((this.configuration.getUri() != null) && (!this.configuration.getUri().isEmpty())) {
        mongoClient = MongoClients.create(this.configuration.getUri());
    } else {
        ServerAddress serverAddress = new ServerAddress(this.configuration.getHost(),
                this.configuration.getPort());
        ClusterSettings clusterSettings = ClusterSettings.builder().hosts(asList(serverAddress)).build();
        MongoClientSettings.Builder settings = MongoClientSettings.builder().clusterSettings(clusterSettings);
        if (this.configuration.isEnableCredentials()) {
            MongoCredential credential = MongoCredential.createCredential(
                    this.configuration.getUsernameCredentials(), this.configuration.getDatabaseCredentials(),
                    this.configuration.getPasswordCredentials().toCharArray());
            settings.credential(credential);
        }
        mongoClient = MongoClients.create(settings.build());
    }
    return mongoClient;
}

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

License:Apache License

@Override
public MongoClient getObject() throws Exception {
    // Client settings
    MongoClientSettings.Builder builder = MongoClientSettings.builder();
    builder.writeConcern(WriteConcern.ACKNOWLEDGED);

    // codec configuration for pojo mapping
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));
    builder.codecRegistry(pojoCodecRegistry);

    // 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.
        MongoClientSettings settings = builder.codecRegistry(pojoCodecRegistry)
                .applyConnectionString(new ConnectionString(uri)).build();

        return MongoClients.create(settings);
    } else {//  w  w w  .  j av  a2 s .  com
        // Advanced configuration
        SocketSettings.Builder socketBuilder = SocketSettings.builder();
        ClusterSettings.Builder clusterBuilder = ClusterSettings.builder();
        ConnectionPoolSettings.Builder connectionPoolBuilder = ConnectionPoolSettings.builder();
        ServerSettings.Builder serverBuilder = ServerSettings.builder();
        SslSettings.Builder sslBuilder = SslSettings.builder();

        Integer connectTimeout = readPropertyValue(propertyPrefix + "connectTimeout", Integer.class, 1000);
        Integer maxWaitTime = readPropertyValue(propertyPrefix + "maxWaitTime", Integer.class);
        Integer socketTimeout = readPropertyValue(propertyPrefix + "socketTimeout", Integer.class, 1000);
        Boolean socketKeepAlive = readPropertyValue(propertyPrefix + "socketKeepAlive", Boolean.class, true);
        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, 1000);
        Integer minHeartbeatFrequency = readPropertyValue(propertyPrefix + "minHeartbeatFrequency",
                Integer.class);
        String description = readPropertyValue(propertyPrefix + "description", String.class, "gravitee.io");
        Integer heartbeatFrequency = readPropertyValue(propertyPrefix + "heartbeatFrequency", Integer.class);
        Boolean sslEnabled = readPropertyValue(propertyPrefix + "sslEnabled", Boolean.class);

        if (maxWaitTime != null)
            connectionPoolBuilder.maxWaitTime(maxWaitTime, TimeUnit.MILLISECONDS);
        if (connectTimeout != null)
            socketBuilder.connectTimeout(connectTimeout, TimeUnit.MILLISECONDS);
        if (socketTimeout != null)
            socketBuilder.readTimeout(socketTimeout, TimeUnit.MILLISECONDS);
        if (socketKeepAlive != null)
            socketBuilder.keepAlive(socketKeepAlive);
        if (maxConnectionLifeTime != null)
            connectionPoolBuilder.maxConnectionLifeTime(maxConnectionLifeTime, TimeUnit.MILLISECONDS);
        if (maxConnectionIdleTime != null)
            connectionPoolBuilder.maxConnectionIdleTime(maxConnectionIdleTime, TimeUnit.MILLISECONDS);
        if (minHeartbeatFrequency != null)
            serverBuilder.minHeartbeatFrequency(minHeartbeatFrequency, TimeUnit.MILLISECONDS);
        if (description != null)
            clusterBuilder.description(description);
        if (heartbeatFrequency != null)
            serverBuilder.heartbeatFrequency(heartbeatFrequency, TimeUnit.MILLISECONDS);
        if (sslEnabled != null)
            sslBuilder.enabled(sslEnabled);
        if (serverSelectionTimeout != null)
            clusterBuilder.serverSelectionTimeout(serverSelectionTimeout, TimeUnit.MILLISECONDS);

        // credentials option
        String username = readPropertyValue(propertyPrefix + "username");
        String password = readPropertyValue(propertyPrefix + "password");
        MongoCredential credentials = null;
        if (username != null || password != null) {
            String authSource = readPropertyValue(propertyPrefix + "authSource", String.class, "gravitee-am");
            credentials = MongoCredential.createCredential(username, authSource, password.toCharArray());
            builder.credential(credentials);
        }

        // clustering option
        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));
            }
        }
        clusterBuilder.hosts(seeds);

        SocketSettings socketSettings = socketBuilder.build();
        ClusterSettings clusterSettings = clusterBuilder.build();
        ConnectionPoolSettings connectionPoolSettings = connectionPoolBuilder.build();
        ServerSettings serverSettings = serverBuilder.build();
        SslSettings sslSettings = sslBuilder.build();
        MongoClientSettings settings = builder
                .applyToClusterSettings(builder1 -> builder1.applySettings(clusterSettings))
                .applyToSocketSettings(builder1 -> builder1.applySettings(socketSettings))
                .applyToConnectionPoolSettings(builder1 -> builder1.applySettings(connectionPoolSettings))
                .applyToServerSettings(builder1 -> builder1.applySettings(serverSettings))
                .applyToSslSettings(builder1 -> builder1.applySettings(sslSettings)).build();

        return MongoClients.create(settings);
    }
}

From source file:io.gravitee.am.repository.mongodb.management.ManagementRepositoryTestConfiguration.java

License:Apache License

@Bean(name = "managementMongo")
public MongoClient mongo() {
    // cluster configuration
    ClusterSettings clusterSettings = ClusterSettings.builder()
            .hosts(Collections.singletonList(new ServerAddress("localhost", 12345))).build();
    // codec configuration
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings)
            .codecRegistry(pojoCodecRegistry).writeConcern(WriteConcern.ACKNOWLEDGED).build();
    return MongoClients.create(settings);
}

From source file:io.gravitee.am.repository.mongodb.oauth2.OAuth2RepositoryTestConfiguration.java

License:Apache License

@Bean(name = "oauth2Mongo")
public MongoClient mongo() {
    // cluster configuration
    ClusterSettings clusterSettings = ClusterSettings.builder()
            .hosts(Collections.singletonList(new ServerAddress("localhost", 12346))).build();
    // codec configuration
    CodecRegistry pojoCodecRegistry = fromRegistries(MongoClients.getDefaultCodecRegistry(),
            fromProviders(PojoCodecProvider.builder().automatic(true).build()));

    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings)
            .codecRegistry(pojoCodecRegistry).writeConcern(WriteConcern.ACKNOWLEDGED).build();
    return MongoClients.create(settings);
}

From source file:org.fixtrading.timpani.securitydef.datastore.MongoDBSecurityDefinitionStore.java

License:Apache License

@Override
public CompletableFuture<SecurityDefinitionStore> open() {
    List<ServerAddress> hostList = Arrays.stream(hosts).map(h -> new ServerAddress(h))
            .collect(Collectors.toList());
    ClusterSettings clusterSettings = ClusterSettings.builder().hosts(hostList).build();
    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).build();
    mongoClient = MongoClients.create(settings);

    database = mongoClient.getDatabase(DATABASE_NAME);
    collection = database.getCollection(SECDEF_COLLECTION_NAME);

    // In the case of MongoDB, open is synchronous because it doesn't
    // actually communicate with the server until a query is invoked.
    return CompletableFuture.completedFuture(this);
}

From source file:org.jnosql.diana.mongodb.document.MongoDBDocumentConfiguration.java

License:Open Source License

private com.mongodb.async.client.MongoClient getAsyncMongoClient(List<ServerAddress> servers) {
    ClusterSettings clusterSettings = ClusterSettings.builder().hosts(servers).build();
    MongoClientSettings settings = MongoClientSettings.builder().clusterSettings(clusterSettings).build();
    return MongoClients.create(settings);
}

From source file:org.jooby.mongodb.MongoRx.java

License:Apache License

static ClusterSettings cluster(final ConnectionString cstr, final Config conf) {
    ClusterSettings.Builder cluster = ClusterSettings.builder().applyConnectionString(cstr);
    withConf("cluster", conf, c -> {
        withInt("maxWaitQueueSize", c, cluster::maxWaitQueueSize);
        withStr("replicaSetName", c, cluster::requiredReplicaSetName);
        withStr("requiredClusterType", c,
                v -> cluster.requiredClusterType(ClusterType.valueOf(v.toUpperCase())));
        withMs("serverSelectionTimeout", c, s -> cluster.serverSelectionTimeout(s, TimeUnit.MILLISECONDS));
    });//from  w  w w  .j av a2  s.  c om
    return cluster.build();
}