Java 类org.bson.json.JsonWriter 实例源码

项目:polymorphia    文件:CodecResolverTest.java   
@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);

}
项目:polymorphia    文件:ListTypeCodecTest.java   
/**
 * 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));
}
项目:polymorphia    文件:PreSaveHookTest.java   
@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);
}
项目:polymorphia    文件:TestEnums.java   
@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));

}
项目:mongowg    文件:DefaultDomainCodecTest.java   
@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());
}
项目:lambdamatic-project    文件:DocumentCodecTest.java   
private void shouldEncodeDocument()
    throws UnsupportedEncodingException, IOException, JSONException {
  Assume.assumeThat(javaObject, CoreMatchers.instanceOf(Foo.class));
  // given
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final BsonWriter bsonWriter = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  final EncoderContext context =
      EncoderContext.builder().isEncodingCollectibleDocument(true).build();
  // when
  new DocumentCodec<Foo>(Foo.class, DEFAULT_CODEC_REGISTRY).encode(bsonWriter, (Foo) javaObject,
      context);
  // then
  final String actualJson = IOUtils.toString(outputStream.toByteArray(), "UTF-8");
  LOGGER.debug("Comparing \nexpected: {} vs \nactual: {}", jsonValue, actualJson);
  JSONAssert.assertEquals(jsonValue, actualJson, true);
}
项目:lambdamatic-project    文件:FilterExpressionCacheTest.java   
private void shouldEncodeFilterExpression(final String stringField, final int primitiveIntField,
    final EnumFoo enumFoo) throws UnsupportedEncodingException, IOException, JSONException {
  // given
  final SerializablePredicate<QFoo> expr = ((QFoo foo) -> foo.stringField.equals(stringField)
      || foo.primitiveIntField.equals(primitiveIntField) || foo.enumFoo.equals(enumFoo));
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final BsonWriter bsonWriter = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  final EncoderContext context =
      EncoderContext.builder().isEncodingCollectibleDocument(true).build();
  // when
  new FilterExpressionCodec().encode(bsonWriter, expr, context);
  // then
  final String actual = IOUtils.toString(outputStream.toByteArray(), "UTF-8");
  final String expected = "{$or: [{primitiveIntField: " + primitiveIntField + "}, {enumFoo: '"
      + enumFoo + "'}, {stringField: '" + stringField + "'}]}";
  LOGGER.debug("Comparing \n{} vs \n{}", expected, actual);
  JSONAssert.assertEquals(expected, actual, false);
}
项目:cherimodata    文件:_DeEncoding.java   
/**
 * 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() );
}
项目:cherimodata    文件:_DeEncoding.java   
@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 );
}
项目:cherimodata    文件:_DeEncoding.java   
@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 );
}
项目:cherimodata    文件:_DeEncoding.java   
@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 );
}
项目:polymorphia    文件:TypeCodecProviderTest.java   
@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));
}
项目:polymorphia    文件:NullHandlingTest.java   
@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);
}
项目:polymorphia    文件:BaseTest.java   
@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);

}
项目:BsonMapper    文件:DefaultBsonMapper.java   
@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();
}
项目:BsonMapper    文件:BsonDocumentConverterTest.java   
@Test
public void testJsonEncode() throws Exception {
    StringWriter writer = new StringWriter();
    BsonWriter bsonWriter = new JsonWriter(writer);
    BsonValueConverterRepertory.getBsonDocumentConverter().encode(bsonWriter, getObject());
    System.out.println(writer.toString());
}
项目:core-ng-project    文件:EntityEncoderBuilderTest.java   
@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);
}
项目:mongowg    文件:BlockVectorCodecTest.java   
@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);
}
项目:mongowg    文件:BlockVector2DCodecTest.java   
@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);
}
项目:mongowg    文件:ProcessingProtectedRegionCodecTest.java   
@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);
}
项目:mongowg    文件:ProcessingProtectedRegionCodecTest.java   
@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);
}
项目:mongowg    文件:ProcessingProtectedRegionCodecTest.java   
@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);
}
项目:lambdamatic-project    文件:DocumentBinaryTypeCodecTest.java   
private void shouldEncodeDocument()
    throws UnsupportedEncodingException, IOException, JSONException {
  Assume.assumeThat(javaObject, CoreMatchers.instanceOf(Foo.class));
  // given
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final JsonWriter jsonWriter = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  final EncoderContext context =
      EncoderContext.builder().isEncodingCollectibleDocument(true).build();
  // when
  new DocumentCodec<Foo>(Foo.class, DEFAULT_CODEC_REGISTRY).encode(jsonWriter, (Foo) javaObject, context);
  // then
  final String actualJson = IOUtils.toString(outputStream.toByteArray(), "UTF-8");
  LOGGER.debug("Comparing \nexpected: {} vs \nactual: {}", expectation.toJson(), actualJson);
  JSONAssert.assertEquals(expectation.toJson(), actualJson, true);
}
项目:lambdamatic-project    文件:ProjectionExpressionCodecTest.java   
private void shouldEncodeProjectionExpression()
    throws UnsupportedEncodingException, IOException, JSONException {
  // given
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final BsonWriter bsonWriter = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  final EncoderContext context =
      EncoderContext.builder().isEncodingCollectibleDocument(true).build();
  // when
  codec.encode(bsonWriter, projectionExpression, context);
  // then
  final String actual = IOUtils.toString(outputStream.toByteArray(), "UTF-8");
  LOGGER.debug("Output JSON: {}", actual);
  JSONAssert.assertEquals(jsonString, actual, true);
}
项目:lambdamatic-project    文件:FilterExpressionCodecTest.java   
private void shouldEncodeFilterExpression()
    throws UnsupportedEncodingException, IOException, JSONException {
  // given
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final BsonWriter bsonWriter = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  final EncoderContext context =
      EncoderContext.builder().isEncodingCollectibleDocument(true).build();
  // when
  new FilterExpressionCodec().encode(bsonWriter, expr, context);
  // then
  final String actual = IOUtils.toString(outputStream.toByteArray(), "UTF-8");
  LOGGER.debug("Comparing \nexpected: {}\nresult:   {}", expectedJSON.replaceAll(" ", ""),
      actual.replaceAll(" ", ""));
  JSONAssert.assertEquals(expectedJSON, actual, false);
}
项目:lambdamatic-project    文件:UpdateExpressionCodecTest.java   
private void shouldEncodeUpdateExpression()
    throws UnsupportedEncodingException, IOException, JSONException {
  // given
  final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  final BsonWriter bsonWriter = new JsonWriter(new OutputStreamWriter(outputStream, "UTF-8"));
  final EncoderContext context =
      EncoderContext.builder().isEncodingCollectibleDocument(true).build();
  // when
  codec.encode(bsonWriter, updateExpression, context);
  // then
  final String actual = IOUtils.toString(outputStream.toByteArray(), "UTF-8");
  LOGGER.debug("Output JSON: {}", actual);
  JSONAssert.assertEquals(jsonString, actual, true);
}
项目:lambdamatic-project    文件:BaseLambdaExpressionCodec.java   
@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);
  }
}
项目:lambdamatic-project    文件:DocumentCodec.java   
/**
 * 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);
  }
}
项目:cherimodata    文件:EntityCodec.java   
public String asString( T value )
{
    try (StringWriter swriter = new StringWriter(); JsonWriter writer = new JsonWriter( swriter ))
    {
        encode( writer, value, false, Lists.<T> newArrayList() );
        return swriter.toString();
    }
    catch ( IOException e )
    {
        Throwables.propagate( e );
        return null;
    }
}
项目:cherimodata    文件:_DeEncoding.java   
/**
 * 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() );
}
项目:cherimodata    文件:_DateTimeCodec.java   
@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 ) ) );
    }
}
项目:polymorphia    文件:BaseTest.java   
@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);
}
项目:querydsl-mongodb-async    文件:BsonQueryTest.java   
@Test
public void test() {
    JsonWriter writer = new JsonWriter(new PrintWriter(System.out));
    Bson eq = Filters.eq("com.value", "123");
    System.out.println(eq);
}