@Test public void reorderingDocumentTest() { Document document = new Document(); document.stringProperty = "a nice string"; document.datProperty = new Date(); MongoCollection<Document> documentMongoCollection = mongoClient.getDatabase("test").getCollection("documents").withDocumentClass(Document.class); documentMongoCollection.insertOne(document); Document readDocument = documentMongoCollection.find(Filters.eq("_id", document.getMeta().getId())).first(); Assert.assertEquals(document, readDocument); Codec<Document> documentCodec = codecRegistry.get(Document.class); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); documentCodec.encode(writer, document, EncoderContext.builder().build()); LOGGER.info("The encoded json looks like: {}", stringWriter); }
/** * Testing if List<String> can be decoded into a */ @Test public void testResilience() { Codec<EncodingPojo> encodingPojoCodec = codecRegistry.get(EncodingPojo.class); Codec<DecodingPojo> decodingPojoCodec = codecRegistry.get(DecodingPojo.class); EncodingPojo encodingPojo = new EncodingPojo(); encodingPojo.someList = new ArrayList<>(); encodingPojo.someList.add("string1"); encodingPojo.someList.add("string2"); encodingPojo.someList.add("string3"); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); encodingPojoCodec.encode(writer, encodingPojo, EncoderContext.builder().build()); System.out.println(stringWriter.toString()); DecodingPojo decodingPojo = decodingPojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); Assert.assertNotNull(decodingPojo.someList); assertThat(decodingPojo.someList, instanceOf(ListOfStrings.class)); }
@Test public void basicTest() { BasePojo basePojo = new BasePojo(); basePojo.aString = STRING; Codec<BasePojo> primitivePojoCodec = codecRegistry.get(BasePojo.class); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); primitivePojoCodec.encode(writer, basePojo, EncoderContext.builder().build()); LOGGER.info("The encoded json looks like: {}", stringWriter); BasePojo readBasePojo = primitivePojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); // assert that the modified version was actually written to the database Assert.assertEquals(basePojo, readBasePojo); Assert.assertEquals(MODIFIED_STRING, readBasePojo.aString); }
@Test public void testEnums() { Codec<Pojo> pojoCodec = codecRegistry.get(Pojo.class); LovelyDisplayable lovelyDisplayable = LovelyDisplayable.builder().identityProperty("foo").build(); Pojo pojo = Pojo.builder() .simpleEnumProperty(EnumA.TYPE1) .displayable(Arrays.asList(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable)) .build(); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); pojoCodec.encode(writer, pojo, EncoderContext.builder().build()); System.out.println(stringWriter.toString()); Pojo decodedPojo = pojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); MatcherAssert.assertThat(decodedPojo.getDisplayable(), IsIterableContainingInOrder.contains(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable)); }
@Test public void testDifferentTypes() { Codec<Pojo> pojoCodec = codecRegistry.get(Pojo.class); CustomType<String> customTypeString = new CustomType("A custom string type"); String[] strings = {"a", "nice", "list", "of", "strings"}; customTypeString.addAll(Arrays.asList(strings)); customTypeString.setInnerType(new InnerType<>("String value")); CustomType<Integer> customTypeInteger = new CustomType("A custom integer type"); Integer[] integers = {1, 42, 66, 89}; customTypeInteger.addAll(Arrays.asList(integers)); customTypeInteger.setInnerType(new InnerType<>(11234567)); String[] stringsForSet = {"Tee", "Brot", "Butter"}; Pojo pojo = Pojo.builder() .customTypeString(customTypeString) .customTypeInteger(customTypeInteger) .name("aName") .strings(new HashSet<>(Arrays.asList(stringsForSet))) .build(); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); pojoCodec.encode(writer, pojo, EncoderContext.builder().build()); System.out.println(stringWriter.toString()); Pojo decodedPojo = pojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); System.out.println(decodedPojo); Assert.assertNotNull(decodedPojo); MatcherAssert.assertThat(decodedPojo.getCustomTypeString(), CoreMatchers.hasItems(strings)); MatcherAssert.assertThat(decodedPojo.getCustomTypeInteger(), CoreMatchers.hasItems(integers)); MatcherAssert.assertThat(decodedPojo.getStrings(), CoreMatchers.hasItems(stringsForSet)); }
@Test public void basicTest() throws JSONException { BasePojo basePojo = new BasePojo(); basePojo.encodeNullsFalseDecodeUndefined_CODEC = null; // encode to undefined basePojo.encodeNullsFalseDecodeUndefined_KEEP_POJO_DEFAULT = null; // encode with null value set basePojo.encodeNullsShouldDecodeToNull = null; // encode with null value set Codec<BasePojo> primitivePojoCodec = codecRegistry.get(BasePojo.class); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); primitivePojoCodec.encode(writer, basePojo, EncoderContext.builder().build()); LOGGER.info("The encoded json looks like: {}", stringWriter); BasePojo readBasePojo = primitivePojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); JSONAssert.assertEquals(stringWriter.toString(), "{\n" + " \"encodeNullsTrue\" : null,\n" + " \"encodeNullHandlingStrategy_CODEC\" : [],\n" + " \"encodeNullsShouldDecodeToNull\" : null\n" + "}", true); Assert.assertNull(readBasePojo.encodeNullsFalse); Assert.assertNull(readBasePojo.aString); Assert.assertNull(readBasePojo.encodeNullsTrue); MatcherAssert.assertThat(readBasePojo.encodeNullHandlingStrategy_CODEC, empty()); MatcherAssert.assertThat(readBasePojo.encodeNullsFalseDecodeUndefined_CODEC, empty()); Assert.assertEquals(readBasePojo.encodeNullsFalseDecodeUndefined_KEEP_POJO_DEFAULT, Arrays.asList(new PojoProperty())); Assert.assertNull(readBasePojo.encodeNullsShouldDecodeToNull); }
@Test public void genericTest() { IntegerType integerType = new IntegerType(); integerType.anyType = INTEGER; Codec<IntegerType> integerTypeCodec = codecRegistry.get(IntegerType.class); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); integerTypeCodec.encode(writer, integerType, EncoderContext.builder().build()); LOGGER.info("The encoded json looks like: {}", stringWriter); IntegerType readIntegerType = integerTypeCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); Assert.assertEquals(integerType, readIntegerType); }
@Override public String writeAsJsonStr(Object object) { if (object == null) { return null; } StringWriter writer = new StringWriter(); JsonWriterSettings jsonWriterSettings = bsonMapperConfig.getJsonWriterSettings(); BsonWriter bsonWriter = new JsonWriter(writer, jsonWriterSettings == null ? new JsonWriterSettings() : jsonWriterSettings); BsonValueConverterRepertory.getBsonDocumentConverter().encode(bsonWriter, object); return writer.toString(); }
@Override public Object execute() throws Exception { MongoDatabase adminDatabase = mongoService.getMongoClient().getDatabase(database); //MongoCollection mongoCollection = adminDatabase.getCollection(collection); Document document = adminDatabase.runCommand(new Document("collStats", collection)); System.out.println(document.toJson(new JsonWriterSettings(true))); return null; }
@Override public Object execute() throws Exception { MongoDatabase adminDatabase = mongoService.getMongoClient().getDatabase(database); Document document = adminDatabase.runCommand(new Document("dbStats", 1)); System.out.println(document.toJson(new JsonWriterSettings(true))); return null; }
@Override public Object execute() throws Exception { MongoDatabase adminDatabase = mongoService.getMongoClient().getDatabase("admin"); Document document = adminDatabase.runCommand(new Document("serverStatus", 1)); System.out.println(document.toJson(new JsonWriterSettings(true))); return null; }
public Document loadDocument(Long documentId, boolean forUpdate) throws SQLException { String query = "select CREATE_DT, MODIFY_DT, DOCUMENT_TYPE, OWNER_TYPE, OWNER_ID " + "from DOCUMENT where DOCUMENT_ID = ?" + (forUpdate ? " for update" : ""); ResultSet rs = db.runSelect(query, documentId); if (rs.next()) { Document vo = new Document(); vo.setDocumentId(documentId); vo.setCreateDate(rs.getTimestamp("CREATE_DT")); vo.setModifyDate(rs.getTimestamp("MODIFY_DT")); vo.setDocumentType(rs.getString("DOCUMENT_TYPE")); vo.setOwnerType(rs.getString("OWNER_TYPE")); vo.setOwnerId(rs.getLong("OWNER_ID")); boolean foundInMongo = false; if (DatabaseAccess.getMongoDb() != null) { CodeTimer timer = new CodeTimer("Load mongodb doc", true); MongoCollection<org.bson.Document> mongoCollection = DatabaseAccess.getMongoDb().getCollection(vo.getOwnerType()); org.bson.Document mongoQuery = new org.bson.Document("document_id", vo.getDocumentId()); org.bson.Document c = mongoCollection.find(mongoQuery).limit(1).projection(fields(include("CONTENT","isJSON"), excludeId())).first(); if (c != null) { if (c.getBoolean("isJSON", false)) vo.setContent(DatabaseAccess.decodeMongoDoc(c.get("CONTENT", org.bson.Document.class)).toJson(new JsonWriterSettings(true))); else vo.setContent(c.getString("CONTENT")); foundInMongo = true; } timer.stopAndLogTiming(null); } if (!foundInMongo) { query = "select CONTENT from DOCUMENT_CONTENT where DOCUMENT_ID = ?"; rs = db.runSelect(query, documentId); if (rs.next()) vo.setContent(rs.getString("CONTENT")); } return vo; } else { throw new SQLException("Document with ID " + documentId + " does not exist"); } }
@Test void encode() throws IOException { assertEquals(Sets.newHashSet(TestEntityChild.TestEnum.class), builder.enumCodecFields.keySet()); StringWriter writer = new StringWriter(); TestEntity entity = new TestEntity(); entity.id = new ObjectId("5627b47d54b92d03adb9e9cf"); entity.booleanField = 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 TestEntityChild(); entity.child.enumField = TestEntityChild.TestEnum.ITEM1; entity.child.enumListField = Lists.newArrayList(TestEntityChild.TestEnum.ITEM2); entity.listField = Lists.newArrayList("V1", "V2"); entity.mapField = Maps.newHashMap(); entity.mapField.put("K1", "V1"); entity.mapField.put("K2", "V2"); encoder.encode(new JsonWriter(writer, JsonWriterSettings.builder().indent(true).build()), entity); ObjectMapper mapper = new ObjectMapper(); JsonNode expectedEntityNode = mapper.readTree(ClasspathResources.text("mongo-test/entity.json")); JsonNode entityNode = mapper.readTree(writer.toString()); assertEquals(expectedEntityNode, entityNode); }
public JsonWriter(final Writer writer, final JsonWriterSettings settings) { super(writer, settings); this.settings = settings; if (settings.getOutputMode().equals(JsonMode.SHELL)) throw new IllegalArgumentException("JsonMode must not be SHELL"); setContext(new Context(null, BsonContextType.TOP_LEVEL, "")); }
@Override public String generateResponse(MetricRegistry registry) throws IOException { BsonDocument document = MetricsJsonGenerator.generateMetricsBson(registry, TimeUnit.SECONDS, TimeUnit.MILLISECONDS); return document.toJson( JsonWriterSettings.builder().outputMode(JsonMode.RELAXED).indent(true).build() ); }
public CustomStateWriter(Writer writer, JsonWriterSettings settings) { super(writer, settings); }
@Test public void basicTest() { BasePojo basePojo = new BasePojo(); basePojo.aString = STRING; basePojo.aPrimitiveByte = PRIMITIVE_BYTE; basePojo.aPrimitiveChar = PRIMITIVE_CHAR; basePojo.aPrimitiveDouble = PRIMITIVE_DOUBLE; basePojo.aPrimitiveShort = PRIMITIVE_SHORT; basePojo.aPrimitiveLong = PRIMITIVE_LONG; basePojo.aPrimitiveFloat = PRIMITIVE_FLOAT; basePojo.aPrimitiveInt = PRIMITIVE_INT; basePojo.aByte = BYTE; basePojo.aCharacter = CHARACTER; basePojo.aDouble = DOUBLE; basePojo.aShort = SHORT; basePojo.aLong = LONG; basePojo.aFloat = FLOAT; basePojo.anInteger = INTEGER; basePojo.strings = STRINGS; basePojo.primitiveFloats = PRIMITIVE_FLOATS; basePojo.primitiveInts = PRIMITIVE_INTS; basePojo.primitiveLongs = PRIMITIVE_LONGS; basePojo.primitiveChars = PRIMITIVE_CHARS; basePojo.primitiveShorts = PRIMITIVE_SHORTS; basePojo.primitiveBytes = PRIMITIVE_BYTES; basePojo.primitiveDoubles = PRIMITIVE_DOUBLES; basePojo.floats = FLOATS; basePojo.integers = INTEGERS; basePojo.longs = LONGS; basePojo.characters = CHARACTERS; basePojo.shorts = SHORTS; basePojo.bytes = BYTES; basePojo.doubles = DOUBLES; Codec<BasePojo> primitivePojoCodec = codecRegistry.get(BasePojo.class); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); primitivePojoCodec.encode(writer, basePojo, EncoderContext.builder().build()); LOGGER.info("The encoded json looks like: {}", stringWriter); BasePojo readBasePojo = primitivePojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); Assert.assertEquals(basePojo, readBasePojo); }
public JsonWriterSettings getJsonWriterSettings() { return jsonWriterSettings; }
public BsonMapperConfigBuilder setJsonWriterSettings(JsonWriterSettings jsonWriterSettings) { this.jsonWriterSettings = jsonWriterSettings; return this; }
@Override public String toJson(JsonWriterSettings writerSettings) { return innerBsonDocument.toJson(writerSettings); }
@Override public String toJson(JsonWriterSettings writerSettings, Encoder<Document> encoder) { throw new UnsupportedOperationException("inner bsonDocument not support toJson(encoder)."); }
protected String toJsonSearchString(Expression<?> expression) { Bson bson = (Bson) this.serializer.handle(expression); return bson.toBsonDocument(Document.class, codecRegistry).toJson(new JsonWriterSettings(true)); }
public static String formatJson(Document doc) { return doc.toJson(new JsonWriterSettings(JsonMode.SHELL, true)); }
@Test public void bsonDocumentShellTest() { assertNotNull(bsonDocument); assertEquals("{\"_id\":\"5662e5798172910f5a925a43\", \"date\":\"2015-12-05T13:26:23.184\", \"pattern\":\"\\\\d/i\", \"pattern2\":\"\\\\s\", \"long\":9223372036854775807, \"null\":null, \"double\":1.0, \"string\":\"thiago\", \"boolean\":true, \"doc\":{\"key\":\"value\"}, \"list\":[\"value\"], \"map\":{\"key\":\"value\"}}", parse(bsonDocument.toJson(new JsonWriterSettings(JsonMode.SHELL)))); }
@Test public void documentStrictTest() { assertNotNull(document); assertEquals("{\"_id\":\"5662e5798172910f5a925a43\", \"date\":\"2015-12-05T13:26:23.184\", \"pattern\":\"\\\\d/i\", \"pattern2\":\"\\\\s\", \"long\":9223372036854775807, \"null\":null, \"double\":1.0, \"string\":\"thiago\", \"boolean\":true, \"doc\":{\"key\":\"value\"}, \"list\":[\"value\"], \"map\":{\"key\":\"value\"}}", parse(document.toJson(new JsonWriterSettings(JsonMode.STRICT)))); }
@Test public void documentShellTest() { assertNotNull(document); assertEquals("{\"_id\":\"5662e5798172910f5a925a43\", \"date\":\"2015-12-05T13:26:23.184\", \"pattern\":\"\\\\d/i\", \"pattern2\":\"\\\\s\", \"long\":9223372036854775807, \"null\":null, \"double\":1.0, \"string\":\"thiago\", \"boolean\":true, \"doc\":{\"key\":\"value\"}, \"list\":[\"value\"], \"map\":{\"key\":\"value\"}}", parse(document.toJson(new JsonWriterSettings(JsonMode.SHELL)))); }
public JsonWriter(Writer writer) { this(writer, new JsonWriterSettings()); }