Search in sources :

Example 96 with BsonInt32

use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.

the class RetryableWritesProseTest method poolClearedExceptionMustBeRetryable.

@SuppressWarnings("try")
public static <R> void poolClearedExceptionMustBeRetryable(final Function<MongoClientSettings, MongoClient> clientCreator, final Function<MongoCollection<Document>, R> operation, final String operationName, final boolean write) throws InterruptedException, ExecutionException, TimeoutException {
    assumeTrue(serverVersionAtLeast(4, 3) && !(write && isStandalone()));
    assumeFalse(isServerlessTest());
    TestConnectionPoolListener connectionPoolListener = new TestConnectionPoolListener(asList("connectionCheckedOutEvent", "poolClearedEvent", "connectionCheckOutFailedEvent"));
    TestCommandListener commandListener = new TestCommandListener(singletonList("commandStartedEvent"), asList("configureFailPoint", "drop"));
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applyToConnectionPoolSettings(builder -> builder.maxSize(1).addConnectionPoolListener(connectionPoolListener)).applyToServerSettings(builder -> builder.minHeartbeatFrequency(50, TimeUnit.MILLISECONDS).heartbeatFrequency(50, TimeUnit.MILLISECONDS)).retryReads(true).retryWrites(true).addCommandListener(commandListener).build();
    BsonDocument configureFailPoint = new BsonDocument().append("configureFailPoint", new BsonString("failCommand")).append("mode", new BsonDocument().append("times", new BsonInt32(1))).append("data", new BsonDocument().append("failCommands", new BsonArray(singletonList(new BsonString(operationName)))).append("errorCode", new BsonInt32(91)).append("errorLabels", write ? new BsonArray(singletonList(new BsonString("RetryableWriteError"))) : new BsonArray()).append("blockConnection", BsonBoolean.valueOf(true)).append("blockTimeMS", new BsonInt32(1000)));
    int timeoutSeconds = 5;
    try (MongoClient client = clientCreator.apply(clientSettings);
        FailPoint ignored = FailPoint.enable(configureFailPoint, client)) {
        MongoCollection<Document> collection = client.getDatabase(getDefaultDatabaseName()).getCollection("poolClearedExceptionMustBeRetryable");
        collection.drop();
        ExecutorService ex = Executors.newFixedThreadPool(2);
        try {
            Future<R> result1 = ex.submit(() -> operation.apply(collection));
            Future<R> result2 = ex.submit(() -> operation.apply(collection));
            connectionPoolListener.waitForEvent(ConnectionCheckedOutEvent.class, 1, timeoutSeconds, SECONDS);
            connectionPoolListener.waitForEvent(ConnectionPoolClearedEvent.class, 1, timeoutSeconds, SECONDS);
            connectionPoolListener.waitForEvent(ConnectionCheckOutFailedEvent.class, 1, timeoutSeconds, SECONDS);
            result1.get(timeoutSeconds, SECONDS);
            result2.get(timeoutSeconds, SECONDS);
        } finally {
            ex.shutdownNow();
        }
        assertEquals(3, commandListener.getCommandStartedEvents().size());
        commandListener.getCommandStartedEvents().forEach(event -> assertEquals(operationName, event.getCommandName()));
    }
}
Also used : Document(org.bson.Document) Fixture.getDefaultDatabaseName(com.mongodb.client.Fixture.getDefaultDatabaseName) ClusterFixture.isDiscoverableReplicaSet(com.mongodb.ClusterFixture.isDiscoverableReplicaSet) MongoClientException(com.mongodb.MongoClientException) BsonBoolean(org.bson.BsonBoolean) Assume.assumeFalse(org.junit.Assume.assumeFalse) TimeoutException(java.util.concurrent.TimeoutException) Function(com.mongodb.Function) BsonString(org.bson.BsonString) BsonDocument(org.bson.BsonDocument) Collections.singletonList(java.util.Collections.singletonList) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) Future(java.util.concurrent.Future) ClusterFixture.isSharded(com.mongodb.ClusterFixture.isSharded) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Arrays.asList(java.util.Arrays.asList) BsonArray(org.bson.BsonArray) ClusterFixture.isStandalone(com.mongodb.ClusterFixture.isStandalone) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) MongoException(com.mongodb.MongoException) ClusterFixture.serverVersionLessThan(com.mongodb.ClusterFixture.serverVersionLessThan) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Executors(java.util.concurrent.Executors) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) ClusterFixture.getServerStatus(com.mongodb.ClusterFixture.getServerStatus) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) BsonInt32(org.bson.BsonInt32) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) TestConnectionPoolListener(com.mongodb.internal.connection.TestConnectionPoolListener) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) MongoClientSettings(com.mongodb.MongoClientSettings) Document(org.bson.Document) BsonDocument(org.bson.BsonDocument) BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) ExecutorService(java.util.concurrent.ExecutorService)

Example 97 with BsonInt32

use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.

the class ServerDiscoveryAndMonitoringProseTests method monitorsSleepAtLeastMinHeartbeatFreqencyMSBetweenChecks.

/**
 * See
 * <a href="https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring-tests.rst#monitors-sleep-at-least-minheartbeatfreqencyms-between-checks">
 * Monitors sleep at least minHeartbeatFreqencyMS between checks</a>.
 */
@Test
@SuppressWarnings("try")
public void monitorsSleepAtLeastMinHeartbeatFreqencyMSBetweenChecks() {
    assumeTrue(serverVersionAtLeast(4, 3));
    assumeFalse(isServerlessTest());
    long defaultMinHeartbeatIntervalMillis = MongoClientSettings.builder().build().getServerSettings().getMinHeartbeatFrequency(MILLISECONDS);
    assertEquals(500, defaultMinHeartbeatIntervalMillis);
    String appName = "SDAMMinHeartbeatFrequencyTest";
    MongoClientSettings clientSettings = getMongoClientSettingsBuilder().applicationName(appName).applyToClusterSettings(ClusterFixture::setDirectConnection).applyToClusterSettings(builder -> builder.serverSelectionTimeout(5000, MILLISECONDS)).applyToServerSettings(builder -> builder.minHeartbeatFrequency(defaultMinHeartbeatIntervalMillis, MILLISECONDS)).build();
    BsonDocument configureFailPoint = new BsonDocument().append("configureFailPoint", new BsonString("failCommand")).append("mode", new BsonDocument().append("times", new BsonInt32(5))).append("data", new BsonDocument().append("failCommands", new BsonArray(asList(new BsonString("hello"), new BsonString("isMaster")))).append("errorCode", new BsonInt32(1234)).append("appName", new BsonString(appName)));
    try (FailPoint ignored = FailPoint.enable(configureFailPoint, clientSettings.getClusterSettings().getHosts().get(0));
        MongoClient client = MongoClients.create(clientSettings)) {
        long startNanos = System.nanoTime();
        client.getDatabase(getDefaultDatabaseName()).runCommand(new BsonDocument("ping", BsonNull.VALUE));
        long durationMillis = NANOSECONDS.toMillis(System.nanoTime() - startNanos);
        String msg = durationMillis + " ms";
        assertTrue(msg, durationMillis >= 2000);
        assertTrue(msg, durationMillis <= 3500);
    }
}
Also used : Document(org.bson.Document) ServerListener(com.mongodb.event.ServerListener) Fixture.getMongoClientSettingsBuilder(com.mongodb.client.Fixture.getMongoClientSettingsBuilder) Collections.singleton(java.util.Collections.singleton) Arrays.asList(java.util.Arrays.asList) BsonArray(org.bson.BsonArray) ClusterFixture.isStandalone(com.mongodb.ClusterFixture.isStandalone) Assert.fail(org.junit.Assert.fail) ServerDescriptionChangedEvent(com.mongodb.event.ServerDescriptionChangedEvent) ServerHeartbeatSucceededEvent(com.mongodb.event.ServerHeartbeatSucceededEvent) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) BsonNull(org.bson.BsonNull) Collections.synchronizedList(java.util.Collections.synchronizedList) Set(java.util.Set) BlockingQueue(java.util.concurrent.BlockingQueue) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) String.format(java.lang.String.format) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) Block(com.mongodb.Block) Assert.assertFalse(org.junit.Assert.assertFalse) Optional(java.util.Optional) ClusterFixture.configureFailPoint(com.mongodb.ClusterFixture.configureFailPoint) Assume.assumeTrue(org.junit.Assume.assumeTrue) MongoClientSettings(com.mongodb.MongoClientSettings) Fixture.getDefaultDatabaseName(com.mongodb.client.Fixture.getDefaultDatabaseName) BsonDocument.parse(org.bson.BsonDocument.parse) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) Assume.assumeFalse(org.junit.Assume.assumeFalse) BsonString(org.bson.BsonString) ServerSettings(com.mongodb.connection.ServerSettings) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterFixture(com.mongodb.ClusterFixture) ServerHeartbeatFailedEvent(com.mongodb.event.ServerHeartbeatFailedEvent) Logger(com.mongodb.diagnostics.logging.Logger) MongoInterruptedException(com.mongodb.MongoInterruptedException) ConnectionPoolListener(com.mongodb.event.ConnectionPoolListener) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Timeout(com.mongodb.internal.Timeout) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ServerMonitorListener(com.mongodb.event.ServerMonitorListener) Ignore(org.junit.Ignore) Loggers(com.mongodb.diagnostics.logging.Loggers) ClusterFixture.serverVersionAtLeast(com.mongodb.ClusterFixture.serverVersionAtLeast) Nullable(com.mongodb.lang.Nullable) BsonInt32(org.bson.BsonInt32) ClusterFixture.disableFailPoint(com.mongodb.ClusterFixture.disableFailPoint) SECONDS(java.util.concurrent.TimeUnit.SECONDS) Assert.assertEquals(org.junit.Assert.assertEquals) BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) BsonString(org.bson.BsonString) MongoClientSettings(com.mongodb.MongoClientSettings) ClusterFixture.configureFailPoint(com.mongodb.ClusterFixture.configureFailPoint) ClusterFixture.disableFailPoint(com.mongodb.ClusterFixture.disableFailPoint) ClusterFixture.isServerlessTest(com.mongodb.ClusterFixture.isServerlessTest) Test(org.junit.Test)

Example 98 with BsonInt32

use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.

the class CrudProseTest method testWriteConcernErrInfoIsPropagated.

/**
 * 1. WriteConcernError.details exposes writeConcernError.errInfo
 */
@Test
public void testWriteConcernErrInfoIsPropagated() {
    assumeTrue(isDiscoverableReplicaSet() && serverVersionAtLeast(4, 0));
    try {
        setFailPoint();
        collection.insertOne(Document.parse("{ x: 1 }"));
    } catch (MongoWriteConcernException e) {
        assertEquals(e.getWriteConcernError().getCode(), 100);
        assertEquals("UnsatisfiableWriteConcern", e.getWriteConcernError().getCodeName());
        assertEquals(e.getWriteConcernError().getDetails(), new BsonDocument("writeConcern", new BsonDocument("w", new BsonInt32(2)).append("wtimeout", new BsonInt32(0)).append("provenance", new BsonString("clientSupplied"))));
    } catch (Exception ex) {
        fail(format("Incorrect exception thrown in test: %s", ex.getClass()));
    } finally {
        disableFailPoint();
    }
}
Also used : BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) MongoWriteConcernException(com.mongodb.MongoWriteConcernException) MongoWriteException(com.mongodb.MongoWriteException) MongoBulkWriteException(com.mongodb.MongoBulkWriteException) MongoWriteConcernException(com.mongodb.MongoWriteConcernException) Test(org.junit.Test)

Example 99 with BsonInt32

use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.

the class AbstractFindBenchmark method insertCopiesOfDocument.

private void insertCopiesOfDocument(final MongoCollection<BsonDocument> collection, final BsonDocument document) {
    List<BsonDocument> documents = new ArrayList<BsonDocument>(NUM_INTERNAL_ITERATIONS);
    for (int i = 0; i < NUM_INTERNAL_ITERATIONS; i++) {
        BsonDocument copy = document.clone();
        copy.put("_id", new BsonInt32(i));
        documents.add(copy);
    }
    collection.insertMany(documents);
}
Also used : BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList)

Example 100 with BsonInt32

use of org.bson.BsonInt32 in project mongo-java-driver by mongodb.

the class BatchCursorFluxTest method ensureExists.

/**
 * This method ensures that the server considers the specified {@code collection} existing for the purposes of, e.g.,
 * {@link MongoCollection#drop()}, instead of replying with
 * {@code "errmsg": "ns not found", "code": 26, "codeName": "NamespaceNotFound"}.
 *
 * @return {@code operationTime} starting at which the {@code collection} is guaranteed to exist.
 */
private static BsonTimestamp ensureExists(final MongoClient client, final MongoCollection<Document> collection) {
    BsonValue insertedId = Mono.from(collection.insertOne(Document.parse("{}"))).map(InsertOneResult::getInsertedId).block(TIMEOUT_DURATION);
    BsonArray deleteStatements = new BsonArray();
    deleteStatements.add(new BsonDocument().append("q", new BsonDocument().append("_id", insertedId)).append("limit", new BsonInt32(1)));
    Publisher<Document> deletePublisher = client.getDatabase(collection.getNamespace().getDatabaseName()).runCommand(new BsonDocument().append("delete", new BsonString(collection.getNamespace().getCollectionName())).append("deletes", deleteStatements));
    BsonTimestamp operationTime = Mono.from(deletePublisher).map(doc -> doc.get("operationTime", BsonTimestamp.class)).block(TIMEOUT_DURATION);
    assertNotNull(operationTime);
    return operationTime;
}
Also used : Document(org.bson.Document) IntStream(java.util.stream.IntStream) BeforeEach(org.junit.jupiter.api.BeforeEach) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Mock(org.mockito.Mock) MongoClients(com.mongodb.reactivestreams.client.MongoClients) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) MongoCollection(com.mongodb.reactivestreams.client.MongoCollection) BsonString(org.bson.BsonString) MongoClient(com.mongodb.reactivestreams.client.MongoClient) BsonDocument(org.bson.BsonDocument) BsonValue(org.bson.BsonValue) TIMEOUT_DURATION(com.mongodb.ClusterFixture.TIMEOUT_DURATION) Fixture.getMongoClientBuilderFromConnectionString(com.mongodb.reactivestreams.client.Fixture.getMongoClientBuilderFromConnectionString) Collections.singletonList(java.util.Collections.singletonList) Fixture.drop(com.mongodb.reactivestreams.client.Fixture.drop) TestCommandListener(com.mongodb.internal.connection.TestCommandListener) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) BsonTimestamp(org.bson.BsonTimestamp) Arrays.asList(java.util.Arrays.asList) BsonArray(org.bson.BsonArray) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) Fixture.isReplicaSet(com.mongodb.reactivestreams.client.Fixture.isReplicaSet) Assertions.assertAll(org.junit.jupiter.api.Assertions.assertAll) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) CommandEvent(com.mongodb.event.CommandEvent) TestSubscriber(com.mongodb.reactivestreams.client.TestSubscriber) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) InsertOneResult(com.mongodb.client.result.InsertOneResult) Assertions.assertIterableEquals(org.junit.jupiter.api.Assertions.assertIterableEquals) Collections.emptyList(java.util.Collections.emptyList) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) Fixture.serverVersionAtLeast(com.mongodb.reactivestreams.client.Fixture.serverVersionAtLeast) Mockito.when(org.mockito.Mockito.when) ClusterFixture.getDefaultDatabaseName(com.mongodb.ClusterFixture.getDefaultDatabaseName) Collectors(java.util.stream.Collectors) DisplayName(org.junit.jupiter.api.DisplayName) Test(org.junit.jupiter.api.Test) AfterEach(org.junit.jupiter.api.AfterEach) List(java.util.List) FindPublisher(com.mongodb.reactivestreams.client.FindPublisher) MongoClientSettings(com.mongodb.MongoClientSettings) BsonInt32(org.bson.BsonInt32) BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) Document(org.bson.Document) ChangeStreamDocument(com.mongodb.client.model.changestream.ChangeStreamDocument) BsonDocument(org.bson.BsonDocument) BsonTimestamp(org.bson.BsonTimestamp) BsonValue(org.bson.BsonValue)

Aggregations

BsonInt32 (org.bson.BsonInt32)106 BsonDocument (org.bson.BsonDocument)91 BsonString (org.bson.BsonString)58 BsonArray (org.bson.BsonArray)26 Test (org.junit.Test)26 Document (org.bson.Document)23 BsonInt64 (org.bson.BsonInt64)20 Test (org.junit.jupiter.api.Test)16 BsonValue (org.bson.BsonValue)15 ArrayList (java.util.ArrayList)13 List (java.util.List)9 BsonDouble (org.bson.BsonDouble)9 DisplayName (org.junit.jupiter.api.DisplayName)8 BsonNull (org.bson.BsonNull)7 MongoClientSettings (com.mongodb.MongoClientSettings)6 TestCommandListener (com.mongodb.internal.connection.TestCommandListener)5 Map (java.util.Map)5 BsonBoolean (org.bson.BsonBoolean)5 ClusterFixture.serverVersionAtLeast (com.mongodb.ClusterFixture.serverVersionAtLeast)4 ServerAddress (com.mongodb.ServerAddress)4