org.bson.json.JsonReader Java Examples

The following examples show how to use org.bson.json.JsonReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a request against Stitch using the provided {@link StitchAuthRequest} object,
 * and decodes the response using the provided result decoder.
 *
 * @param stitchReq The request to perform.
 * @return The response to the request, successful or not.
 */
public <T> T doAuthenticatedRequest(final StitchAuthRequest stitchReq,
                                    final Decoder<T> resultDecoder) {
  final Response response = doAuthenticatedRequest(stitchReq);
  try {
    final String bodyStr = IoUtils.readAllToString(response.getBody());
    final JsonReader bsonReader = new JsonReader(bodyStr);

    // We must check this condition because the decoder will throw trying to decode null
    if (bsonReader.readBsonType() == BsonType.NULL) {
      return null;
    }
    return resultDecoder.decode(bsonReader, DecoderContext.builder().build());
  } catch (final Exception e) {
    throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR);
  }
}
 
Example #2
Source File: CoreStitchAuth.java    From stitch-android-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Performs a request against Stitch using the provided {@link StitchAuthRequest} object, and
 * decodes the JSON body of the response into a T value as specified by the provided class type.
 * The type will be decoded using the codec found for T in the codec registry given.
 * If the provided type is not supported by the codec registry to be used, the method will throw
 * a {@link org.bson.codecs.configuration.CodecConfigurationException}.
 *
 * @param stitchReq     the request to perform.
 * @param resultClass   the class that the JSON response should be decoded as.
 * @param codecRegistry the codec registry used for de/serialization.
 * @param <T>           the type into which the JSON response will be decoded into.
 * @return the decoded value.
 */
public <T> T doAuthenticatedRequest(
    final StitchAuthRequest stitchReq,
    final Class<T> resultClass,
    final CodecRegistry codecRegistry
) {
  final Response response = doAuthenticatedRequest(stitchReq);

  try {
    final String bodyStr = IoUtils.readAllToString(response.getBody());
    final JsonReader bsonReader = new JsonReader(bodyStr);

    // We must check this condition because the decoder will throw trying to decode null
    if (bsonReader.readBsonType() == BsonType.NULL) {
      return null;
    }

    final CodecRegistry newReg =
            CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);
    return newReg.get(resultClass).decode(bsonReader, DecoderContext.builder().build());
  } catch (final Exception e) {
    throw new StitchRequestException(e, StitchRequestErrorCode.DECODING_ERROR);
  }
}
 
Example #3
Source File: EntityDecoderBuilderTest.java    From core-ng-project with Apache License 2.0 6 votes vote down vote up
@Test
void decode() {
    String entityJSON = ClasspathResources.text("mongo-test/entity.json");

    TestEntity entity = decoder.decode(new JsonReader(entityJSON));

    assertThat(entity.id).isEqualTo(new ObjectId("5627b47d54b92d03adb9e9cf"));
    assertThat(entity.stringField).isEqualTo("string");
    assertThat(entity.longField).isEqualTo(325);
    assertThat(entity.zonedDateTimeField).isEqualTo("2016-09-01T15:00:00Z");
    assertThat(entity.child.enumField).isEqualTo(TestEnum.ITEM1);
    assertThat(entity.listField).containsExactly("V1", "V2");
    assertThat(entity.nullChild).isNull();

    assertThat(entity.mapField).containsOnly(entry("K1", "V1"), entry("K2", "V2"));
    assertThat(entity.enumMapField).containsEntry(TestEnum.ITEM1, "V1");
    assertThat(entity.mapListField).containsOnly(entry("K1", List.of("V1")), entry("K2", List.of("V2", "V3")));
}
 
Example #4
Source File: EntityEncoderBuilderTest.java    From core-ng-project with Apache License 2.0 5 votes vote down vote up
@Test
void encode() {
    assertThat(builder.enumCodecFields.keySet()).containsExactly(TestEnum.class);

    TestEntity entity = new TestEntity();
    entity.id = new ObjectId("5627b47d54b92d03adb9e9cf");
    entity.booleanField = Boolean.TRUE;
    entity.longField = 325L;
    entity.stringField = "string";
    entity.zonedDateTimeField = ZonedDateTime.of(LocalDateTime.of(2016, 9, 1, 11, 0, 0), ZoneId.of("America/New_York"));
    entity.child = new TestChildEntity();
    entity.child.enumField = TestEnum.ITEM1;
    entity.child.enumListField = List.of(TestEnum.ITEM2);
    entity.listField = List.of("V1", "V2");
    entity.mapField = Map.of("K1", "V1", "K2", "V2");
    entity.enumMapField = Map.of(TestEnum.ITEM1, "V1");
    entity.mapListField = Map.of("K1", List.of("V1"), "K2", List.of("V2", "V3"));

    var bson = new BsonDocument();
    try (var writer = new BsonDocumentWriter(bson)) {
        encoder.encode(writer, entity);
    }

    var expectedBSON = new BsonDocument();
    try (var writer = new BsonDocumentWriter(expectedBSON)) {
        writer.pipe(new JsonReader(ClasspathResources.text("mongo-test/entity.json")));
    }

    assertThat(bson).isEqualTo(expectedBSON);
}
 
Example #5
Source File: SharedFongoResource.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean doInitialize(
    ResourceSpecifier aSpecifier, Map<String, Object> aAdditionalParams)
    throws ResourceInitializationException {
  // Work whether it's a list of DB Objects or a single
  if ("{}".equals(fongoData) || "[]".equals(fongoData) || Strings.isNullOrEmpty(fongoData)) {
    return true;
  }

  if (fongoData.trim().startsWith("[")) {
    CodecRegistry codecRegistry =
        CodecRegistries.fromProviders(
            Arrays.asList(
                new ValueCodecProvider(),
                new BsonValueCodecProvider(),
                new DocumentCodecProvider()));
    JsonReader reader = new JsonReader(fongoData);
    BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry);

    BsonArray docArray = arrayReader.decode(reader, DecoderContext.builder().build());

    for (BsonValue doc : docArray.getValues()) {
      fongo
          .getDatabase(BALEEN)
          .getCollection(fongoCollection)
          .insertOne(Document.parse(doc.asDocument().toJson()));
    }
  } else if (fongoData.trim().startsWith("{")) {
    Document data = Document.parse(fongoData);
    fongo.getDatabase(BALEEN).getCollection(fongoCollection).insertOne(data);
  } else {
    getMonitor().error("Unsupported type");
    throw new ResourceInitializationException();
  }

  return true;
}
 
Example #6
Source File: MongoBsonUtils.java    From mongowp with Apache License 2.0 5 votes vote down vote up
public static BsonValue read(InputStream is) throws IOException {
  String allText =
      CharStreams.toString(new BufferedReader(new InputStreamReader(is, Charsets.UTF_8)));
  JsonReader reader = new JsonReader(allText);

  DecoderContext context = DecoderContext.builder().build();

  return BSON_CODEC.decode(reader, context);
}
 
Example #7
Source File: JsonPoweredTestHelper.java    From mongo-java-driver-rx with Apache License 2.0 4 votes vote down vote up
public static BsonDocument getTestDocument(final File file) throws IOException {
    return new BsonDocumentCodec().decode(new JsonReader(getFileAsString(file)), DecoderContext.builder().build());
}
 
Example #8
Source File: JsonPoweredTestHelper.java    From mongo-java-driver-reactivestreams with Apache License 2.0 4 votes vote down vote up
public static BsonDocument getTestDocument(final File file) throws IOException {
    return new BsonDocumentCodec().decode(new JsonReader(getFileAsString(file)), DecoderContext.builder().build());
}
 
Example #9
Source File: BsonReaderTest.java    From immutables with Apache License 2.0 4 votes vote down vote up
private static void compare(String string) throws IOException {
  JsonElement bson = TypeAdapters.JSON_ELEMENT.read(new BsonReader(new JsonReader(string))); // compare as BSON
  JsonElement gson = TypeAdapters.JSON_ELEMENT.fromJson(string); // compare as JSON
  check(bson).is(gson); // compare the two
}
 
Example #10
Source File: BsonUtils.java    From stitch-android-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Parses the provided extended JSON string and decodes it into a T value as specified by the
 * provided class type. The type will decoded using the codec found for the type in the default
 * codec registry. If the provided type is not supported by the default codec registry, the method
 * will throw a {@link org.bson.codecs.configuration.CodecConfigurationException}.
 *
 * @param json the JSON string to parse.
 * @param valueClass the class that the JSON string should be decoded into.
 * @param <T> the type into which the JSON string is decoded.
 * @return the decoded value.
 */
public static <T> T parseValue(final String json, final Class<T> valueClass) {
  final JsonReader bsonReader = new JsonReader(json);
  bsonReader.readBsonType();
  return DEFAULT_CODEC_REGISTRY
      .get(valueClass)
      .decode(bsonReader, DecoderContext.builder().build());
}
 
Example #11
Source File: BsonUtils.java    From stitch-android-sdk with Apache License 2.0 3 votes vote down vote up
/**
 * Parses the provided extended JSON string and decodes it into a T value as specified by the
 * provided class type. The type will decoded using the codec found for the type in the provided
 * codec registry. If the provided type is not supported by the provided codec registry, the
 * method will throw a {@link org.bson.codecs.configuration.CodecConfigurationException}.
 *
 * @param json the JSON string to parse.
 * @param valueClass the class that the JSON string should be decoded into.
 * @param codecRegistry the codec registry to use to find the codec for the provided class.
 * @param <T> the type into which the JSON string is decoded.
 * @return the decoded value.
 */
public static <T> T parseValue(
    final String json, final Class<T> valueClass, final CodecRegistry codecRegistry) {
  final JsonReader bsonReader = new JsonReader(json);
  bsonReader.readBsonType();
  // We can't detect if their codecRegistry has any duplicate providers. There's also a chance
  // that putting ours first may prevent decoding of some of their classes if for example they
  // have their own way of decoding an Integer.
  final CodecRegistry newReg =
      CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);
  return newReg.get(valueClass).decode(bsonReader, DecoderContext.builder().build());
}
 
Example #12
Source File: BsonUtils.java    From stitch-android-sdk with Apache License 2.0 2 votes vote down vote up
/**
 * Parses the provided extended JSON string and decodes it into a T value as specified by the
 * provided {@link Decoder}.
 *
 * @param json the JSON string to parse.
 * @param valueDecoder the {@link Decoder} to use to convert the BSON value into the type T.
 * @param <T> the type into which the JSON string is decoded.
 * @return the decoded value.
 */
public static <T> T parseValue(final String json, final Decoder<T> valueDecoder) {
  final JsonReader bsonReader = new JsonReader(json);
  bsonReader.readBsonType();
  return valueDecoder.decode(bsonReader, DecoderContext.builder().build());
}