org.bson.json.JsonWriterSettings Java Examples

The following examples show how to use org.bson.json.JsonWriterSettings. 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: MongoDocumentDb.java    From mdw with Apache License 2.0 6 votes vote down vote up
@Override
public String getDocumentContent(String ownerType, Long documentId) {
    CodeTimer timer = new CodeTimer("Load from documentDb", true);
    try {
        MongoDatabase mongoDb =  getMongoDb();
        if (mongoDb != null) {
            MongoCollection<Document> mongoCollection = mongoDb.getCollection(getCollectionName(ownerType));
            org.bson.Document mongoQuery = new org.bson.Document("document_id", documentId);
            org.bson.Document c = mongoCollection.find(mongoQuery).limit(1).projection(fields(include("CONTENT", "isJSON"), excludeId())).first();
            if (c == null) {
                return null;
            } else if (c.getBoolean("isJSON", false)) {
                boolean isIndent = PropertyManager.getBooleanProperty(PropertyNames.MDW_MONGODB_FORMAT_JSON , false);
                return decodeMongoDoc(c.get("CONTENT", org.bson.Document.class)).toJson(JsonWriterSettings.builder().indent(isIndent).build());
            } else {
                return c.getString("CONTENT");
            }
        }
        return null;
    }
    finally {
        timer.stopAndLogTiming(null);
    }
}
 
Example #2
Source File: GetMongo.java    From nifi with Apache License 2.0 6 votes vote down vote up
private String buildBatch(List<Document> documents, String jsonTypeSetting, String prettyPrintSetting) throws IOException {
    StringBuilder builder = new StringBuilder();
    for (int index = 0; index < documents.size(); index++) {
        Document document = documents.get(index);
        String asJson;
        if (jsonTypeSetting.equals(JSON_TYPE_STANDARD)) {
            asJson = getObjectWriter(objectMapper, prettyPrintSetting).writeValueAsString(document);
        } else {
            asJson = document.toJson(new JsonWriterSettings(true));
        }
        builder
                .append(asJson)
                .append( (documents.size() > 1 && index + 1 < documents.size()) ? ", " : "" );
    }

    return "[" + builder.toString() + "]";
}
 
Example #3
Source File: BsonToJsonLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenBsonDocument_whenUsingRelaxedJsonTransformation_thenJsonDateIsObjectIsoDate() {
   
    String json = null;
    try (MongoClient mongoClient = new MongoClient()) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
        Document bson = mongoDatabase.getCollection("Books").find().first();
        json = bson.toJson(JsonWriterSettings
            .builder()
            .outputMode(JsonMode.RELAXED)
            .build());
    }
    
    String expectedJson = "{\"_id\": \"isbn\", " + 
        "\"className\": \"com.baeldung.bsontojson.Book\", " + 
        "\"title\": \"title\", " + 
        "\"author\": \"author\", " + 
        "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + 
        "\"name\": \"publisher\"}, " + 
        "\"price\": 3.95, " + 
        "\"publishDate\": {\"$date\": \"2020-01-01T17:13:32Z\"}}";

    assertNotNull(json);
    
    assertEquals(expectedJson, json);
}
 
Example #4
Source File: BsonToJsonLiveTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenBsonDocument_whenUsingCustomJsonTransformation_thenJsonDateIsStringField() {

    String json = null;
    try (MongoClient mongoClient = new MongoClient()) {
        MongoDatabase mongoDatabase = mongoClient.getDatabase(DB_NAME);
        Document bson = mongoDatabase.getCollection("Books").find().first();
        json = bson.toJson(JsonWriterSettings
            .builder()
            .dateTimeConverter(new JsonDateTimeConverter())
            .build());
    }

    String expectedJson = "{\"_id\": \"isbn\", " + 
        "\"className\": \"com.baeldung.bsontojson.Book\", " + 
        "\"title\": \"title\", " + 
        "\"author\": \"author\", " + 
        "\"publisher\": {\"_id\": {\"$oid\": \"fffffffffffffffffffffffa\"}, " + 
        "\"name\": \"publisher\"}, " + 
        "\"price\": 3.95, " + 
        "\"publishDate\": \"2020-01-01T17:13:32Z\"}";

    assertEquals(expectedJson, json);

}
 
Example #5
Source File: QueryAssertion.java    From immutables with Apache License 2.0 6 votes vote down vote up
private static void assertEquals(List<BsonDocument> actual, List<BsonDocument> expected) {
  if (!actual.equals(expected)) {
    final JsonWriterSettings settings = JsonWriterSettings.builder().indent(true).build();
    // outputs Bson in pretty Json format (with new lines)
    // so output is human friendly in IDE diff tool
    final Function<List<BsonDocument>, String> prettyFn = bsons -> bsons.stream()
            .map(b -> b.toJson(settings)).collect(Collectors.joining("\n"));

    // used to pretty print Assertion error
    Assertions.assertEquals(
            prettyFn.apply(expected),
            prettyFn.apply(actual),
            "expected and actual Mongo pipelines do not match");

    Assertions.fail("Should have failed previously because expected != actual is known to be true");
  }
}
 
Example #6
Source File: MongoV4MasterConnectorTest.java    From syncer with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void int64Id() {
  //9007199254740993
  long v = ((long) Math.pow(2, 53)) + 1;
  assertNotEquals(v, (double)v);

  BsonDocument key = new BsonDocument(ID, new BsonInt64(v));
  Object o = gson.fromJson(key.toJson(JsonWriterSettings.builder()
      .objectIdConverter((value, writer) -> writer.writeString(value.toHexString()))
      .build()), Map.class).get(ID);
  assertNotEquals(v, o);
}
 
Example #7
Source File: MongoDbTable.java    From beam with Apache License 2.0 5 votes vote down vote up
@DoFn.ProcessElement
public void processElement(ProcessContext context) {
  context.output(
      context
          .element()
          .toJson(JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).build()));
}
 
Example #8
Source File: JsonBsonDocumentWriter.java    From mongowp with Apache License 2.0 5 votes vote down vote up
@Override
public void writeInto(StringBuilder sink, BsonDocument doc) {
  String json = MongoBsonTranslator.translate(doc)
      .toJson(new JsonWriterSettings(JsonMode.STRICT));

  sink.append(json);
}
 
Example #9
Source File: JsonBsonDocumentWriter.java    From mongowp with Apache License 2.0 4 votes vote down vote up
public String writeIntoString(BsonDocument doc) {
  return MongoBsonTranslator.translate(doc)
      .toJson(new JsonWriterSettings(JsonMode.STRICT));
}
 
Example #10
Source File: MongoAdapterTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a function that checks that a particular MongoDB query
 * has been called.
 *
 * @param expected Expected query (as array)
 * @return validation function
 */
private static Consumer<List> mongoChecker(final String... expected) {
  return actual -> {
    if (expected == null) {
      assertThat("null mongo Query", actual, nullValue());
      return;
    }

    if (expected.length == 0) {
      CalciteAssert.assertArrayEqual("empty Mongo query", expected,
          actual.toArray(new Object[0]));
      return;
    }

    // comparing list of Bsons (expected and actual)
    final List<BsonDocument> expectedBsons = Arrays.stream(expected).map(BsonDocument::parse)
        .collect(Collectors.toList());

    final List<BsonDocument> actualBsons =  ((List<?>) actual.get(0))
        .stream()
        .map(Objects::toString)
        .map(BsonDocument::parse)
        .collect(Collectors.toList());

    // compare Bson (not string) representation
    if (!expectedBsons.equals(actualBsons)) {
      final JsonWriterSettings settings = JsonWriterSettings.builder().indent(true).build();
      // outputs Bson in pretty Json format (with new lines)
      // so output is human friendly in IDE diff tool
      final Function<List<BsonDocument>, String> prettyFn = bsons -> bsons.stream()
          .map(b -> b.toJson(settings)).collect(Collectors.joining("\n"));

      // used to pretty print Assertion error
      assertEquals(
          prettyFn.apply(expectedBsons),
          prettyFn.apply(actualBsons),
          "expected and actual Mongo queries (pipelines) do not match");

      fail("Should have failed previously because expected != actual is known to be true");
    }
  };
}
 
Example #11
Source File: ExampleSlowOpsCache.java    From mongodb-slow-operations-profiler with GNU Affero General Public License v3.0 4 votes vote down vote up
public static void main(String[] args) {
    /*
    $root": {
        "$number": 1,
        "$field": {
          "$date": "2020-04-08T13:07:27.456Z"
        },
        "$list": [
          {
            "$l1": "v1"
          },
          {
            "$l2": "v2"
          }
        ],
        "$array": [
          1,2
        ]
      },
     */
    List<Document> list = Lists.newArrayList();
    list.add(new Document("$l1", "v1"));
    list.add(new Document("$l2", "v2"));
    List<Integer> array = Lists.newArrayList();
    array.add(1);
    array.add(2);

    Document in = new Document("$root",
            new Document("$number", -1)
                    .append("$field", new Date())
                    .append("$list", list)
                    .append("$array", array)
    );

    Document out = ExampleSlowOpsCache.INSTANCE.replaceIllegalChars(in, new Document());

    JsonWriterSettings.Builder settingsBuilder = JsonWriterSettings.builder().indent(true);
    String json = out.toJson(settingsBuilder.build());
    LOG.info(json);


}