use of org.bson.json.JsonReader in project immutables by immutables.
the class BsonReaderTest method compare.
private static void compare(String string) throws IOException {
// compare as BSON
JsonElement bson = TypeAdapters.JSON_ELEMENT.read(new BsonReader(new JsonReader(string)));
// compare as JSON
JsonElement gson = TypeAdapters.JSON_ELEMENT.fromJson(string);
// compare the two
check(bson).is(gson);
}
use of org.bson.json.JsonReader in project realm-java by realm.
the class JniBsonProtocol method decode.
public static <T> T decode(String string, Decoder<T> decoder) {
try {
StringReader stringReader = new StringReader(string);
JsonReader jsonReader = new JsonReader(stringReader);
jsonReader.readStartDocument();
jsonReader.readName(VALUE);
T value = decoder.decode(jsonReader, DecoderContext.builder().build());
jsonReader.readEndDocument();
return value;
} catch (CodecConfigurationException e) {
// might be missing
throw new AppException(ErrorCode.BSON_CODEC_NOT_FOUND, "Could not resolve decoder for end type" + string, e);
} catch (Exception e) {
throw new AppException(ErrorCode.BSON_DECODING, "Error decoding value " + string, e);
}
}
use of org.bson.json.JsonReader in project spring-data-mongodb by spring-projects.
the class MappingMongoConverter method readDocument.
/**
* Conversion method to materialize an object from a {@link Bson document}. Can be overridden by subclasses.
*
* @param context must not be {@literal null}
* @param bson must not be {@literal null}
* @param typeHint the {@link TypeInformation} to be used to unmarshall this {@link Document}.
* @return the converted object, will never be {@literal null}.
* @since 3.2
*/
@SuppressWarnings("unchecked")
protected <S extends Object> S readDocument(ConversionContext context, Bson bson, TypeInformation<? extends S> typeHint) {
Document document = bson instanceof BasicDBObject ? new Document((BasicDBObject) bson) : (Document) bson;
TypeInformation<? extends S> typeToRead = getTypeMapper().readType(document, typeHint);
Class<? extends S> rawType = typeToRead.getType();
if (conversions.hasCustomReadTarget(bson.getClass(), rawType)) {
return doConvert(bson, rawType, typeHint.getType());
}
if (Document.class.isAssignableFrom(rawType)) {
return (S) bson;
}
if (DBObject.class.isAssignableFrom(rawType)) {
if (bson instanceof DBObject) {
return (S) bson;
}
if (bson instanceof Document) {
return (S) new BasicDBObject((Document) bson);
}
return (S) bson;
}
if (typeToRead.isMap()) {
return context.convert(bson, typeToRead);
}
if (BSON.isAssignableFrom(typeHint)) {
return (S) bson;
}
MongoPersistentEntity<?> entity = mappingContext.getPersistentEntity(typeToRead);
if (entity == null) {
if (codecRegistryProvider != null) {
Optional<? extends Codec<? extends S>> codec = codecRegistryProvider.getCodecFor(rawType);
if (codec.isPresent()) {
return codec.get().decode(new JsonReader(document.toJson()), DecoderContext.builder().build());
}
}
throw new MappingException(String.format(INVALID_TYPE_TO_READ, document, rawType));
}
return read(context, (MongoPersistentEntity<S>) entity, document);
}
use of org.bson.json.JsonReader in project mongo-java-driver by mongodb.
the class MessageHelper method encodeJson.
private static ByteBuf encodeJson(final String json) {
OutputBuffer outputBuffer = new BasicOutputBuffer();
JsonReader jsonReader = new JsonReader(json);
BsonDocumentCodec codec = new BsonDocumentCodec();
BsonDocument document = codec.decode(jsonReader, DecoderContext.builder().build());
BsonBinaryWriter writer = new BsonBinaryWriter(outputBuffer);
codec.encode(writer, document, EncoderContext.builder().build());
ByteBuffer documentByteBuffer = ByteBuffer.allocate(outputBuffer.size());
documentByteBuffer.put(outputBuffer.toByteArray());
return new ByteBufNIO(documentByteBuffer);
}
use of org.bson.json.JsonReader 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();
}
}
Aggregations