Search in sources :

Example 31 with MongoClient

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

the class Entities method initClient.

private void initClient(final BsonDocument entity, final String id, final Function<MongoClientSettings, MongoClient> mongoClientSupplier, final boolean waitForPoolAsyncWorkManagerStart) {
    if (!SUPPORTED_CLIENT_ENTITY_OPTIONS.containsAll(entity.keySet())) {
        throw new UnsupportedOperationException("Client entity contains unsupported options: " + entity.keySet() + ". Supported options are " + SUPPORTED_CLIENT_ENTITY_OPTIONS);
    }
    MongoClientSettings.Builder clientSettingsBuilder;
    if (entity.getBoolean("useMultipleMongoses", BsonBoolean.FALSE).getValue() && (isSharded() || isLoadBalanced())) {
        assumeTrue("Multiple mongos connection string not available for sharded cluster", !isSharded() || getMultiMongosConnectionString() != null);
        assumeTrue("Multiple mongos connection string not available for load-balanced cluster", !isLoadBalanced() || getMultiMongosConnectionString() != null);
        clientSettingsBuilder = getMultiMongosMongoClientSettingsBuilder();
    } else {
        clientSettingsBuilder = getMongoClientSettingsBuilder();
    }
    if (entity.containsKey("observeEvents")) {
        List<String> ignoreCommandMonitoringEvents = entity.getArray("ignoreCommandMonitoringEvents", new BsonArray()).stream().map(type -> type.asString().getValue()).collect(Collectors.toList());
        ignoreCommandMonitoringEvents.add("configureFailPoint");
        TestCommandListener testCommandListener = new TestCommandListener(entity.getArray("observeEvents").stream().map(type -> type.asString().getValue()).collect(Collectors.toList()), ignoreCommandMonitoringEvents, entity.getBoolean("observeSensitiveCommands", BsonBoolean.FALSE).getValue());
        clientSettingsBuilder.addCommandListener(testCommandListener);
        putEntity(id + "-command-listener", testCommandListener, clientCommandListeners);
        TestConnectionPoolListener testConnectionPoolListener = new TestConnectionPoolListener(entity.getArray("observeEvents").stream().map(type -> type.asString().getValue()).collect(Collectors.toList()));
        clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(testConnectionPoolListener));
        putEntity(id + "-connection-pool-listener", testConnectionPoolListener, clientConnectionPoolListeners);
    } else {
        // Regardless of whether events are observed, we still need to track some info about the pool in order to implement
        // the assertNumberConnectionsCheckedOut operation
        TestConnectionPoolListener testConnectionPoolListener = new TestConnectionPoolListener();
        clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(testConnectionPoolListener));
        putEntity(id + "-connection-pool-listener", testConnectionPoolListener, clientConnectionPoolListeners);
    }
    if (entity.containsKey("storeEventsAsEntities")) {
        BsonArray storeEventsAsEntitiesArray = entity.getArray("storeEventsAsEntities");
        for (BsonValue eventValue : storeEventsAsEntitiesArray) {
            BsonDocument eventDocument = eventValue.asDocument();
            String key = eventDocument.getString("id").getValue();
            BsonArray eventList = eventDocument.getArray("events");
            List<BsonDocument> eventDocumentList = synchronizedList(new ArrayList<>());
            putEntity(key, eventDocumentList, eventsMap);
            if (eventList.stream().map(value -> value.asString().getValue()).anyMatch(value -> value.startsWith("Command"))) {
                clientSettingsBuilder.addCommandListener(new EntityCommandListener(eventList.stream().map(value -> value.asString().getValue()).collect(Collectors.toSet()), eventDocumentList));
            }
            if (eventList.stream().map(value -> value.asString().getValue()).anyMatch(value -> value.startsWith("Pool") || value.startsWith("Connection"))) {
                clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.addConnectionPoolListener(new EntityConnectionPoolListener(eventList.stream().map(value -> value.asString().getValue()).collect(Collectors.toSet()), eventDocumentList)));
            }
        }
    }
    clientSettingsBuilder.applyToServerSettings(builder -> {
        builder.heartbeatFrequency(50, TimeUnit.MILLISECONDS);
        builder.minHeartbeatFrequency(50, TimeUnit.MILLISECONDS);
    });
    if (entity.containsKey("uriOptions")) {
        entity.getDocument("uriOptions").forEach((key, value) -> {
            switch(key) {
                case "retryReads":
                    clientSettingsBuilder.retryReads(value.asBoolean().getValue());
                    break;
                case "retryWrites":
                    clientSettingsBuilder.retryWrites(value.asBoolean().getValue());
                    break;
                case "readConcernLevel":
                    clientSettingsBuilder.readConcern(new ReadConcern(ReadConcernLevel.fromString(value.asString().getValue())));
                    break;
                case "w":
                    clientSettingsBuilder.writeConcern(new WriteConcern(value.asInt32().intValue()));
                    break;
                case "maxPoolSize":
                    clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.maxSize(value.asNumber().intValue()));
                    break;
                case "waitQueueTimeoutMS":
                    clientSettingsBuilder.applyToConnectionPoolSettings(builder -> builder.maxWaitTime(value.asNumber().longValue(), TimeUnit.MILLISECONDS));
                    break;
                case "loadBalanced":
                    if (value.asBoolean().getValue()) {
                        clientSettingsBuilder.applyToClusterSettings(builder -> builder.mode(ClusterConnectionMode.LOAD_BALANCED));
                    }
                    break;
                case "appname":
                    clientSettingsBuilder.applicationName(value.asString().getValue());
                    break;
                default:
                    throw new UnsupportedOperationException("Unsupported uri option: " + key);
            }
        });
    }
    if (entity.containsKey("serverApi")) {
        BsonDocument serverApiDocument = entity.getDocument("serverApi");
        String apiVersion = serverApiDocument.getString("version").getValue();
        ServerApi.Builder serverApiBuilder = ServerApi.builder().version(ServerApiVersion.findByValue(apiVersion));
        if (serverApiDocument.containsKey("deprecationErrors")) {
            serverApiBuilder.deprecationErrors(serverApiDocument.getBoolean("deprecationErrors").getValue());
        }
        if (serverApiDocument.containsKey("strict")) {
            serverApiBuilder.strict(serverApiDocument.getBoolean("strict").getValue());
        }
        clientSettingsBuilder.serverApi(serverApiBuilder.build());
    }
    putEntity(id, mongoClientSupplier.apply(clientSettingsBuilder.build()), clients);
    if (waitForPoolAsyncWorkManagerStart) {
        waitForPoolAsyncWorkManagerStart();
    }
}
Also used : GridFSBucket(com.mongodb.client.gridfs.GridFSBucket) MongoDatabase(com.mongodb.client.MongoDatabase) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) ConnectionPoolCreatedEvent(com.mongodb.event.ConnectionPoolCreatedEvent) BsonValue(org.bson.BsonValue) CommandListener(com.mongodb.event.CommandListener) ClusterFixture.isSharded(com.mongodb.ClusterFixture.isSharded) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Arrays.asList(java.util.Arrays.asList) CommandSucceededEvent(com.mongodb.event.CommandSucceededEvent) BsonArray(org.bson.BsonArray) Map(java.util.Map) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) ReadConcern(com.mongodb.ReadConcern) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) CommandEvent(com.mongodb.event.CommandEvent) UnifiedCrudHelper.asReadPreference(com.mongodb.client.unified.UnifiedCrudHelper.asReadPreference) Collections.synchronizedList(java.util.Collections.synchronizedList) Set(java.util.Set) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Collectors(java.util.stream.Collectors) List(java.util.List) EventMatcher.getReasonString(com.mongodb.client.unified.EventMatcher.getReasonString) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) NotNull(org.jetbrains.annotations.NotNull) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) ConnectionCheckedInEvent(com.mongodb.event.ConnectionCheckedInEvent) MongoClient(com.mongodb.client.MongoClient) MongoCollection(com.mongodb.client.MongoCollection) ServerApi(com.mongodb.ServerApi) ClusterFixture.isLoadBalanced(com.mongodb.ClusterFixture.isLoadBalanced) BsonBoolean(org.bson.BsonBoolean) HashMap(java.util.HashMap) AbstractConnectionPoolTest.waitForPoolAsyncWorkManagerStart(com.mongodb.internal.connection.AbstractConnectionPoolTest.waitForPoolAsyncWorkManagerStart) BsonString(org.bson.BsonString) Function(java.util.function.Function) Fixture.getMultiMongosMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMultiMongosMongoClientSettingsBuilder) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) TransactionOptions(com.mongodb.TransactionOptions) HashSet(java.util.HashSet) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) MongoCursor(com.mongodb.client.MongoCursor) ClusterConnectionMode(com.mongodb.connection.ClusterConnectionMode) BsonInt64(org.bson.BsonInt64) ConnectionCreatedEvent(com.mongodb.event.ConnectionCreatedEvent) ConnectionReadyEvent(com.mongodb.event.ConnectionReadyEvent) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) ServerApiVersion(com.mongodb.ServerApiVersion) ServerId(com.mongodb.connection.ServerId) UnifiedCrudHelper.asReadConcern(com.mongodb.client.unified.UnifiedCrudHelper.asReadConcern) BsonDouble(org.bson.BsonDouble) CommandFailedEvent(com.mongodb.event.CommandFailedEvent) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolClosedEvent(com.mongodb.event.ConnectionPoolClosedEvent) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ClientSessionOptions(com.mongodb.ClientSessionOptions) ReadConcernLevel(com.mongodb.ReadConcernLevel) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent) UnifiedCrudHelper.asWriteConcern(com.mongodb.client.unified.UnifiedCrudHelper.asWriteConcern) ClientSession(com.mongodb.client.ClientSession) BsonInt32(org.bson.BsonInt32) WriteConcern(com.mongodb.WriteConcern) ConnectionId(com.mongodb.connection.ConnectionId) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) CommandStartedEvent(com.mongodb.event.CommandStartedEvent) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) MongoClientSettings(com.mongodb.MongoClientSettings) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) EventMatcher.getReasonString(com.mongodb.client.unified.EventMatcher.getReasonString) BsonString(org.bson.BsonString) ReadConcern(com.mongodb.ReadConcern) UnifiedCrudHelper.asReadConcern(com.mongodb.client.unified.UnifiedCrudHelper.asReadConcern) BsonDocument(org.bson.BsonDocument) UnifiedCrudHelper.asWriteConcern(com.mongodb.client.unified.UnifiedCrudHelper.asWriteConcern) WriteConcern(com.mongodb.WriteConcern) BsonArray(org.bson.BsonArray) ServerApi(com.mongodb.ServerApi) BsonValue(org.bson.BsonValue)

Example 32 with MongoClient

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

the class Entities method initSession.

private void initSession(final BsonDocument entity, final String id) {
    MongoClient client = clients.get(entity.getString("client").getValue());
    ClientSessionOptions.Builder optionsBuilder = ClientSessionOptions.builder();
    if (entity.containsKey("sessionOptions")) {
        for (Map.Entry<String, BsonValue> entry : entity.getDocument("sessionOptions").entrySet()) {
            switch(entry.getKey()) {
                case "defaultTransactionOptions":
                    optionsBuilder.defaultTransactionOptions(getTransactionOptions(entry.getValue().asDocument()));
                    break;
                case "snapshot":
                    optionsBuilder.snapshot(entry.getValue().asBoolean().getValue());
                    break;
                default:
                    throw new UnsupportedOperationException("Unsupported session option: " + entry.getKey());
            }
        }
    }
    ClientSession session = client.startSession(optionsBuilder.build());
    putEntity(id, session, sessions);
    putEntity(id + "-identifier", session.getServerSession().getIdentifier(), sessionIdentifiers);
}
Also used : MongoClient(com.mongodb.client.MongoClient) ClientSession(com.mongodb.client.ClientSession) ClusterFixture.getMultiMongosConnectionString(com.mongodb.ClusterFixture.getMultiMongosConnectionString) EventMatcher.getReasonString(com.mongodb.client.unified.EventMatcher.getReasonString) BsonString(org.bson.BsonString) ClientSessionOptions(com.mongodb.ClientSessionOptions) Map(java.util.Map) HashMap(java.util.HashMap) BsonValue(org.bson.BsonValue)

Example 33 with MongoClient

use of com.mongodb.client.MongoClient in project spring-data-mongodb by spring-projects.

the class MongoDbFactoryParserIntegrationTests method testWriteConcern.

// DATAMONGO-2199
@Test
public void testWriteConcern() throws Exception {
    try (MongoClient client = MongoTestUtils.client()) {
        SimpleMongoClientDatabaseFactory dbFactory = new SimpleMongoClientDatabaseFactory(client, "database");
        dbFactory.setWriteConcern(WriteConcern.ACKNOWLEDGED);
        dbFactory.getMongoDatabase();
        assertThat(ReflectionTestUtils.getField(dbFactory, "writeConcern")).isEqualTo(WriteConcern.ACKNOWLEDGED);
    }
}
Also used : MongoClient(com.mongodb.client.MongoClient) SimpleMongoClientDatabaseFactory(org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory) Test(org.junit.jupiter.api.Test)

Example 34 with MongoClient

use of com.mongodb.client.MongoClient in project spring-data-mongodb by spring-projects.

the class MongoNamespaceTests method testThirdMongoDbFactory.

// DATAMONGO-789
@Test
public void testThirdMongoDbFactory() {
    assertThat(ctx.containsBean("thirdMongoDbFactory")).isTrue();
    MongoDatabaseFactory dbf = (MongoDatabaseFactory) ctx.getBean("thirdMongoDbFactory");
    MongoClient mongo = (MongoClient) getField(dbf, "mongoClient");
    assertThat(mongo.getClusterDescription().getClusterSettings().getHosts()).containsExactly(new ServerAddress());
    assertThat(getField(dbf, "databaseName")).isEqualTo("database");
}
Also used : MongoClient(com.mongodb.client.MongoClient) MongoDatabaseFactory(org.springframework.data.mongodb.MongoDatabaseFactory) ServerAddress(com.mongodb.ServerAddress) Test(org.junit.Test)

Example 35 with MongoClient

use of com.mongodb.client.MongoClient in project spring-data-mongodb by spring-projects.

the class MongoPersistentEntityIndexCreatorIntegrationTests method createIndexShouldThrowMeaningfulExceptionWhenIndexCreationFails.

// DATAMONGO-1125
@Test
public void createIndexShouldThrowMeaningfulExceptionWhenIndexCreationFails() {
    expectedException.expect(DataIntegrityViolationException.class);
    expectedException.expectMessage("collection 'datamongo-1125'");
    expectedException.expectMessage("dalinar.kohlin");
    expectedException.expectMessage("lastname");
    expectedException.expectCause(IsInstanceOf.<Throwable>instanceOf(MongoCommandException.class));
    try (MongoClient client = MongoTestUtils.client()) {
        MongoTemplate mongoTemplate = new MongoTemplate(client, "issue");
        MongoPersistentEntityIndexCreator indexCreator = new MongoPersistentEntityIndexCreator(new MongoMappingContext(), mongoTemplate);
        indexCreator.createIndex(new IndexDefinitionHolder("dalinar.kohlin", new Index().named("stormlight").on("lastname", Direction.ASC).unique(), "datamongo-1125"));
        indexCreator.createIndex(new IndexDefinitionHolder("dalinar.kohlin", new Index().named("stormlight").on("lastname", Direction.ASC).sparse(), "datamongo-1125"));
    }
}
Also used : MongoClient(com.mongodb.client.MongoClient) MongoCommandException(com.mongodb.MongoCommandException) IndexDefinitionHolder(org.springframework.data.mongodb.core.index.MongoPersistentEntityIndexResolver.IndexDefinitionHolder) MongoMappingContext(org.springframework.data.mongodb.core.mapping.MongoMappingContext) MongoTemplate(org.springframework.data.mongodb.core.MongoTemplate) Test(org.junit.Test)

Aggregations

MongoClient (com.mongodb.client.MongoClient)45 Document (org.bson.Document)22 MongoDatabase (com.mongodb.client.MongoDatabase)19 Test (org.junit.Test)10 Map (java.util.Map)9 MongoClientSettings (com.mongodb.MongoClientSettings)8 ServerAddress (com.mongodb.ServerAddress)8 HashMap (java.util.HashMap)7 ConnectionString (com.mongodb.ConnectionString)6 BsonDocument (org.bson.BsonDocument)6 BsonString (org.bson.BsonString)6 Test (org.junit.jupiter.api.Test)6 List (java.util.List)5 SecureRandom (java.security.SecureRandom)4 Set (java.util.Set)4 TimeUnit (java.util.concurrent.TimeUnit)4 BsonValue (org.bson.BsonValue)4 ClientEncryptionSettings (com.mongodb.ClientEncryptionSettings)3 ClientSessionOptions (com.mongodb.ClientSessionOptions)3 ClusterFixture.getMultiMongosConnectionString (com.mongodb.ClusterFixture.getMultiMongosConnectionString)3