org.bson.codecs.EncoderContext Java Examples

The following examples show how to use org.bson.codecs.EncoderContext. 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: SetEntityOperator.java    From morphia with Apache License 2.0 6 votes vote down vote up
@Override
public OperationTarget toTarget(final PathTarget pathTarget) {
    return new OperationTarget(null, value()) {
        @Override
        public Object encode(final Mapper mapper) {
            MappedClass mappedClass = mapper.getMappedClass(getValue().getClass());
            if (mappedClass.getVersionField() == null) {
                return super.encode(mapper);
            }

            Codec codec = mapper.getCodecRegistry().get(getValue().getClass());
            DocumentWriter writer = new DocumentWriter();

            codec.encode(writer, getValue(), EncoderContext.builder().build());

            Document document = writer.getDocument();
            document.remove(mappedClass.getVersionField().getMappedFieldName());
            return document;
        }
    };
}
 
Example #2
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 #3
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 #4
Source File: JsonObjectCodec.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Override
public BsonValue getDocumentId(JsonObject json) {
  if (!documentHasId(json)) {
    throw new IllegalStateException("The document does not contain an _id");
  }

  Object id = json.getValue(ID_FIELD);
  if (id instanceof String) {
    return new BsonString((String) id);
  }

  BsonDocument idHoldingDocument = new BsonDocument();
  BsonWriter writer = new BsonDocumentWriter(idHoldingDocument);
  writer.writeStartDocument();
  writer.writeName(ID_FIELD);
  writeValue(writer, null, id, EncoderContext.builder().build());
  writer.writeEndDocument();
  return idHoldingDocument.get(ID_FIELD);
}
 
Example #5
Source File: ElemMatchFilter.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));
    if (isNot()) {
        writer.writeStartDocument("$not");
    }
    writer.writeStartDocument(getFilterName());
    List<Filter> filters = (List<Filter>) getValue();
    for (final Filter filter : filters) {
        filter.encode(mapper, writer, context);
    }
    if (isNot()) {
        writer.writeEndDocument();
    }
    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #6
Source File: EntityEncoder.java    From morphia with Apache License 2.0 6 votes vote down vote up
private <S> void encodeIdProperty(final BsonWriter writer, final T instance, final EncoderContext encoderContext,
                                  final FieldModel<S> idModel) {
    if (idModel != null) {
        IdGenerator generator = getIdGenerator();
        if (generator == null) {
            encodeProperty(writer, instance, encoderContext, idModel);
        } else {
            S id = idModel.getAccessor().get(instance);
            if (id == null && encoderContext.isEncodingCollectibleDocument()) {
                id = (S) generator.generate();
                idModel.getAccessor().set(instance, id);
            }
            encodeValue(writer, encoderContext, idModel, id);
        }
    }
}
 
Example #7
Source File: JsonObjectCodecTest.java    From vertx-mongo-client with Apache License 2.0 6 votes vote down vote up
@Test
public void writeDocument_supportObjectId() {
  JsonObjectCodec codec = new JsonObjectCodec(options);

  ObjectId objectId = new ObjectId();
  JsonObject oidJson = new JsonObject();
  oidJson.put(JsonObjectCodec.OID_FIELD, objectId.toHexString());
  JsonObject value = new JsonObject();
  value.put("test", oidJson);

  BsonDocument bsonResult = new BsonDocument();
  BsonDocumentWriter writer = new BsonDocumentWriter(bsonResult);

  codec.writeDocument(writer, "", value, EncoderContext.builder().build());

  BsonValue resultValue = bsonResult.get("test");
  assertEquals(BsonType.OBJECT_ID, resultValue.getBsonType());

  BsonObjectId bsonObjectId = resultValue.asObjectId();

  assertEquals(objectId.toHexString(), bsonObjectId.getValue().toHexString());

}
 
Example #8
Source File: ExpressionsTestBase.java    From morphia with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
protected void assertAndCheckDocShape(final String expectedString, final Expression value, final Object expectedValue) {
    Document expected = Document.parse(expectedString);
    DocumentWriter writer = new DocumentWriter();
    ((Codec) getMapper().getCodecRegistry()
                        .get(MathExpression.class))
        .encode(writer, value, EncoderContext.builder().build());
    Document actual = writer.getDocument();
    assertEquals(0, writer.getDocsLevel());
    assertEquals(0, writer.getArraysLevel());
    assertDocumentEquals(expected, actual);

    Document test = getDs().aggregate(User.class)
                           .project(Projection.of()
                                              .include("test", value))
                           .execute(Document.class)
                           .next();
    Assert.assertEquals(expectedValue, test.get("test"));
}
 
Example #9
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 #10
Source File: CenterCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(final BsonWriter writer, final dev.morphia.query.Shape.Center value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeStartArray(value.getGeometry());

    encodePosition(writer, value.getCenter().getPosition());
    writer.writeDouble(value.getRadius());

    writer.writeEndArray();
    writer.writeEndDocument();
}
 
Example #11
Source File: ReduceExpression.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.writeNamedExpression(mapper, writer, "initialValue", initial, encoderContext);
    ExpressionCodec.writeNamedExpression(mapper, writer, "in", in, encoderContext);
    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #12
Source File: GraphLookupCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
protected void encodeStage(final BsonWriter writer, final GraphLookup value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    if(value.getFrom() != null) {
        writeNamedValue(writer, "from", value.getFrom(), encoderContext);
    } else {
        MongoCollection collection = getMapper().getCollection(value.getFromType());
        writer.writeString("from", collection.getNamespace().getCollectionName());
    }
    writeNamedExpression(getMapper(), writer, "startWith", value.getStartWith(), encoderContext);
    writeNamedValue(writer, "connectFromField", value.getConnectFromField(), encoderContext);
    writeNamedValue(writer, "connectToField", value.getConnectToField(), encoderContext);
    writeNamedValue(writer, "as", value.getAs(), encoderContext);
    writeNamedValue(writer, "maxDepth", value.getMaxDepth(), encoderContext);
    writeNamedValue(writer, "depthField", value.getDepthField(), encoderContext);
    Filter[] restriction = value.getRestriction();
    if (restriction != null) {
        writer.writeStartDocument("restrictSearchWithMatch");
        for (final Filter filter : restriction) {
            filter.encode(getMapper(), writer, encoderContext);
        }
        writer.writeEndDocument();
    }

    writer.writeEndDocument();
}
 
Example #13
Source File: ZipExpression.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());
    writeNamedValue(mapper, writer, "inputs", inputs, encoderContext);
    writeNamedValue(mapper, writer, "useLongestLength", useLongestLength, encoderContext);
    writeNamedValue(mapper, writer, "defaults", defaults, encoderContext);
    writer.writeEndDocument();
    writer.writeEndDocument();
}
 
Example #14
Source File: Support.java    From immutables with Apache License 2.0 5 votes vote down vote up
BsonValue toBson() {
  BsonDocument bson = new BsonDocument();
  org.bson.BsonWriter writer = new BsonDocumentWriter(bson);
  // Bson doesn't allow to write directly scalars / primitives, they have to be embedded in a
  // document.
  writer.writeStartDocument();
  writer.writeName("$");
  encoder.encode(writer, value, EncoderContext.builder().build());
  writer.writeEndDocument();
  writer.flush();
  return bson.get("$");
}
 
Example #15
Source File: Filters.java    From morphia with Apache License 2.0 5 votes vote down vote up
/**
 * Specifies equality condition. The $eq operator matches documents where the value of a field equals the specified value.
 *
 * @param field the field to check
 * @param val   the value to check
 * @return the filter
 * @query.filter $eq
 */
public static Filter eq(final String field, final Object val) {
    return new Filter("$eq", field, val) {
        @Override
        public void encode(final Mapper mapper, final BsonWriter writer, final EncoderContext context) {
            writer.writeName(field(mapper));
            writeUnnamedValue(getValue(mapper), mapper, writer, context);
        }
    };
}
 
Example #16
Source File: JsonObjectCodec.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeNumberDecimal(BsonWriter writer, String name, Object value, EncoderContext ctx) {
  final String decimal = ((JsonObject) value).getString(DECIMAL_FIELD);
  if (decimal.contains(".")) {
    writer.writeDecimal128(new Decimal128(new BigDecimal(decimal)));
  } else {
    writer.writeDecimal128(new Decimal128(Long.parseLong(decimal)));
  }
}
 
Example #17
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 #18
Source File: JsonObjectCodec.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeTimeStamp(BsonWriter writer, String name, Object value, EncoderContext ctx) {
  final JsonObject timeStamp = ((JsonObject) value).getJsonObject(TIMESTAMP_FIELD);

  final BsonTimestamp bson = new BsonTimestamp(timeStamp.getInteger(TIMESTAMP_TIME_FIELD),
    timeStamp.getInteger(TIMESTAMP_INCREMENT_FIELD));

  writer.writeTimestamp(bson);
}
 
Example #19
Source File: AutoBucketCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final AutoBucket value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writeNamedExpression(getMapper(), writer, "groupBy", value.getGroupBy(), encoderContext);
    writeNamedValue(writer, "buckets", value.getBuckets(), encoderContext);
    writeNamedValue(writer, "granularity", value.getGranularity(), encoderContext);
    DocumentExpression output = value.getOutput();
    if (output != null) {
        output.encode("output", getMapper(), writer, encoderContext);
    }
    writer.writeEndDocument();
}
 
Example #20
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 #21
Source File: JsonObjectCodecTest.java    From vertx-mongo-client with Apache License 2.0 5 votes vote down vote up
@Test
public void writeDocument_supportBsonTimeStamp(){
  JsonObjectCodec codec = new JsonObjectCodec(options);

  int time = (int)(System.currentTimeMillis() / 1000L);
  int increment = 5;

  JsonObject timeStampComponent = new JsonObject();
  timeStampComponent.put(JsonObjectCodec.TIMESTAMP_TIME_FIELD, time);
  timeStampComponent.put(JsonObjectCodec.TIMESTAMP_INCREMENT_FIELD, increment);

  JsonObject timeStamp = new JsonObject();
  timeStamp.put(JsonObjectCodec.TIMESTAMP_FIELD, timeStampComponent);

  JsonObject value = new JsonObject();
  value.put("test", timeStamp);

  BsonDocument bsonResult = new BsonDocument();
  BsonDocumentWriter writer = new BsonDocumentWriter(bsonResult);

  codec.writeDocument(writer, "", value, EncoderContext.builder().build());

  BsonValue resultValue = bsonResult.get("test");

  assertEquals(BsonType.TIMESTAMP, resultValue.getBsonType());
  assertEquals(time, resultValue.asTimestamp().getTime());
  assertEquals(increment, resultValue.asTimestamp().getInc());
}
 
Example #22
Source File: JacksonCodecsTest.java    From immutables with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static <T> T writeThenRead(CodecRegistry registry, ObjectMapper mapper, T value) throws IOException {
  BasicOutputBuffer buffer = new BasicOutputBuffer();
  BsonWriter writer = new BsonBinaryWriter(buffer);
  registry.get((Class<T>) value.getClass()).encode(writer, value, 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);
  return mapper.readValue(parser, (Class<T>) value.getClass());
}
 
Example #23
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 #24
Source File: JacksonCodec.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@Override
public void encode(BsonWriter writer, T value, EncoderContext encoderContext) {
  try {
    byte[] data = mapper.writerWithView(DatabaseOnly.class).writeValueAsBytes(value);
    codec.encode(writer, new RawBsonDocument(data), encoderContext);
  } catch (JsonProcessingException e) {
    throw new MongoException(e.getMessage());
  }
}
 
Example #25
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 #26
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 #27
Source File: ArrayIndexExpression.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.writeStartArray(getOperation());
    writeUnnamedExpression(mapper, writer, array, encoderContext);
    writeUnnamedExpression(mapper, writer, search, encoderContext);
    writeUnnamedValue(mapper, writer, start, encoderContext);
    writeUnnamedValue(mapper, writer, end, encoderContext);
    writer.writeEndArray();
    writer.writeEndDocument();

}
 
Example #28
Source File: ReferenceCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
public Object encode(final Object value) {
    try {
        DocumentWriter writer = new DocumentWriter();
        writer.writeStartDocument();
        writer.writeName("ref");
        encode(writer, value, EncoderContext.builder().build());
        writer.writeEndDocument();
        return writer.getDocument().get("ref");
    } catch (ReferenceException e) {
        return value;
    }
}
 
Example #29
Source File: Push.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());
    if (field != null) {
        field.encode(mapper, writer, encoderContext);
    } else if(document != null) {
        document.encode(mapper, writer, encoderContext);
    }
    writer.writeEndDocument();
}
 
Example #30
Source File: CurrentOpCodec.java    From morphia with Apache License 2.0 5 votes vote down vote up
@Override
protected void encodeStage(final BsonWriter writer, final CurrentOp value, final EncoderContext encoderContext) {
    writer.writeStartDocument();
    writeBoolean(writer, "allUsers", value.isAllUsers(), encoderContext);
    writeBoolean(writer, "idleConnections", value.isIdleConnections(), encoderContext);
    writeBoolean(writer, "idleCursors", value.isIdleCursors(), encoderContext);
    writeBoolean(writer, "idleSessions", value.isIdleSessions(), encoderContext);
    writeBoolean(writer, "localOps", value.isLocalOps(), encoderContext);
    writer.writeEndDocument();
}