org.bson.BsonWriter Java Examples

The following examples show how to use org.bson.BsonWriter. 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: BsonParserTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * write with BSON read with jackson.
 * inverse of {@link #jacksonThenBson(String)}
 */
private void bsonThenJackson(String json) throws IOException {
  ObjectNode toWrite = maybeWrap(mapper.readTree(json));

  BasicOutputBuffer buffer = new BasicOutputBuffer();
  BsonWriter writer = new BsonBinaryWriter(buffer);

  // write with BSON
  BsonDocument expected = BsonDocument.parse(toWrite.toString());
  MongoClientSettings.getDefaultCodecRegistry().get(BsonDocument.class)
          .encode(writer, expected, EncoderContext.builder().build());

  BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray()));
  IOContext ioContext = new IOContext(new BufferRecycler(), null, false);
  BsonParser parser = new BsonParser(ioContext, 0, reader);

  // read with jackson
  BsonDocument actual = BsonDocument.parse(mapper.readValue(parser, JsonNode.class).toString());

  if (!actual.equals(expected)) {
     check(maybeUnwrap(actual)).is(maybeUnwrap(expected));
     Assertions.fail("Should have failed before");
  }
}
 
Example #2
Source File: CenterFilter.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext context) {
    writer.writeStartDocument(field(mapper));
    writer.writeStartDocument("$geoWithin");

    writer.writeStartArray(getFilterName());
    Point center = getValue();
    writer.writeStartArray();
    for (final Double value : center.getPosition().getValues()) {
        writer.writeDouble(value);
    }
    writer.writeEndArray();
    writer.writeDouble(radius);
    writer.writeEndArray();

    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #3
Source File: GroupCodec.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final Group group, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    GroupId id = group.getId();
    if (id != null) {
        writer.writeName("_id");
        if(id.getDocument() != null) {
            id.getDocument().encode(getMapper(), writer, encoderContext);
        } else {
            id.getField().encode(getMapper(), writer, encoderContext);
        }
    } else {
        writer.writeNull("_id");
    }

    Fields<Group> fields = group.getFields();
    if(fields != null) {
        fields.encode(getMapper(), writer, encoderContext);
    }

    writer.writeEndDocument();
}
 
Example #4
Source File: CollectionStatsCodec.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final CollectionStats value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    if (value.getHistogram()) {
        writer.writeStartDocument("latencyStats");
        writer.writeBoolean("histograms", true);
        writer.writeEndDocument();
    }
    if (value.getScale() != null) {
        writer.writeStartDocument("storageStats");
        writer.writeInt32("scale", value.getScale());
        writer.writeEndDocument();
    }
    if (value.getCount()) {
        writer.writeStartDocument("count");
        writer.writeEndDocument();
    }
    writer.writeEndDocument();
}
 
Example #5
Source File: GeoNearCodec.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final GeoNear value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writeNamedValue(writer, "near", value.getPoint(), encoderContext);
    writeNamedValue(writer, "near", value.getCoordinates(), encoderContext);
    writeNamedValue(writer, "key", value.getKey(), encoderContext);
    writeNamedValue(writer, "distanceField", value.getDistanceField(), encoderContext);
    writeNamedValue(writer, "spherical", value.getSpherical(), encoderContext);
    writeNamedValue(writer, "maxDistance", value.getMaxDistance(), encoderContext);
    writeNamedValue(writer, "minDistance", value.getMinDistance(), encoderContext);
    Filter[] filters = value.getFilters();
    if (filters != null) {
        writer.writeStartDocument("query");
        for (final Filter filter : filters) {
            filter.encode(getMapper(), writer, encoderContext);
        }
        writer.writeEndDocument();
    }
    writeNamedValue(writer, "distanceMultiplier", value.getDistanceMultiplier(), encoderContext);
    writeNamedValue(writer, "includeLocs", value.getIncludeLocs(), encoderContext);
    writer.writeEndDocument();
}
 
Example #6
Source File: EntityEncoder.java    From morphia with Apache License 2.0 6 votes vote down vote up
private <S> void encodeValue(final BsonWriter writer, final EncoderContext encoderContext, final FieldModel<S> model,
                             final S propertyValue) {
    if (model.shouldSerialize(propertyValue)) {
        writer.writeName(model.getMappedName());
        if (propertyValue == null) {
            writer.writeNull();
        } else {
            try {
                encoderContext.encodeWithChildContext(model.getCachedCodec(), writer, propertyValue);
            } catch (CodecConfigurationException e) {
                throw new CodecConfigurationException(String.format("Failed to encode '%s'. Encoding '%s' errored with: %s",
                    morphiaCodec.getEntityModel().getName(), model.getMappedName(), e.getMessage()), e);
            }
        }
    }
}
 
Example #7
Source File: BsonParserTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
/**
 * Read and Write in Jackson API but using BSON reader/writer adapters
 */
private void jacksonThenJackson(String json) throws IOException {
  ObjectNode expected = maybeWrap(mapper.readTree(json));

  BasicOutputBuffer buffer = new BasicOutputBuffer();
  BsonWriter writer = new BsonBinaryWriter(buffer);

  BsonGenerator generator = new BsonGenerator(0, writer);
  // write with Jackson
  mapper.writeValue(generator, expected);

  BsonBinaryReader reader = new BsonBinaryReader(ByteBuffer.wrap(buffer.toByteArray()));
  IOContext ioContext = new IOContext(new BufferRecycler(), null, false);
  BsonParser parser = new BsonParser(ioContext, 0, reader);

  // read with Jackson
  JsonNode actual = mapper.readValue(parser, JsonNode.class);
  check(actual).is(expected);
}
 
Example #8
Source File: DateFromParts.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeName(getOperation());
    writer.writeStartDocument();

    ExpressionCodec.writeNamedExpression(mapper, writer, "year", year, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "month", month, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "day", day, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "hour", hour, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "minute", minute, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "second", second, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "millisecond", millisecond, encoderContext);

    ExpressionCodec.writeNamedExpression(mapper, writer, "isoWeekYear", isoWeekYear, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "isoWeek", isoWeek, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "isoDayOfWeek", isoDayOfWeek, encoderContext);

    ExpressionCodec.writeNamedExpression(mapper, writer, "timezone", timezone, encoderContext);

    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #9
Source File: SwitchExpression.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeStartDocument(getOperation());
    writer.writeStartArray("branches");
    for (final Pair branch : branches) {
        writer.writeStartDocument();
        writer.writeName("case");
        branch.caseExpression.encode(mapper, writer, encoderContext);
        writer.writeName("then");
        branch.then.encode(mapper, writer, encoderContext);
        writer.writeEndDocument();
    }
    writer.writeEndArray();
    writeNamedExpression(mapper, writer, "default", defaultCase, encoderContext);
    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #10
Source File: LiteralExpression.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeName(getOperation());
    Codec codec = mapper.getCodecRegistry().get(getValue().getClass());
    encoderContext.encodeWithChildContext(codec, writer, getValue());
    writer.writeEndDocument();
}
 
Example #11
Source File: CoreDocumentSynchronizationConfig.java    From stitch-android-sdk with Apache License 2.0 5 votes vote down vote up
public void encode(
    final BsonWriter writer,
    final CoreDocumentSynchronizationConfig value,
    final EncoderContext encoderContext
) {
  new BsonDocumentCodec().encode(writer, value.toBsonDocument(), encoderContext);
}
 
Example #12
Source File: ArrayFilterExpression.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeStartDocument(getOperation());
    ExpressionCodec.writeNamedExpression(mapper, writer, "input", array, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "cond", conditional, encoderContext);
    ExpressionCodec.writeNamedValue(mapper, writer, "as", as, encoderContext);
    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #13
Source File: StageCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
protected void writeNamedValue(final BsonWriter writer, final String name, final Object value, final EncoderContext encoderContext) {
    if (value != null) {
        writer.writeName(name);
        Codec codec = getCodecRegistry().get(value.getClass());
        encoderContext.encodeWithChildContext(codec, writer, value);
    }
}
 
Example #14
Source File: ReplaceRootCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final ReplaceRoot replace, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeName("newRoot");
    if(replace.getValue() != null) {
        replace.getValue().encode(getMapper(), writer, encoderContext);
    } else {
        replace.getDocument().encode(getMapper(), writer, encoderContext);
    }
    writer.writeEndDocument();
}
 
Example #15
Source File: DateToParts.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeName(getOperation());

    writer.writeStartDocument();
    ExpressionCodec.writeNamedExpression(mapper, writer, "date", date, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "timezone", timeZone, encoderContext);
    ExpressionCodec.writeNamedValue(mapper, writer, "iso8601", iso8601, encoderContext);
    writer.writeEndDocument();

    writer.writeEndDocument();
}
 
Example #16
Source File: UnwindCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final Unwind value, final EncoderContext encoderContext) {
    if(!value.optionsPresent()) {
        value.getPath().encode(getMapper(), writer, encoderContext);
    } else {
        writer.writeStartDocument();
        writeNamedExpression(getMapper(), writer, "path", value.getPath(), encoderContext);
        writeNamedValue(writer, "includeArrayIndex", value.getIncludeArrayIndex(), encoderContext);
        writeNamedValue(writer, "preserveNullAndEmptyArrays", value.getPreserveNullAndEmptyArrays(), encoderContext);
        writer.writeEndDocument();
    }
}
 
Example #17
Source File: AbstractJsonCodec.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
protected void writeInt64(BsonWriter writer, String name, Object value, EncoderContext ctx) {
  if (value instanceof JsonObject) {
    writeNumberLong(writer, name, value, ctx);
  } else {
    writer.writeInt64((long)value);
  }
}
 
Example #18
Source File: JacksonCodecs.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(BsonWriter writer, T value, EncoderContext encoderContext) {
  final BsonGenerator generator = new BsonGenerator(0, mapper, writer);
  try {
    mapper.writerFor(getEncoderClass()).writeValue(generator, value);
  } catch (IOException e) {
    throw new RuntimeException("Couldn't serialize [" + value + "] as " + getEncoderClass(), e);
  }
}
 
Example #19
Source File: GeoWithinFilter.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public final void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext context) {
    writer.writeStartDocument(field(mapper));
    writer.writeStartDocument(getFilterName());
    writer.writeName("$geometry");

    Object shape = getValue();
    Codec codec = mapper.getCodecRegistry().get(shape.getClass());
    codec.encode(writer, shape, context);

    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #20
Source File: AbstractJsonCodec.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
protected void writeArray(BsonWriter writer, String name, Object value, EncoderContext ctx) {
  @SuppressWarnings("unchecked")
  A array = (A) value;

  writer.writeStartArray();
  forEach(array, o -> writeValue(writer, null, o, ctx));
  writer.writeEndArray();
}
 
Example #21
Source File: JacksonCodecRegistry.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(BsonWriter writer, T value, EncoderContext encoderContext) {
  final BsonGenerator generator = new BsonGenerator(0, writer);
  try {
    this.writer.writeValue(generator, value);
  } catch (IOException e) {
    throw new UncheckedIOException("Couldn't serialize [" + value + "] as " + getEncoderClass(), e);
  }
}
 
Example #22
Source File: IfNull.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeName(getOperation());
    writer.writeStartArray();
    writeUnnamedExpression(mapper, writer, target, encoderContext);
    writeUnnamedExpression(mapper, writer, replacement, encoderContext);
    writeUnnamedExpression(mapper, writer, document, encoderContext);
    writer.writeEndArray();
    writer.writeEndDocument();
}
 
Example #23
Source File: ArrayCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void encode(final BsonWriter writer, final Object value, final EncoderContext encoderContext) {
    writer.writeStartArray();
    int length = Array.getLength(value);
    for (int i = 0; i < length; i++) {
        Object element = Array.get(value, i);
        Codec codec = mapper.getCodecRegistry().get(element.getClass());
        codec.encode(writer, element, encoderContext);
    }
    writer.writeEndArray();
}
 
Example #24
Source File: ConvertExpression.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeStartDocument(getOperation());
    ExpressionCodec.writeNamedExpression(mapper, writer, "input", input, encoderContext);
    ExpressionCodec.writeNamedValue(mapper, writer, "to", to.getName(), encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "onError", onError, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "onNull", onNull, encoderContext);
    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #25
Source File: SortCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final Sort value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    for (final SortType sort : value.getSorts()) {
        writer.writeName(sort.getField());
        sort.getDirection().encode(writer);
    }
    writer.writeEndDocument();
}
 
Example #26
Source File: DateFromString.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeStartDocument(getOperation());

    ExpressionCodec.writeNamedExpression(mapper, writer, "dateString", dateString, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "format", format, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "timezone", timeZone, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "onError", onError, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "onNull", onNull, encoderContext);

    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #27
Source File: BsonCodecRepoTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(BsonWriter writer, Somebody value, EncoderContext encoderContext) {
  writer.writeStartDocument();
  writer.writeObjectId("_id", value.id());
  writer.writeString("prop1", value.prop1());
  writer.writeDateTime("dateChanged", value.date().getTime());
  writer.writeEndDocument();
}
 
Example #28
Source File: MorphiaMapPropertyCodecProvider.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final BsonWriter writer, final Map<K, V> map, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    for (final Entry<K, V> entry : map.entrySet()) {
        final K key = entry.getKey();
        writer.writeName((String) Conversions.convert(key, String.class));
        if (entry.getValue() == null) {
            writer.writeNull();
        } else {
            codec.encode(writer, entry.getValue(), encoderContext);
        }
    }
    writer.writeEndDocument();
}
 
Example #29
Source File: ExpressionCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * @param mapper
 * @param writer
 * @param value
 * @param encoderContext
 * @morphia.internal
 */
public static void writeUnnamedValue(final Mapper mapper, final BsonWriter writer, final Object value,
                                     final EncoderContext encoderContext) {
    if (value != null) {
        Codec codec = mapper.getCodecRegistry().get(value.getClass());
        encoderContext.encodeWithChildContext(codec, writer, value);
    }
}
 
Example #30
Source File: TypedArrayCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final BsonWriter writer, final Object value, final EncoderContext encoderContext) {
    writer.writeStartArray();
    int length = Array.getLength(value);
    for (int i = 0; i < length; i++) {
        getCodec().encode(writer, Array.get(value, i), encoderContext);
    }
    writer.writeEndArray();
}