/** * 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 void decode() { String entityJSON = ClasspathResources.text("mongo-test/entity.json"); TestEntity entity = decoder.decode(new JsonReader(entityJSON)); assertEquals(new ObjectId("5627b47d54b92d03adb9e9cf"), entity.id); assertEquals("string", entity.stringField); assertEquals(Long.valueOf(325), entity.longField); assertEquals(ZonedDateTime.of(LocalDateTime.of(2016, 9, 1, 11, 0, 0), ZoneId.of("America/New_York")).toInstant(), entity.zonedDateTimeField.toInstant()); assertEquals(TestEntityChild.TestEnum.ITEM1, entity.child.enumField); assertEquals(2, entity.listField.size()); assertEquals("V1", entity.listField.get(0)); assertEquals("V2", entity.listField.get(1)); assertNull(entity.nullChild); assertEquals("V1", entity.mapField.get("K1")); assertEquals("V2", entity.mapField.get("K2")); }
@Test public void testCodec() throws IOException { Codec<DefaultDomain> codec = DefaultDomainCodec.INSTANCE; DefaultDomain domain = new DefaultDomain(); domain.addPlayer(UUID.randomUUID()); domain.addGroup("test_group"); DefaultDomain other; try (StringWriter sw = new StringWriter()) { codec.encode(new JsonWriter(sw), domain, EncoderContext.builder().build()); other = codec.decode(new JsonReader(sw.toString()), DecoderContext.builder().build()); } Assert.assertEquals(domain.getPlayers(), other.getPlayers()); Assert.assertEquals(domain.getUniqueIds(), other.getUniqueIds()); Assert.assertEquals(domain.getGroups(), other.getGroups()); }
/** * @param json * @return either a BsonDocument or a BsonArray from the json string * @throws JsonParseException */ public static BsonValue parse(String json) throws JsonParseException { if (json == null) { return null; } String trimmed = json.trim(); if (trimmed.startsWith("{")) { try { return BsonDocument.parse(json); } catch (BsonInvalidOperationException ex) { // this can happen parsing a bson type, e.g. // {"$oid": "xxxxxxxx" } // the string starts with { but is not a document return getBsonValue(json); } } else if (trimmed.startsWith("[")) { return BSON_ARRAY_CODEC.decode( new JsonReader(json), DecoderContext.builder().build()); } else { return getBsonValue(json); } }
/** * Tests if de/encoding a simple Entity with only primitive data types work */ @Test public void basicDeEncoding() { EntityCodec codec = new EntityCodec<>( db, EntityFactory.getProperties( PrimitiveEntity.class ) ); PrimitiveEntity pe = instantiate( PrimitiveEntity.class ); pe.setString( "value" ); pe.setInteger( 123 ); StringWriter swriter = new StringWriter(); JsonWriter jwriter = new JsonWriter( swriter ); codec.encode( jwriter, pe, null ); assertJson( sameJSONAs( "{ \"Integer\" : 123, \"string\" : \"value\" }" ), swriter ); JsonReader jreader = new JsonReader( swriter.toString() ); PrimitiveEntity read = decode( codec, jreader, PrimitiveEntity.class ); assertEquals( pe.getString(), read.getString() ); assertEquals( pe.getInteger(), read.getInteger() ); }
@Test public void collectionDeEncoding() { EntityCodec codec = new EntityCodec<>( db, EntityFactory.getProperties( CollectionEntity.class ) ); CollectionEntity ce = instantiate( CollectionEntity.class ); ce.setArrayStrings( new String[] { "one", "two" } ); ce.setStrings( Lists.newArrayList( "three", "four" ) ); StringWriter swriter = new StringWriter(); JsonWriter jwriter = new JsonWriter( swriter ); codec.encode( jwriter, ce, null ); assertJson( sameJSONAs( "{ \"arrayStrings\": [\"one\",\"two\"],\"strings\":[\"three\",\"four\"] }" ), swriter ); JsonReader jreader = new JsonReader( swriter.toString() ); CollectionEntity ceRead = decode( codec, jreader, CollectionEntity.class ); assertJson( sameJSONAs( "{ \"arrayStrings\": [\"one\",\"two\"],\"strings\":[\"three\",\"four\"] }" ), ceRead ); }
@Test public void collectionDeEncodingDB() { EntityCodec codec = new EntityCodec<>( db, EntityFactory.getProperties( Listed.class ) ); Listed listed = factory.create( Listed.class ); listed.setList( Lists.newArrayList( factory.create( PrimitiveEntity.class ).setString( "nested" ) ) ); StringWriter swriter = new StringWriter(); JsonWriter jwriter = new JsonWriter( swriter ); codec.encode( jwriter, listed, null ); assertJson( sameJSONAs( "{ \"list\": [{\"string\": \"nested\"}]}" ), swriter ); JsonReader jsonReader = new JsonReader( swriter.toString() ); Listed read = decode( codec, jsonReader, Listed.class ); assertNotNull( read.getList() ); assertEquals( listed.getList().get( 0 ), read.getList().get( 0 ) ); listed.save(); Listed r = factory.load( Listed.class, listed.get( ID ) ); assertEquals( listed, r ); }
@Test public void enumDeEncoding() { EntityCodec codec = new EntityCodec<>( db, EntityFactory.getProperties( EnumEntity.class ) ); EnumEntity ee = instantiate( EnumEntity.class ); ee.setCategory( EnumEntity.Category.Misc ); StringWriter swriter = new StringWriter(); JsonWriter jwriter = new JsonWriter( swriter ); codec.encode( jwriter, ee, null ); assertJson( sameJSONAs( "{ \"category\": \"Misc\" }" ), swriter ); JsonReader jreader = new JsonReader( swriter.toString() ); EnumEntity eeRead = decode( codec, jreader, EnumEntity.class ); assertEquals( ee, eeRead ); }
@Override public Object parse(String source) throws Exception { char c = source.charAt(0); if (c == '{') { return documentCodec.decode(new JsonReader(source), context); } if (c == '[') { return arrayCodec.decode(new JsonReader(source), context); } throw new IllegalArgumentException("Malformed JSON: " + source); }
public static Object parseValue(final String json) { final JsonReader bsonReader = new JsonReader(json); bsonReader.readBsonType(); final Object decoded = DEFAULT_BSON_TYPE_CODEC_MAP.get(bsonReader.getCurrentBsonType()).decode( bsonReader, DecoderContext.builder().build()); return decoded; }
@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); }
private BsonArray parseJsonArray(String json) { final CodecRegistry codecRegistry = CodecRegistries.fromProviders(Arrays.asList( new ValueCodecProvider(), new BsonValueCodecProvider(), new DocumentCodecProvider())); JsonReader reader = new JsonReader(json); BsonArrayCodec arrayReader = new BsonArrayCodec(codecRegistry); return arrayReader.decode(reader, DecoderContext.builder().build()); }
@Override public <T> T readFrom(String jsonString, Class<T> targetClazz) { if (isStrEmpty(jsonString)) { return null; } checkNotNull(targetClazz, NOT_NULL_MSG); checkIsSupportClazz(targetClazz, NOT_SUPPORT_CLAZZ_MSG + targetClazz.getName()); JsonReader jsonReader = new JsonReader(jsonString); return BsonValueConverterRepertory.getBsonDocumentConverter().decode(jsonReader, targetClazz, bsonMapperConfig); }
@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; }
@Test public void testCodec() throws IOException { Codec<BlockVector> codec = BlockVectorCodec.INSTANCE; BlockVector blockVector = new BlockVector(4, 8, 15); BlockVector other; try (StringWriter sw = new StringWriter()) { codec.encode(new JsonWriter(sw), blockVector, EncoderContext.builder().build()); other = codec.decode(new JsonReader(sw.toString()), DecoderContext.builder().build()); } Assert.assertEquals(blockVector, other); }
@Test public void testCodec() throws IOException { Codec<BlockVector2D> codec = BlockVector2DCodec.INSTANCE; BlockVector2D blockVector = new BlockVector2D(4, 8); BlockVector2D other; try (StringWriter sw = new StringWriter()) { codec.encode(new JsonWriter(sw), blockVector, EncoderContext.builder().build()); other = codec.decode(new JsonReader(sw.toString()), DecoderContext.builder().build()); } Assert.assertEquals(blockVector, other); }
@Test public void testCodecForCuboid() throws IOException { ProtectedRegion region = new ProtectedCuboidRegion("cuboid", new BlockVector(4, 4, 4), new BlockVector(42, 42, 42)); fillRegion(region); ProcessingProtectedRegion container = new ProcessingProtectedRegion(region, "world"); ProcessingProtectedRegion other; try (StringWriter sw = new StringWriter()) { codec.encode(new JsonWriter(sw), container, EncoderContext.builder().build()); other = codec.decode(new JsonReader(sw.toString()), DecoderContext.builder().build()); } Assert.assertEquals(container, other); }
@Test public void testCodecForGlobal() throws IOException { ProtectedRegion region = new GlobalProtectedRegion(GlobalProtectedRegion.GLOBAL_REGION); fillRegion(region); ProcessingProtectedRegion container = new ProcessingProtectedRegion(region, "world"); ProcessingProtectedRegion other; try (StringWriter sw = new StringWriter()) { codec.encode(new JsonWriter(sw), container, EncoderContext.builder().build()); other = codec.decode(new JsonReader(sw.toString()), DecoderContext.builder().build()); } Assert.assertEquals(container, other); }
@Test public void testCodecForPolygonal() throws IOException { ProtectedRegion region = new ProtectedPolygonalRegion("polygon", ImmutableList.of(new BlockVector2D(0, 0), new BlockVector2D(0, 4), new BlockVector2D(4, 4), new BlockVector2D(4, 0)), 0, 64); fillRegion(region); ProcessingProtectedRegion container = new ProcessingProtectedRegion(region, "world"); ProcessingProtectedRegion other; try (StringWriter sw = new StringWriter()) { codec.encode(new JsonWriter(sw), container, EncoderContext.builder().build()); other = codec.decode(new JsonReader(sw.toString()), DecoderContext.builder().build()); } Assert.assertEquals(container, other); }
private void shouldDecodeDocument(boolean loggerEnabled) { // given final BsonReader bsonReader = new JsonReader(jsonValue); final DecoderContext decoderContext = DecoderContext.builder().build(); // when final Foo actual = new DocumentCodec<Foo>(Foo.class, DEFAULT_CODEC_REGISTRY).decode(bsonReader, decoderContext); // then assertEquals(javaObject, actual); }
@Override public void encode(final BsonWriter writer, final T filterExpression, final EncoderContext encoderContext) { final LambdaExpression lambdaExpression = LambdaExpressionAnalyzer.getInstance().analyzeExpression(filterExpression); if (LOGGER.isInfoEnabled()) { final ByteArrayOutputStream jsonOutputStream = new ByteArrayOutputStream(); try (final JsonWriter debugWriter = new JsonWriter(new OutputStreamWriter(jsonOutputStream, "UTF-8"))) { encodeExpression(lambdaExpression, debugWriter, encoderContext); // use an intermediate JsonWriter whose Outputstream can be // retrieved final String jsonContent = IOUtils.toString(jsonOutputStream.toByteArray(), "UTF-8"); LOGGER.info("Bson Expression: {}", jsonContent); try (final JsonReader jsonContentReader = new JsonReader(jsonContent)) { // now, write the document in the target writer writer.pipe(jsonContentReader); writer.flush(); } } catch (IOException e) { throw new ConversionException( "Failed to convert '" + lambdaExpression.toString() + "' to a BSON document", e); } } else { encodeExpression(lambdaExpression, writer, encoderContext); } }
/** * Encodes the given {@code domainObject}, putting the {@code _id} attribute first, followed by * {@code _targetClassName} to be able to decode the BSON/JSON document later, followed by the * other annotated Java attributes. * * {@inheritDoc} */ @Override public void encode(final BsonWriter writer, final DomainType domainObject, final EncoderContext encoderContext) { if (LOGGER.isDebugEnabled()) { final ByteArrayOutputStream jsonOutputStream = new ByteArrayOutputStream(); try (final JsonWriter debugWriter = new JsonWriter(new OutputStreamWriter(jsonOutputStream, "UTF-8"))) { // use an intermediate JsonWriter whose Outputstream can be // retrieved EncoderUtils.encodeDomainObject(debugWriter, domainObject, encoderContext, this.codecRegistry); final String jsonContent = IOUtils.toString(jsonOutputStream.toByteArray(), "UTF-8"); LOGGER.debug("Encoded document: {}", jsonContent); // now, write the document in the target writer try (final JsonReader jsonContentReader = new JsonReader(jsonContent)) { writer.pipe(jsonContentReader); writer.flush(); } } catch (IOException e) { throw new ConversionException( "Failed to convert '" + domainObject.toString() + "' to a BSON document", e); } } else { EncoderUtils.encodeDomainObject(writer, domainObject, encoderContext, this.codecRegistry); } }
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); }
/** * tests if de/encoding a complex (nested) entity works */ @Test public void nestedDeEncoding() { EntityCodec codec = new EntityCodec<>( db, EntityFactory.getProperties( NestedEntity.class ) ); PrimitiveEntity pe = instantiate( PrimitiveEntity.class ); pe.setString( "value" ); pe.setInteger( 123 ); NestedEntity ce = instantiate( NestedEntity.class ); ce.setString( "outer" ); ce.setPE( pe ); StringWriter swriter = new StringWriter(); JsonWriter jwriter = new JsonWriter( swriter ); codec.encode( jwriter, ce, null ); assertJson( sameJSONAs( "{ \"string\" : \"outer\", \"PE\" : { \"Integer\" : 123, \"string\" : \"value\" } }" ), swriter ); JsonReader jreader = new JsonReader( swriter.toString() ); NestedEntity ceRead = decode( codec, jreader, NestedEntity.class ); PrimitiveEntity peRead = ceRead.getPE(); assertEquals( pe.getInteger(), peRead.getInteger() ); assertEquals( pe.getString(), peRead.getString() ); assertEquals( ce.getString(), ceRead.getString() ); }
@Test public void enumDeEncodingUnknownEnum() { EntityCodec codec = new EntityCodec<>( db, EntityFactory.getProperties( EnumEntity.class ) ); JsonReader jreader = new JsonReader( "{ \"category\": \"miscellaneous\" }" ); try { decode( codec, jreader, EnumEntity.class ); fail( "Should throw an exception" ); } catch ( IllegalArgumentException e ) { assertThat( e.getMessage(), containsString( "doesn't match any declared enum value of" ) ); } }
@Test public void dateTimeDeEncoding() throws IOException { DateTimeCodec codec = new DateTimeCodec(); DateTime now = DateTime.now(); try (StringWriter swriter = new StringWriter(); JsonWriter writer = new JsonWriter( swriter )) { codec.encode( writer, now, null ); JsonReader reader = new JsonReader( swriter.toString() ); assertTrue( now.equals( codec.decode( reader, null ) ) ); } }
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 }
public static Iterable parseIterable(final String json) { final JsonReader bsonReader = new JsonReader(json); final Object decoded = DEFAULT_BSON_TYPE_CODEC_MAP.get(BsonType.ARRAY).decode(bsonReader, DecoderContext.builder().build()); return (Iterable) decoded; }
@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 static BsonDocument getTestDocument(final File file) throws IOException { return new BsonDocumentCodec().decode(new JsonReader(getFileAsString(file)), DecoderContext.builder().build()); }
private static BsonArray parseBsonArray(final String json) { return new BsonArrayCodec(CodecRegistries.fromProviders(new BsonValueCodecProvider())).decode(new JsonReader(json), DecoderContext.builder().build()); }
/** * creates an Entity from the given JSON String which is of the given Entity class * * @param clazz entity class the string reflects an instance from * @param json String representation of an instance of the given Entity class * @param <T> Entity class * @return Entity instance representing the given String, with MongoDB reference. Thus being able to perform e.g. * Entity.save() */ public <T extends Entity> T readEntity( Class<T> clazz, String json ) { return new EntityCodec<T>( db, defFactory.create( clazz ) ).decode( new JsonReader( json ), null ); }
/** * creates a list of Entities from the given JSON String, which is of the given Entity class * * @param clazz entity class of the lists string representation * @param json String representation of the entity list * @param <T> Entity class * @return List of entities represented by the given String, with MongoDB reference. This means each entity is able * to be saved, e.g. Entity.save() */ public <T extends Entity> List<T> readList( Class<T> clazz, String json ) { return (List<T>) new EntityCodec<T>( db, defFactory.create( clazz ) ).getCodec( List.class ) .decode( new JsonReader( json ), null ); }