Search in sources :

Example 11 with JsonReader

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);
}
Also used : JsonElement(com.google.gson.JsonElement) JsonReader(org.bson.json.JsonReader)

Example 12 with JsonReader

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);
    }
}
Also used : AppException(io.realm.mongodb.AppException) CodecConfigurationException(org.bson.codecs.configuration.CodecConfigurationException) StringReader(java.io.StringReader) JsonReader(org.bson.json.JsonReader) AppException(io.realm.mongodb.AppException) CodecConfigurationException(org.bson.codecs.configuration.CodecConfigurationException)

Example 13 with JsonReader

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);
}
Also used : BasicDBObject(com.mongodb.BasicDBObject) JsonReader(org.bson.json.JsonReader) Document(org.bson.Document) DBObject(com.mongodb.DBObject) BasicDBObject(com.mongodb.BasicDBObject)

Example 14 with JsonReader

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);
}
Also used : BsonDocument(org.bson.BsonDocument) JsonReader(org.bson.json.JsonReader) BsonBinaryWriter(org.bson.BsonBinaryWriter) ByteBufNIO(org.bson.ByteBufNIO) BasicOutputBuffer(org.bson.io.BasicOutputBuffer) OutputBuffer(org.bson.io.OutputBuffer) ByteBuffer(java.nio.ByteBuffer) BsonDocumentCodec(org.bson.codecs.BsonDocumentCodec) BasicOutputBuffer(org.bson.io.BasicOutputBuffer)

Example 15 with JsonReader

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();
    }
}
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)

Aggregations

JsonReader (org.bson.json.JsonReader)18 BsonDocument (org.bson.BsonDocument)5 BsonDocumentCodec (org.bson.codecs.BsonDocumentCodec)5 BsonReader (org.bson.BsonReader)4 Test (org.junit.Test)4 ArrayList (java.util.ArrayList)3 MongoDatabase (com.mongodb.client.MongoDatabase)2 InsertManyOptions (com.mongodb.client.model.InsertManyOptions)2 BufferedReader (java.io.BufferedReader)2 IOException (java.io.IOException)2 ByteBuffer (java.nio.ByteBuffer)2 Converter (org.apache.camel.Converter)2 IOConverter (org.apache.camel.converter.IOConverter)2 BsonArray (org.bson.BsonArray)2 BsonBinaryWriter (org.bson.BsonBinaryWriter)2 ByteBufNIO (org.bson.ByteBufNIO)2 Document (org.bson.Document)2 RawBsonDocument (org.bson.RawBsonDocument)2 RawBsonDocumentCodec (org.bson.codecs.RawBsonDocumentCodec)2 BasicOutputBuffer (org.bson.io.BasicOutputBuffer)2