Example usage for com.mongodb ConnectionString ConnectionString

List of usage examples for com.mongodb ConnectionString ConnectionString

Introduction

In this page you can find the example usage for com.mongodb ConnectionString ConnectionString.

Prototype

public ConnectionString(final String connectionString) 

Source Link

Document

Creates a ConnectionString from the given string.

Usage

From source file:com.creactiviti.piper.config.MongoPersistenceConfiguration.java

License:Apache License

@Bean
ConnectionString mongoConnectionString(/*  www. j a  v  a  2 s.  co m*/
        @Value("${spring.datasource.url:mongodb://localhost:27017/piper}") URI datasourceURI) {
    return new ConnectionString(datasourceURI.toString());
}

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 {//from  w ww  .  ja va2  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:mongodb.clients.percunia.mongo.AsyncClient.java

License:Apache License

private AsyncClient() {

    logger.info("initiating connection to Mongo");

    try {/*from   w  w w .  j  av a 2 s  . c  o  m*/

        ConnectionString uri = new ConnectionString("mongodb://" + Config.USERNAME + ":" + Config.PASSWORD + "@"
                + Config.HOST + "/?authSource=" + Config.DB_NAME);
        //ConnectionString uri = new ConnectionString("mongodb://localhost");

        mongoClient = MongoClients.create(uri);
        database = mongoClient.getDatabase(Config.DB_NAME);

    } catch (Exception e) {
        logger.warn(e.toString());
    }

}

From source file:org.flinkmon.mongo.conn.ShardSetFinder.java

License:Open Source License

private List<ConnectionString> buildServerAddressList(DBObject next) {
    List<ConnectionString> hosts = new ArrayList<>();
    for (String host : Arrays.asList(((String) next.get("host")).split("/")[1].split(","))) {
        hosts.add(new ConnectionString("mongodb://" + host));
    }// w w w. ja  v a  2  s  . c  o  m
    return hosts;
}

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

License:Apache License

@SuppressWarnings({ "rawtypes", "unchecked" })
@Override/*from  w  w  w. j a  v a2 s  .  c o m*/
public void configure(final Env env, final Config conf, final Binder binder) {
    /** connection string */
    ConnectionString cstr = Try.of(() -> new ConnectionString(db))
            .getOrElse(() -> new ConnectionString(conf.getString(db)));

    log.debug("Starting {}", cstr);

    boolean first = instances.getAndIncrement() == 0;
    Function3<Class, String, Object, Void> bind = (type, name, value) -> {
        binder.bind(Key.get(type, Names.named(name))).toInstance(value);
        if (first) {
            binder.bind(Key.get(type)).toInstance(value);
        }
        return null;
    };

    /** settings */
    MongoClientSettings.Builder settings = settings(cstr, dbconf(db, conf));
    if (configurer != null) {
        configurer.accept(settings, conf);
    }
    MongoClient client = MongoClients.create(settings.build());
    bind.apply(MongoClient.class, db, client);

    /** bind database */
    Optional.ofNullable(cstr.getDatabase()).ifPresent(dbname -> {
        // observable adapter
        MongoDatabase predb = adapter.map(a -> client.getDatabase(dbname).withObservableAdapter(a))
                .orElseGet(() -> client.getDatabase(dbname));
        // codec registry
        MongoDatabase database = codecRegistry.map(predb::withCodecRegistry).orElse(predb);

        bind.apply(MongoDatabase.class, dbname, database);

        /** bind collection */
        Optional.ofNullable(cstr.getCollection()).ifPresent(cname -> {
            MongoCollection<Document> collection = database.getCollection(cname);
            bind.apply(MongoCollection.class, cname, collection);
        });
    });

    /** mapper */
    env.router().map(mapper());

    log.info("Started {}", cstr);

    env.onStop(() -> {
        log.debug("Stopping {}", cstr);
        client.close();
        log.info("Stopped {}", cstr);
    });
}

From source file:org.openo.commontosca.inventory.core.mongo.MongoInventoryProvider.java

License:Apache License

public static MongoClient create(final String url) {
    ConnectionString connectionString = new ConnectionString(url);
    Builder builder = MongoClientSettings.builder();
    builder.clusterSettings(ClusterSettings.builder().applyConnectionString(connectionString).build());
    builder.connectionPoolSettings(// w  w w  .  ja va2 s  .c  o  m
            ConnectionPoolSettings.builder().applyConnectionString(connectionString).build());
    builder.serverSettings(ServerSettings.builder().build());
    builder.credentialList(connectionString.getCredentialList());
    builder.sslSettings(SslSettings.builder().applyConnectionString(connectionString).build());
    builder.socketSettings(SocketSettings.builder().applyConnectionString(connectionString).build());
    builder.codecRegistry(
            CodecRegistries.fromRegistries(MongoClients.getDefaultCodecRegistry(), new ObjectCodecRegistry()));
    // builder.streamFactoryFactory(new NettyStreamFactoryFactory());
    return MongoClients.create(builder.build());
}

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

License:Apache License

private MongoClient createNetworkMongoClient(MongoClientSettings settings) {
    if (hasCustomAddress() || hasCustomCredentials()) {
        return createCredentialNetworkMongoClient(settings);
    }/*from   ww  w .j a  v a  2s . c o m*/
    ConnectionString connectionString = new ConnectionString(this.properties.determineUri());
    return createMongoClient(createBuilder(settings, connectionString));
}

From source file:tour.ClientSideEncryptionAutoEncryptionSettingsTour.java

License:Apache License

/**
 * Run this main method to see the output of this quick example.
 *
 * Requires the mongodb-crypt library in the class path and mongocryptd on the system path.
 *
 * @param args ignored args/*from   www. j av  a  2  s . c om*/
 */
public static void main(final String[] args) {

    // This would have to be the same master key as was used to create the encryption key
    final byte[] localMasterKey = new byte[96];
    new SecureRandom().nextBytes(localMasterKey);

    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {
        {
            put("local", new HashMap<String, Object>() {
                {
                    put("key", localMasterKey);
                }
            });
        }
    };

    String keyVaultNamespace = "admin.datakeys";
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder()
            .keyVaultMongoClientSettings(MongoClientSettings.builder()
                    .applyConnectionString(new ConnectionString("mongodb://localhost")).build())
            .keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).build();

    ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
    BsonBinary dataKeyId = clientEncryption.createDataKey("local", new DataKeyOptions());
    final String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData());

    final String dbName = "test";
    final String collName = "coll";
    AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder()
            .keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders)
            .schemaMap(new HashMap<String, BsonDocument>() {
                {
                    put(dbName + "." + collName,
                            // Need a schema that references the new data key
                            BsonDocument.parse("{" + "  properties: {" + "    encryptedField: {"
                                    + "      encrypt: {" + "        keyId: [{" + "          \"$binary\": {"
                                    + "            \"base64\": \"" + base64DataKeyId + "\","
                                    + "            \"subType\": \"04\"" + "          }" + "        }],"
                                    + "        bsonType: \"string\","
                                    + "        algorithm: \"AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic\""
                                    + "      }" + "    }" + "  }," + "  \"bsonType\": \"object\"" + "}"));
                }
            }).build();

    MongoClientSettings clientSettings = MongoClientSettings.builder()
            .autoEncryptionSettings(autoEncryptionSettings).build();

    MongoClient mongoClient = MongoClients.create(clientSettings);
    MongoCollection<Document> collection = mongoClient.getDatabase("test").getCollection("coll");
    collection.drop(); // Clear old data

    collection.insertOne(new Document("encryptedField", "123456789"));

    System.out.println(collection.find().first().toJson());

    // release resources
    mongoClient.close();
}