Search in sources :

Example 36 with BsonInt64

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

the class TestWindows method rangeBased.

@Test
void rangeBased() {
    assertAll(() -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonInt64(-1), new BsonInt64(0)))), range(-1, 0).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonDouble(0), new BsonDouble(0)))), range(0d, 0d).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonDecimal128(new Decimal128(1)), new BsonDecimal128(new Decimal128(2))))), range(new Decimal128(1), new Decimal128(2)).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonString(CURRENT.value()), new BsonDouble(0.1)))), range(CURRENT, 0.1).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonDouble(0.1), new BsonString(UNBOUNDED.value())))), range(0.1, UNBOUNDED).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonString(CURRENT.value()), new BsonDecimal128(new Decimal128(Long.MAX_VALUE))))), range(CURRENT, new Decimal128(Long.MAX_VALUE)).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonDecimal128(new Decimal128(Long.MAX_VALUE)), new BsonString(UNBOUNDED.value())))), range(new Decimal128(Long.MAX_VALUE), UNBOUNDED).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonInt64(-1), new BsonInt64(0)))).append("unit", new BsonString("millisecond")), timeRange(-1, 0, MILLISECOND).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonString(CURRENT.value()), new BsonInt64(1)))).append("unit", new BsonString("hour")), timeRange(CURRENT, 1, HOUR).toBsonDocument()), () -> assertEquals(new BsonDocument("range", new BsonArray(asList(new BsonInt64(1), new BsonString(UNBOUNDED.value())))).append("unit", new BsonString("month")), timeRange(1, MONTH, UNBOUNDED).toBsonDocument()));
    assertAll(() -> assertThrows(IllegalArgumentException.class, () -> range(1, -1)), () -> assertThrows(IllegalArgumentException.class, () -> range(null, 1)), () -> assertThrows(IllegalArgumentException.class, () -> range(null, 0.1)), () -> assertThrows(IllegalArgumentException.class, () -> range((Bound) null, Decimal128.POSITIVE_ZERO)), () -> assertThrows(IllegalArgumentException.class, () -> range(1, null)), () -> assertThrows(IllegalArgumentException.class, () -> range(0.1, null)), () -> assertThrows(IllegalArgumentException.class, () -> range(Decimal128.POSITIVE_ZERO, (Bound) null)), () -> assertThrows(IllegalArgumentException.class, () -> range((Decimal128) null, Decimal128.POSITIVE_ZERO)), () -> assertThrows(IllegalArgumentException.class, () -> range(Decimal128.POSITIVE_ZERO, (Decimal128) null)), () -> assertThrows(IllegalArgumentException.class, () -> range((Decimal128) null, (Decimal128) null)), () -> assertThrows(IllegalArgumentException.class, () -> timeRange(1, -1, MongoTimeUnit.DAY)), () -> assertThrows(IllegalArgumentException.class, () -> timeRange(1, 2, null)));
}
Also used : BsonInt64(org.bson.BsonInt64) BsonDocument(org.bson.BsonDocument) BsonDecimal128(org.bson.BsonDecimal128) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) BsonDouble(org.bson.BsonDouble) BsonDecimal128(org.bson.BsonDecimal128) Decimal128(org.bson.types.Decimal128) Test(org.junit.jupiter.api.Test)

Example 37 with BsonInt64

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

the class AbstractConnectionPoolTest method shouldPassAllOutcomes.

@Test
public void shouldPassAllOutcomes() throws Exception {
    try {
        for (BsonValue cur : definition.getArray("operations")) {
            final BsonDocument operation = cur.asDocument();
            String name = operation.getString("name").getValue();
            if (name.equals("start")) {
                String target = operation.getString("target", new BsonString("")).getValue();
                executorServiceMap.put(target, Executors.newSingleThreadExecutor(r -> {
                    Thread result = Executors.defaultThreadFactory().newThread(r);
                    result.setName(target);
                    return result;
                }));
            } else if (name.equals("wait")) {
                Thread.sleep(operation.getNumber("ms").intValue());
            } else if (name.equals("waitForThread")) {
                String target = operation.getString("target", new BsonString("")).getValue();
                Exception exceptionFromFuture = futureMap.remove(target).get(5, TimeUnit.SECONDS);
                if (exceptionFromFuture != null) {
                    throw exceptionFromFuture;
                }
            } else if (name.equals("waitForEvent")) {
                Class<?> eventClass = getEventClass(operation.getString("event").getValue());
                assumeNotNull(eventClass);
                long timeoutMillis = operation.getNumber("timeout", new BsonInt64(TimeUnit.SECONDS.toMillis(5))).longValue();
                listener.waitForEvent(eventClass, operation.getNumber("count").intValue(), timeoutMillis, TimeUnit.MILLISECONDS);
            } else if (name.equals("clear")) {
                pool.invalidate(null);
            } else if (name.equals("ready")) {
                pool.ready();
            } else if (name.equals("close")) {
                pool.close();
            } else if (name.equals("checkOut") || name.equals("checkIn")) {
                Callable<Exception> callable = createCallable(operation);
                if (operation.containsKey("thread")) {
                    String threadTarget = operation.getString("thread").getValue();
                    ExecutorService executorService = executorServiceMap.get(threadTarget);
                    futureMap.put(threadTarget, executorService.submit(callable));
                } else {
                    callable.call();
                }
            } else {
                throw new UnsupportedOperationException("No support for " + name);
            }
        }
    } catch (Exception e) {
        if (!definition.containsKey("error")) {
            throw e;
        }
        BsonDocument errorDocument = definition.getDocument("error");
        String exceptionType = errorDocument.getString("type").getValue();
        if (exceptionType.equals("PoolClosedError")) {
            assertEquals(IllegalStateException.class, e.getClass());
        } else if (exceptionType.equals("WaitQueueTimeoutError")) {
            if (e.getClass() != MongoTimeoutException.class) {
                throw e;
            }
        } else {
            throw e;
        }
    }
    if (definition.containsKey("events")) {
        Iterator<Object> actualEventsIterator = getNonIgnoredActualEvents().iterator();
        BsonArray expectedEvents = definition.getArray("events");
        for (BsonValue cur : expectedEvents) {
            BsonDocument expectedEvent = cur.asDocument();
            String type = expectedEvent.getString("type").getValue();
            if (type.equals("ConnectionPoolCreated")) {
                ConnectionPoolCreatedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolCreatedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
                assertEquals(settings, actualEvent.getSettings());
            } else if (type.equals("ConnectionPoolCleared")) {
                ConnectionPoolClearedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolClearedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionPoolReady")) {
                ConnectionPoolReadyEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolReadyEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionPoolClosed")) {
                ConnectionPoolClosedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionPoolClosedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionCreated")) {
                ConnectionCreatedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCreatedEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
            } else if (type.equals("ConnectionReady")) {
                ConnectionReadyEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionReadyEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getConnectionId().getServerId().getAddress());
            } else if (type.equals("ConnectionClosed")) {
                ConnectionClosedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionClosedEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
                assertReasonMatch(expectedEvent, actualEvent);
            } else if (type.equals("ConnectionCheckOutStarted")) {
                ConnectionCheckOutStartedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckOutStartedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
            } else if (type.equals("ConnectionCheckOutFailed")) {
                ConnectionCheckOutFailedEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckOutFailedEvent.class);
                assertAddressMatch(expectedEvent, actualEvent.getServerId().getAddress());
                assertReasonMatch(expectedEvent, actualEvent);
            } else if (type.equals("ConnectionCheckedOut")) {
                ConnectionCheckedOutEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckedOutEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
            } else if (type.equals("ConnectionCheckedIn")) {
                ConnectionCheckedInEvent actualEvent = getNextEvent(actualEventsIterator, ConnectionCheckedInEvent.class);
                assertConnectionIdMatch(expectedEvent, actualEvent.getConnectionId());
            } else {
                throw new UnsupportedOperationException("Unsupported event type " + type);
            }
        }
    }
}
Also used : URISyntaxException(java.net.URISyntaxException) JsonTestServerVersionChecker(com.mongodb.JsonTestServerVersionChecker) ConnectionPoolCreatedEvent(com.mongodb.event.ConnectionPoolCreatedEvent) BsonValue(org.bson.BsonValue) ClusterId(com.mongodb.connection.ClusterId) Future(java.util.concurrent.Future) ServerListener(com.mongodb.event.ServerListener) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SocketSettings(com.mongodb.connection.SocketSettings) BsonArray(org.bson.BsonArray) After(org.junit.After) Map(java.util.Map) Assert.fail(org.junit.Assert.fail) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) Parameterized(org.junit.runners.Parameterized) StreamFactory(com.mongodb.connection.StreamFactory) Collection(java.util.Collection) Set(java.util.Set) Assertions.assertFalse(com.mongodb.assertions.Assertions.assertFalse) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) Executors(java.util.concurrent.Executors) String.format(java.lang.String.format) SingleResultCallback(com.mongodb.internal.async.SingleResultCallback) List(java.util.List) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) Assume.assumeNotNull(org.junit.Assume.assumeNotNull) Mockito.mock(org.mockito.Mockito.mock) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) ConnectionPoolSettings(com.mongodb.connection.ConnectionPoolSettings) JsonPoweredTestHelper(util.JsonPoweredTestHelper) ConnectionCheckedInEvent(com.mongodb.event.ConnectionCheckedInEvent) Assume.assumeFalse(org.junit.Assume.assumeFalse) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) SameObjectProvider(com.mongodb.internal.inject.SameObjectProvider) BsonString(org.bson.BsonString) BsonDocument(org.bson.BsonDocument) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ClusterFixture(com.mongodb.ClusterFixture) ClusterConnectionMode(com.mongodb.connection.ClusterConnectionMode) BsonInt64(org.bson.BsonInt64) ConnectionCreatedEvent(com.mongodb.event.ConnectionCreatedEvent) MongoDriverInformation(com.mongodb.MongoDriverInformation) ExecutorService(java.util.concurrent.ExecutorService) Before(org.junit.Before) ServerAddress(com.mongodb.ServerAddress) SslSettings(com.mongodb.connection.SslSettings) ConnectionReadyEvent(com.mongodb.event.ConnectionReadyEvent) MongoInterruptedException(com.mongodb.MongoInterruptedException) Iterator(java.util.Iterator) ServerId(com.mongodb.connection.ServerId) CommandReadOperation(com.mongodb.internal.operation.CommandReadOperation) Test(org.junit.Test) IOException(java.io.IOException) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) File(java.io.File) MongoTimeoutException(com.mongodb.MongoTimeoutException) TimeUnit(java.util.concurrent.TimeUnit) ConnectionPoolClosedEvent(com.mongodb.event.ConnectionPoolClosedEvent) Mockito(org.mockito.Mockito) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent) ObjectId(org.bson.types.ObjectId) Nullable(com.mongodb.lang.Nullable) ConnectionId(com.mongodb.connection.ConnectionId) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) ConnectionClosedEvent(com.mongodb.event.ConnectionClosedEvent) ConnectionReadyEvent(com.mongodb.event.ConnectionReadyEvent) BsonString(org.bson.BsonString) ConnectionCheckOutStartedEvent(com.mongodb.event.ConnectionCheckOutStartedEvent) Callable(java.util.concurrent.Callable) ConnectionCheckedOutEvent(com.mongodb.event.ConnectionCheckedOutEvent) ConnectionPoolClearedEvent(com.mongodb.event.ConnectionPoolClearedEvent) ConnectionCreatedEvent(com.mongodb.event.ConnectionCreatedEvent) ConnectionCheckedInEvent(com.mongodb.event.ConnectionCheckedInEvent) ConnectionPoolReadyEvent(com.mongodb.event.ConnectionPoolReadyEvent) ConnectionCheckOutFailedEvent(com.mongodb.event.ConnectionCheckOutFailedEvent) URISyntaxException(java.net.URISyntaxException) MongoInterruptedException(com.mongodb.MongoInterruptedException) IOException(java.io.IOException) MongoTimeoutException(com.mongodb.MongoTimeoutException) BsonInt64(org.bson.BsonInt64) BsonDocument(org.bson.BsonDocument) ConnectionPoolCreatedEvent(com.mongodb.event.ConnectionPoolCreatedEvent) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) ExecutorService(java.util.concurrent.ExecutorService) ConnectionPoolClosedEvent(com.mongodb.event.ConnectionPoolClosedEvent) BsonValue(org.bson.BsonValue) Test(org.junit.Test)

Example 38 with BsonInt64

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

the class WorkloadExecutor method main.

public static void main(String[] args) throws IOException {
    if (args.length != 2) {
        System.out.println("Usage: AstrolabeTestRunner <path to workload spec JSON file> <path to results directory>");
        System.exit(1);
    }
    String pathToWorkloadFile = args[0];
    String pathToResultsDirectory = args[1];
    LOGGER.info("Max memory (GB): " + (Runtime.getRuntime().maxMemory() / 1_073_741_824.0));
    LOGGER.info("Path to workload file: '" + pathToWorkloadFile + "'");
    LOGGER.info("Path to results directory: '" + pathToResultsDirectory + "'");
    Runtime.getRuntime().addShutdownHook(new Thread(() -> {
        LOGGER.info("Running shutdown hook");
        terminateLoop = true;
        try {
            if (!terminationLatch.await(1, TimeUnit.MINUTES)) {
                LOGGER.warn("Terminating after waiting for 1 minute for results to be written");
            } else {
                LOGGER.info("Terminating.");
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }));
    BsonDocument fileDocument;
    try (FileReader reader = new FileReader(pathToWorkloadFile)) {
        fileDocument = new BsonDocumentCodec().decode(new JsonReader(reader), DecoderContext.builder().build());
    }
    LOGGER.info("Executing workload: " + fileDocument.toJson(JsonWriterSettings.builder().indent(true).build()));
    BsonArray testArray = fileDocument.getArray("tests");
    if (testArray.size() != 1) {
        throw new IllegalArgumentException("Expected exactly one test");
    }
    BsonDocument testDocument = testArray.get(0).asDocument();
    UnifiedTest unifiedTest = new UnifiedSyncTest(fileDocument.getString("schemaVersion").getValue(), fileDocument.getArray("runOnRequirements", null), fileDocument.getArray("createEntities", new BsonArray()), fileDocument.getArray("initialData", new BsonArray()), testDocument) {

        @Override
        protected boolean terminateLoop() {
            return terminateLoop;
        }
    };
    try {
        unifiedTest.setUp();
        unifiedTest.shouldPassAllOutcomes();
        Entities entities = unifiedTest.getEntities();
        long iterationCount = -1;
        if (entities.hasIterationCount("iterations")) {
            iterationCount = entities.getIterationCount("iterations");
        }
        long successCount = -1;
        if (entities.hasSuccessCount("successes")) {
            successCount = entities.getSuccessCount("successes");
        }
        BsonArray errorDocuments = null;
        long errorCount = 0;
        if (entities.hasErrorDocuments("errors")) {
            errorDocuments = entities.getErrorDocuments("errors");
            errorCount = errorDocuments.size();
        }
        BsonArray failureDocuments = null;
        long failureCount = 0;
        if (entities.hasFailureDocuments("failures")) {
            failureDocuments = entities.getFailureDocuments("failures");
            failureCount = failureDocuments.size();
        }
        BsonArray eventDocuments = new BsonArray();
        if (entities.hasEvents("events")) {
            eventDocuments = new BsonArray(entities.getEvents("events"));
        }
        BsonDocument eventsDocument = new BsonDocument().append("errors", errorDocuments == null ? new BsonArray() : errorDocuments).append("failures", failureDocuments == null ? new BsonArray() : failureDocuments).append("events", eventDocuments);
        BsonDocument resultsDocument = new BsonDocument().append("numErrors", new BsonInt64(errorCount)).append("numFailures", new BsonInt64(failureCount)).append("numSuccesses", new BsonInt64(successCount)).append("numIterations", new BsonInt64(iterationCount));
        writeFile(eventsDocument, Paths.get(pathToResultsDirectory, "events.json"));
        writeFile(resultsDocument, Paths.get(pathToResultsDirectory, "results.json"));
    } finally {
        unifiedTest.cleanUp();
        terminationLatch.countDown();
    }
}
Also used : UnifiedSyncTest(com.mongodb.client.unified.UnifiedSyncTest) Entities(com.mongodb.client.unified.Entities) BsonInt64(org.bson.BsonInt64) BsonDocument(org.bson.BsonDocument) BsonArray(org.bson.BsonArray) JsonReader(org.bson.json.JsonReader) FileReader(java.io.FileReader) UnifiedTest(com.mongodb.client.unified.UnifiedTest) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec)

Example 39 with BsonInt64

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

the class AggregateToCollectionOperation method getCommand.

private BsonDocument getCommand(final ConnectionDescription description) {
    validateCollation(description, collation);
    BsonValue aggregationTarget = (aggregationLevel == AggregationLevel.DATABASE) ? new BsonInt32(1) : new BsonString(namespace.getCollectionName());
    BsonDocument commandDocument = new BsonDocument("aggregate", aggregationTarget);
    commandDocument.put("pipeline", new BsonArray(pipeline));
    if (maxTimeMS > 0) {
        commandDocument.put("maxTimeMS", new BsonInt64(maxTimeMS));
    }
    if (allowDiskUse != null) {
        commandDocument.put("allowDiskUse", BsonBoolean.valueOf(allowDiskUse));
    }
    if (bypassDocumentValidation != null && serverIsAtLeastVersionThreeDotTwo(description)) {
        commandDocument.put("bypassDocumentValidation", BsonBoolean.valueOf(bypassDocumentValidation));
    }
    if (serverIsAtLeastVersionThreeDotSix(description)) {
        commandDocument.put("cursor", new BsonDocument());
    }
    appendWriteConcernToCommand(writeConcern, commandDocument, description);
    if (readConcern != null && !readConcern.isServerDefault() && serverIsAtLeastVersionThreeDotFour(description)) {
        commandDocument.put("readConcern", readConcern.asDocument());
    }
    if (collation != null) {
        commandDocument.put("collation", collation.asDocument());
    }
    if (comment != null) {
        commandDocument.put("comment", new BsonString(comment));
    }
    if (hint != null) {
        commandDocument.put("hint", hint);
    }
    if (variables != null) {
        commandDocument.put("let", variables);
    }
    return commandDocument;
}
Also used : BsonInt64(org.bson.BsonInt64) BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString) BsonArray(org.bson.BsonArray) BsonValue(org.bson.BsonValue)

Example 40 with BsonInt64

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

the class QueryBatchCursor method asGetMoreCommandDocument.

private BsonDocument asGetMoreCommandDocument(final ServerCursor serverCursor) {
    BsonDocument document = new BsonDocument("getMore", new BsonInt64(serverCursor.getId())).append("collection", new BsonString(namespace.getCollectionName()));
    int batchSizeForGetMoreCommand = Math.abs(getNumberToReturn(limit, this.batchSize, count));
    if (batchSizeForGetMoreCommand != 0) {
        document.append("batchSize", new BsonInt32(batchSizeForGetMoreCommand));
    }
    if (maxTimeMS != 0) {
        document.append("maxTimeMS", new BsonInt64(maxTimeMS));
    }
    return document;
}
Also used : BsonInt64(org.bson.BsonInt64) BsonInt32(org.bson.BsonInt32) BsonDocument(org.bson.BsonDocument) BsonString(org.bson.BsonString)

Aggregations

BsonInt64 (org.bson.BsonInt64)44 BsonDocument (org.bson.BsonDocument)36 BsonString (org.bson.BsonString)30 BsonInt32 (org.bson.BsonInt32)20 BsonArray (org.bson.BsonArray)16 BsonDouble (org.bson.BsonDouble)13 BsonValue (org.bson.BsonValue)11 Test (org.junit.Test)7 MongoNamespace (com.mongodb.MongoNamespace)4 ArrayList (java.util.ArrayList)4 Map (java.util.Map)4 CommandSucceededEvent (com.mongodb.event.CommandSucceededEvent)3 BsonDocumentReader (org.bson.BsonDocumentReader)3 BsonRegularExpression (org.bson.BsonRegularExpression)3 ObjectId (org.bson.types.ObjectId)3 Test (org.junit.jupiter.api.Test)3 SingleMapReaderImpl (org.apache.drill.exec.vector.complex.impl.SingleMapReaderImpl)2 BsonBoolean (org.bson.BsonBoolean)2 BsonDateTime (org.bson.BsonDateTime)2 BsonNull (org.bson.BsonNull)2