List of usage examples for com.mongodb MongoClientSettings builder
public static Builder builder()
From source file:com.example.App.java
License:Apache License
public static void main(String[] args) throws InterruptedException { final MongoClientSettings settings = MongoClientSettings.builder() .addCommandListener(new CommandListener() { @Override/*from w ww.java2 s .c o m*/ public void commandStarted(CommandStartedEvent event) { logger.info("command: db = {}, command = {}", event.getDatabaseName(), event.getCommandName()); } @Override public void commandSucceeded(CommandSucceededEvent event) { logger.info("command succeed: request = {}, command = {}", event.getRequestId(), event.getCommandName()); } @Override public void commandFailed(CommandFailedEvent event) { logger.info("command failed: request = {}, command = {}", event.getRequestId(), event.getCommandName()); logger.error("detail", event.getThrowable()); } }).applicationName("sample-app") .applyToConnectionPoolSettings(builder -> builder.maxSize(1).minSize(1)).build(); final MongoClient client = MongoClients.create(settings); final MongoDatabase database = client.getDatabase("sample"); final MongoCollection<Document> collection = database.getCollection("test"); final Document firstDocument = new Document("id", UUID.randomUUID()).append("name", "test user") .append("created", LocalDateTime.now()); logger.info("document to be saved: {}", firstDocument); final Mono<Document> firstMono = Mono.create(sink -> collection.insertOne(firstDocument, (result, t) -> { if (t == null) { logger.info("inserted: {}", firstDocument); sink.success(firstDocument); } else { logger.error("error", t); sink.error(t); } })); final Mono<List<Document>> secondMono = create100Users(collection, firstMono); final Mono<Long> thirdMono = secondMono.then(Mono.create(sink -> collection.countDocuments((count, t) -> { if (t == null) { logger.info("collection has {} items.", count); sink.success(count); } else { logger.error("error", t); sink.error(t); } }))); final Mono<List<Document>> fourthMono = create100Users(collection, thirdMono); final Mono<List<Document>> fifthMono = create100Users(collection, fourthMono); final Mono<List<Document>> sixthMono = create100Users(collection, fifthMono); final Mono<Document> seventhMono = sixthMono.then(Mono.create(sink -> collection.find().first((doc, t) -> { if (t == null) { logger.info("found document: {}", doc); sink.success(doc); } else { logger.error("error", t); sink.error(t); } }))); final CountDownLatch latch = new CountDownLatch(1); seventhMono.doOnTerminate(() -> { latch.countDown(); client.close(); }).subscribe(doc -> logger.info("first document: {}", doc)); latch.await(); }
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.j a v a2 s .co m // 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:org.springframework.boot.autoconfigure.mongo.ReactiveMongoClientFactory.java
License:Apache License
private Builder builder(MongoClientSettings settings) { if (settings == null) { return MongoClientSettings.builder(); }/*www.j a va2s .c o m*/ return MongoClientSettings.builder(settings); }
From source file:org.springframework.boot.autoconfigure.mongo.ReactiveMongoClientFactory.java
License:Apache License
private void customize(MongoClientSettings.Builder builder) { for (MongoClientSettingsBuilderCustomizer customizer : this.builderCustomizers) { customizer.customize(builder);// ww w .j a v a 2 s .c om } }
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// w w w .j a v a 2 s.c o m */ 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(); }
From source file:tour.ClientSideEncryptionSimpleTour.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. * Assumes the schema has already been created in MongoDB. * * @param args ignored args//w w w . java 2 s. co m */ 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"; AutoEncryptionSettings autoEncryptionSettings = AutoEncryptionSettings.builder() .keyVaultNamespace(keyVaultNamespace).kmsProviders(kmsProviders).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(); }