use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.
the class UnifiedTest method addInitialData.
private void addInitialData() {
for (BsonValue cur : initialData.getValues()) {
BsonDocument curDataSet = cur.asDocument();
CollectionHelper<BsonDocument> helper = new CollectionHelper<>(new BsonDocumentCodec(), new MongoNamespace(curDataSet.getString("databaseName").getValue(), curDataSet.getString("collectionName").getValue()));
helper.create(WriteConcern.MAJORITY);
BsonArray documentsArray = curDataSet.getArray("documents", new BsonArray());
if (!documentsArray.isEmpty()) {
helper.insertDocuments(documentsArray.stream().map(BsonValue::asDocument).collect(toList()), WriteConcern.MAJORITY);
}
}
}
use of org.bson.codecs.BsonDocumentCodec 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();
}
}
use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.
the class CommandOperationHelper method executeCommandAsync.
/* Async Write Binding Helpers */
static <T> void executeCommandAsync(final AsyncWriteBinding binding, final String database, final BsonDocument command, final AsyncConnection connection, final CommandWriteTransformerAsync<BsonDocument, T> transformer, final SingleResultCallback<T> callback) {
notNull("binding", binding);
SingleResultCallback<T> addingRetryableLabelCallback = addingRetryableLabelCallback(callback, connection.getDescription().getMaxWireVersion());
connection.commandAsync(database, command, new NoOpFieldNameValidator(), primary(), new BsonDocumentCodec(), binding.getSessionContext(), binding.getServerApi(), binding.getRequestContext(), transformingWriteCallback(transformer, connection, addingRetryableLabelCallback));
}
use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.
the class ListCollectionsOperation method execute.
@Override
public BatchCursor<T> execute(final ReadBinding binding) {
RetryState retryState = initialRetryState(retryReads);
Supplier<BatchCursor<T>> read = decorateReadWithRetries(retryState, () -> {
logRetryExecute(retryState);
return withSourceAndConnection(binding::getReadConnectionSource, false, (source, connection) -> {
retryState.breakAndThrowIfRetryAnd(() -> !canRetryRead(source.getServerDescription(), connection.getDescription(), binding.getSessionContext()));
if (serverIsAtLeastVersionThreeDotZero(connection.getDescription())) {
try {
return createReadCommandAndExecute(retryState, binding, source, databaseName, getCommandCreator(), createCommandDecoder(), commandTransformer(), connection);
} catch (MongoCommandException e) {
return rethrowIfNotNamespaceError(e, createEmptyBatchCursor(createNamespace(), decoder, source.getServerDescription().getAddress(), batchSize));
}
} else {
retryState.markAsLastAttempt();
return new ProjectingBatchCursor(new QueryBatchCursor<>(connection.query(getNamespace(), asQueryDocument(connection.getDescription(), binding.getReadPreference()), null, 0, 0, batchSize, binding.getReadPreference().isSecondaryOk(), false, false, false, false, false, new BsonDocumentCodec(), binding.getRequestContext()), 0, batchSize, new BsonDocumentCodec(), source));
}
});
});
return read.get();
}
use of org.bson.codecs.BsonDocumentCodec in project mongo-java-driver by mongodb.
the class ListCollectionsOperation method executeAsync.
@Override
public void executeAsync(final AsyncReadBinding binding, final SingleResultCallback<AsyncBatchCursor<T>> callback) {
RetryState retryState = initialRetryState(retryReads);
binding.retain();
AsyncCallbackSupplier<AsyncBatchCursor<T>> asyncRead = CommandOperationHelper.<AsyncBatchCursor<T>>decorateReadWithRetries(retryState, funcCallback -> {
logRetryExecute(retryState);
withAsyncSourceAndConnection(binding::getReadConnectionSource, false, funcCallback, (source, connection, releasingCallback) -> {
if (retryState.breakAndCompleteIfRetryAnd(() -> !canRetryRead(source.getServerDescription(), connection.getDescription(), binding.getSessionContext()), releasingCallback)) {
return;
}
if (serverIsAtLeastVersionThreeDotZero(connection.getDescription())) {
createReadCommandAndExecuteAsync(retryState, binding, source, databaseName, getCommandCreator(), createCommandDecoder(), asyncTransformer(), connection, (result, t) -> {
if (t != null && !isNamespaceError(t)) {
releasingCallback.onResult(null, t);
} else {
releasingCallback.onResult(result != null ? result : emptyAsyncCursor(source), null);
}
});
} else {
retryState.markAsLastAttempt();
connection.queryAsync(getNamespace(), asQueryDocument(connection.getDescription(), binding.getReadPreference()), null, 0, 0, batchSize, binding.getReadPreference().isSecondaryOk(), false, false, false, false, false, new BsonDocumentCodec(), binding.getRequestContext(), new SingleResultCallback<QueryResult<BsonDocument>>() {
@Override
public void onResult(final QueryResult<BsonDocument> result, final Throwable t) {
if (t != null) {
releasingCallback.onResult(null, t);
} else {
releasingCallback.onResult(new ProjectingAsyncBatchCursor(new AsyncQueryBatchCursor<BsonDocument>(result, 0, batchSize, 0, new BsonDocumentCodec(), source, connection)), null);
}
}
});
}
});
}).whenComplete(binding::release);
asyncRead.get(errorHandlingCallback(callback, LOGGER));
}
Aggregations