Search in sources :

Example 6 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class FailPoint method enable.

/**
 * @param configureFailPointDoc A document representing {@code configureFailPoint} command to be issued as is via
 * {@link com.mongodb.client.MongoDatabase#runCommand(Bson)}.
 */
public static FailPoint enable(final BsonDocument configureFailPointDoc, final ServerAddress serverAddress) {
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applyToClusterSettings(builder -> builder.mode(ClusterConnectionMode.SINGLE).hosts(Collections.singletonList(serverAddress))).build();
    MongoClient client = MongoClients.create(clientSettings);
    return enable(configureFailPointDoc, client, true);
}
Also used : ServerAddress(com.mongodb.ServerAddress) Bson(org.bson.conversions.Bson) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) ClusterConnectionMode(com.mongodb.connection.ClusterConnectionMode) MongoClientSettings(com.mongodb.MongoClientSettings) BsonString(org.bson.BsonString) Collections(java.util.Collections) BsonDocument(org.bson.BsonDocument) MongoClientSettings(com.mongodb.MongoClientSettings)

Example 7 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class InitialDnsSeedlistDiscoveryTest method shouldDiscoverSrvRecord.

@Test
public void shouldDiscoverSrvRecord() throws InterruptedException {
    assumeFalse(isServerlessTest());
    assumeFalse(isError);
    final CountDownLatch seedsLatch = new CountDownLatch(1);
    final CountDownLatch hostsLatch = new CountDownLatch(1);
    final ConnectionString connectionString = new ConnectionString(uri);
    final SslSettings sslSettings = getSslSettings(connectionString);
    assumeTrue("SSL settings don't match", getSslSettings().isEnabled() == sslSettings.isEnabled());
    MongoClientSettings settings = MongoClientSettings.builder().applyToClusterSettings(new Block<ClusterSettings.Builder>() {

        @Override
        public void apply(final ClusterSettings.Builder builder) {
            builder.applyConnectionString(connectionString).addClusterListener(new ClusterListener() {

                @Override
                public void clusterOpening(final ClusterOpeningEvent event) {
                }

                @Override
                public void clusterClosed(final ClusterClosedEvent event) {
                }

                @Override
                public void clusterDescriptionChanged(final ClusterDescriptionChangedEvent event) {
                    List<String> seedsList = event.getNewDescription().getServerDescriptions().stream().map(ServerDescription::getAddress).map(ServerAddress::toString).collect(Collectors.toList());
                    List<String> okHostsList = event.getNewDescription().getServerDescriptions().stream().filter(ServerDescription::isOk).map(ServerDescription::getAddress).map(ServerAddress::toString).collect(Collectors.toList());
                    hostsCheck(seedsList, seeds, numSeeds, seedsLatch);
                    hostsCheck(okHostsList, hosts, numHosts, hostsLatch);
                }
            });
        }

        private void hostsCheck(final List<String> actual, @Nullable final List<String> expected, @Nullable final Integer expectedSize, final CountDownLatch latch) {
            if (expected == null && expectedSize == null) {
                latch.countDown();
            } else if (expected != null && actual.size() == expected.size() && actual.containsAll(expected)) {
                latch.countDown();
            } else if (expectedSize != null && actual.size() == expectedSize) {
                latch.countDown();
            }
        }
    }).applyToSslSettings(new Block<SslSettings.Builder>() {

        @Override
        public void apply(final SslSettings.Builder builder) {
            builder.applySettings(sslSettings);
            builder.invalidHostNameAllowed(true);
        }
    }).build();
    try (MongoClient client = createMongoClient(settings)) {
        assertTrue(seedsLatch.await(ClusterFixture.TIMEOUT, TimeUnit.SECONDS));
        assertTrue(hostsLatch.await(ClusterFixture.TIMEOUT, TimeUnit.SECONDS));
        assertTrue(client.getDatabase("admin").runCommand(new Document("ping", 1)).containsKey("ok"));
    }
}
Also used : ClusterSettings(com.mongodb.connection.ClusterSettings) ServerDescription(com.mongodb.connection.ServerDescription) MongoClientSettings(com.mongodb.MongoClientSettings) ConnectionString(com.mongodb.ConnectionString) CountDownLatch(java.util.concurrent.CountDownLatch) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) ClusterFixture.getSslSettings(com.mongodb.ClusterFixture.getSslSettings) SslSettings(com.mongodb.connection.SslSettings) ClusterClosedEvent(com.mongodb.event.ClusterClosedEvent) ClusterDescriptionChangedEvent(com.mongodb.event.ClusterDescriptionChangedEvent) ClusterListener(com.mongodb.event.ClusterListener) Block(com.mongodb.Block) ConnectionString(com.mongodb.ConnectionString) ClusterOpeningEvent(com.mongodb.event.ClusterOpeningEvent) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 8 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class ClientSideEncryptionCorpusTest method setUp.

@Before
public void setUp() throws IOException, URISyntaxException {
    assumeTrue(serverVersionAtLeast(4, 2));
    assumeTrue("Corpus tests disabled", hasEncryptionTestsEnabled());
    MongoClientSettings clientSettings = getMongoClientBuilderFromConnectionString().codecRegistry(fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClientSettings.getDefaultCodecRegistry())).build();
    // Step 1: create unencrypted client
    client = MongoClients.create(clientSettings);
    MongoDatabase db = client.getDatabase("db");
    // Step 2: Drop and recreate db.coll with schema
    BsonDocument schemaDocument = bsonDocumentFromPath("corpus-schema.json");
    Mono.from(db.getCollection("coll").drop()).block(TIMEOUT_DURATION);
    Mono.from(db.runCommand(new BsonDocument("create", new BsonString("coll")).append("validator", new BsonDocument("$jsonSchema", schemaDocument)))).block(TIMEOUT_DURATION);
    // Step 3: Drop and create keyvault.datakeys
    MongoDatabase keyVaultDatabase = client.getDatabase("keyvault");
    MongoCollection<BsonDocument> dataKeysCollection = keyVaultDatabase.getCollection("datakeys", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
    Mono.from(dataKeysCollection.drop()).block(TIMEOUT_DURATION);
    Mono.from(dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-aws.json"))).block(TIMEOUT_DURATION);
    Mono.from(dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-azure.json"))).block(TIMEOUT_DURATION);
    Mono.from(dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-gcp.json"))).block(TIMEOUT_DURATION);
    Mono.from(dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-kmip.json"))).block(TIMEOUT_DURATION);
    Mono.from(dataKeysCollection.insertOne(bsonDocumentFromPath("corpus-key-local.json"))).block(TIMEOUT_DURATION);
    // Step 4: Configure our objects
    Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>() {

        {
            put("aws", new HashMap<String, Object>() {

                {
                    put("accessKeyId", System.getProperty("org.mongodb.test.awsAccessKeyId"));
                    put("secretAccessKey", System.getProperty("org.mongodb.test.awsSecretAccessKey"));
                }
            });
            put("azure", new HashMap<String, Object>() {

                {
                    put("tenantId", System.getProperty("org.mongodb.test.azureTenantId"));
                    put("clientId", System.getProperty("org.mongodb.test.azureClientId"));
                    put("clientSecret", System.getProperty("org.mongodb.test.azureClientSecret"));
                }
            });
            put("gcp", new HashMap<String, Object>() {

                {
                    put("email", System.getProperty("org.mongodb.test.gcpEmail"));
                    put("privateKey", System.getProperty("org.mongodb.test.gcpPrivateKey"));
                }
            });
            put("kmip", new HashMap<String, Object>() {

                {
                    put("endpoint", System.getProperty("org.mongodb.test.kmipEndpoint", "localhost:5698"));
                }
            });
            put("local", new HashMap<String, Object>() {

                {
                    put("key", "Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM" + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
                }
            });
        }
    };
    HashMap<String, BsonDocument> schemaMap = new HashMap<>();
    schemaMap.put("db.coll", schemaDocument);
    AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders);
    if (useLocalSchema) {
        autoEncryptionSettingsBuilder.schemaMap(schemaMap);
    }
    clientSettings = getMongoClientBuilderFromConnectionString().codecRegistry(fromRegistries(fromCodecs(new UuidCodec(UuidRepresentation.STANDARD)), MongoClientSettings.getDefaultCodecRegistry())).autoEncryptionSettings(autoEncryptionSettingsBuilder.build()).build();
    autoEncryptingClient = MongoClients.create(clientSettings);
    ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(getMongoClientSettings()).kmsProviders(kmsProviders).keyVaultNamespace("keyvault.datakeys").build();
    clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
}
Also used : UuidCodec(org.bson.codecs.UuidCodec) HashMap(java.util.HashMap) Fixture.getMongoClientSettings(com.mongodb.reactivestreams.client.Fixture.getMongoClientSettings) MongoClientSettings(com.mongodb.MongoClientSettings) BsonString(org.bson.BsonString) Fixture.getMongoClientBuilderFromConnectionString(com.mongodb.reactivestreams.client.Fixture.getMongoClientBuilderFromConnectionString) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) HashMap(java.util.HashMap) Map(java.util.Map) Before(org.junit.Before)

Example 9 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class ClientSideEncryptionExternalKeyVaultTest method setUp.

@Before
public void setUp() throws Throwable {
    assumeTrue(serverVersionAtLeast(4, 2));
    assumeTrue("Encryption test with external keyVault is disabled", isClientSideEncryptionTest());
    /* Step 1: get unencrypted client and recreate keys collection */
    MongoClient client = getMongoClient();
    MongoDatabase keyvaultDatabase = client.getDatabase("keyvault");
    MongoCollection<BsonDocument> datakeys = keyvaultDatabase.getCollection("datakeys", BsonDocument.class).withWriteConcern(WriteConcern.MAJORITY);
    Mono.from(datakeys.drop()).block(TIMEOUT_DURATION);
    Mono.from(datakeys.insertOne(bsonDocumentFromPath("external-key.json"))).block(TIMEOUT_DURATION);
    /* Step 2: create encryption objects. */
    Map<String, Map<String, Object>> kmsProviders = new HashMap<>();
    Map<String, Object> localMasterkey = new HashMap<>();
    Map<String, BsonDocument> schemaMap = new HashMap<>();
    byte[] localMasterkeyBytes = Base64.getDecoder().decode("Mng0NCt4ZHVUYUJCa1kxNkVyNUR1QURhZ2h2UzR2d2RrZzh0cFBwM3R6NmdWMDFBM" + "UN3YkQ5aXRRMkhGRGdQV09wOGVNYUMxT2k3NjZKelhaQmRCZGJkTXVyZG9uSjFk");
    localMasterkey.put("key", localMasterkeyBytes);
    kmsProviders.put("local", localMasterkey);
    schemaMap.put("db.coll", bsonDocumentFromPath("external-schema.json"));
    AutoEncryptionSettings.Builder autoEncryptionSettingsBuilder = AutoEncryptionSettings.builder().keyVaultNamespace("keyvault.datakeys").kmsProviders(kmsProviders).schemaMap(schemaMap);
    MongoClientSettings externalClientSettings = null;
    if (withExternalKeyVault) {
        externalClientSettings = getMongoClientBuilderFromConnectionString().credential(MongoCredential.createCredential("fake-user", "admin", "fake-pwd".toCharArray())).build();
        autoEncryptionSettingsBuilder.keyVaultMongoClientSettings(externalClientSettings);
    }
    AutoEncryptionSettings autoEncryptionSettings = autoEncryptionSettingsBuilder.build();
    MongoClientSettings clientSettings = getMongoClientBuilderFromConnectionString().autoEncryptionSettings(autoEncryptionSettings).build();
    clientEncrypted = MongoClients.create(clientSettings);
    ClientEncryptionSettings.Builder clientEncryptionSettingsBuilder = ClientEncryptionSettings.builder().keyVaultMongoClientSettings(getMongoClientBuilderFromConnectionString().build()).kmsProviders(kmsProviders).keyVaultNamespace("keyvault.datakeys");
    if (withExternalKeyVault) {
        clientEncryptionSettingsBuilder.keyVaultMongoClientSettings(externalClientSettings);
    }
    ClientEncryptionSettings clientEncryptionSettings = clientEncryptionSettingsBuilder.build();
    clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
}
Also used : HashMap(java.util.HashMap) BsonString(org.bson.BsonString) Fixture.getMongoClientBuilderFromConnectionString(com.mongodb.reactivestreams.client.Fixture.getMongoClientBuilderFromConnectionString) MongoClientSettings(com.mongodb.MongoClientSettings) Fixture.getMongoClient(com.mongodb.reactivestreams.client.Fixture.getMongoClient) ClientEncryptionSettings(com.mongodb.ClientEncryptionSettings) BsonDocument(org.bson.BsonDocument) AutoEncryptionSettings(com.mongodb.AutoEncryptionSettings) HashMap(java.util.HashMap) Map(java.util.Map) Before(org.junit.Before)

Example 10 with MongoClientSettings

use of com.mongodb.MongoClientSettings in project mongo-java-driver by mongodb.

the class BatchCursorFluxTest method setUp.

@BeforeEach
public void setUp() {
    commandListener = new TestCommandListener(singletonList("commandStartedEvent"), asList("insert", "killCursors"));
    MongoClientSettings mongoClientSettings = getMongoClientBuilderFromConnectionString().addCommandListener(commandListener).build();
    client = MongoClients.create(mongoClientSettings);
    collection = client.getDatabase(getDefaultDatabaseName()).getCollection(getClass().getName());
    drop(collection.getNamespace());
}
Also used : TestCommandListener(com.mongodb.internal.connection.TestCommandListener) MongoClientSettings(com.mongodb.MongoClientSettings) BeforeEach(org.junit.jupiter.api.BeforeEach)

Aggregations

MongoClientSettings (com.mongodb.MongoClientSettings)75 Test (org.junit.jupiter.api.Test)24 BsonString (org.bson.BsonString)21 Map (java.util.Map)20 Test (org.junit.Test)20 HashMap (java.util.HashMap)19 Document (org.bson.Document)19 BsonDocument (org.bson.BsonDocument)18 ServerAddress (com.mongodb.ServerAddress)17 AutoEncryptionSettings (com.mongodb.AutoEncryptionSettings)14 Before (org.junit.Before)14 MongoNamespace (com.mongodb.MongoNamespace)13 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)12 ConnectionString (com.mongodb.ConnectionString)12 MongoClientFactoryBean (org.springframework.data.mongodb.core.MongoClientFactoryBean)10 Block (com.mongodb.Block)8 Fixture.getMongoClientSettingsBuilder (com.mongodb.client.Fixture.getMongoClientSettingsBuilder)8 SecureRandom (java.security.SecureRandom)8 TimeUnit (java.util.concurrent.TimeUnit)8 ClusterFixture.isServerlessTest (com.mongodb.ClusterFixture.isServerlessTest)7