Java 类org.bson.BsonWriter 实例源码

项目:BsonMapper    文件:DefaultBsonMapperTest.java   
@Test
public void testCustomizedBsonConverter() throws Exception {
    BsonValueConverterRepertory.registerCustomizedBsonConverter(String.class, new AbstractBsonConverter<String, BsonString>() {
        @Override
        public String decode(BsonReader bsonReader) {
            return "replace string";
        }

        @Override
        public void encode(BsonWriter bsonWriter, String value) {

        }

        @Override
        public String decode(BsonValue bsonValue) {
            return "replace string";
        }

        @Override
        public BsonString encode(String object) {
            return new BsonString("replace string");
        }
    });
    readFrom();
}
项目:GitHub    文件:BsonEncoding.java   
/**
 * Creates "writer" which can serialize existing immutable instance into <a href="http://bsonspec.org/">BSON format</a>
 * consumed by mongo server.
 */
public static <T> Encoder<T> encoderFor(final Class<T> type, final TypeAdapter<T> adapter) {
  checkNotNull(type, "type");
  checkNotNull(adapter, "adapter");
  return new Encoder<T>() {
    @Override
    public void encode(org.bson.BsonWriter writer, T value, EncoderContext encoderContext) {
      try {
        adapter.write(new org.immutables.mongo.repository.internal.BsonWriter(writer), value);
      } catch (IOException e) {
        throw new RuntimeException(String.format("Couldn't write value of class %s: %s", type.getName(), value),e);
      }
    }

    @Override
    public Class<T> getEncoderClass() {
      return type;
    }
  };
}
项目:mongodb-rdbms-sync    文件:SyncErrorCodec.java   
@Override
public void encode(BsonWriter writer, SyncError error, EncoderContext encoderContext) {
    Document document= new Document();
    if(error.getMessage()!=null && !error.getMessage().isEmpty()){
        document.append(SyncAttrs.ERROR_MESSAGE, error.getMessage());
    }

    String fullStackTrace = ExceptionUtils.getStackTrace(error);
    if(fullStackTrace!=null && !fullStackTrace.isEmpty()){
        document.append(SyncAttrs.TRACE, fullStackTrace);
    }
    if(error.getThreadName()!=null && !error.getThreadName().isEmpty()){
        document.append(SyncAttrs.THREAD_NAME, error.getThreadName());
    }
    documentCodec.encode(writer, document, encoderContext);
}
项目:mongodb-rdbms-sync    文件:SyncUserDetailCodec.java   
@Override
public void encode(BsonWriter writer, SyncUser user, EncoderContext encoderContext) {
    logger.info("Start of Encode method");
    Document document = new Document();
    if (user.getUserid()!=null && !user.getUserid().isEmpty()){
        document.append(String.valueOf(UserDetailAttributes._id), user.getUserid());
    }       
    if(user.getSourceDbMap()!=null && !user.getSourceDbMap().isEmpty()){
        document.append(String.valueOf(UserDetailAttributes.sourceDbMap), user.getSourceDbMap());
    }
    if(user.getTargetDbMap()!=null && !user.getTargetDbMap().isEmpty()){
        document.append(String.valueOf(UserDetailAttributes.targetDbMap), user.getTargetDbMap());
    }
    if(user.getUserRoles()!=null && !user.getUserRoles().isEmpty()){
        document.append("roles", user.getUserRoles());
    }
    documentCodec.encode(writer, document, encoderContext);
    logger.info("Encoder completed. Document formed is \n"+document);
}
项目:mongodb-rdbms-sync    文件:SyncUserSessionCodec.java   
@Override
public void encode(BsonWriter writer, SyncUserSession session, EncoderContext encoderContext) {
    Document document = new Document();
    if(session.getSessionId()!=null && !session.getSessionId().isEmpty() ){
        document.append(String.valueOf(SessionAttributes._id), session.getSessionId()); 
    }
    if(session.getUserid()!=null && !session.getUserid().isEmpty()){
        document.append(String.valueOf(SessionAttributes.userid), session.getUserid());
    }
    if(session.getLoginTime()!=null){
        document.append(String.valueOf(SessionAttributes.loginTime), session.getLoginTime());
    }
    if(session.getClientIPAddress()!=null && !session.getClientIPAddress().isEmpty()){
        document.append(String.valueOf(SessionAttributes.clientIPAddress), session.getClientIPAddress());
    }
    if(session.getClientHostName()!=null && !session.getClientHostName().isEmpty()){
        document.append(String.valueOf(SessionAttributes.clientHostName), session.getClientHostName());
    }
    if(session.getClientAgent()!=null && !session.getClientAgent().isEmpty()){
        document.append(String.valueOf(SessionAttributes.clientAgent), session.getClientAgent());
    }
    documentCodec.encode(writer, document, encoderContext);
}
项目:mongodb-rdbms-sync    文件:SyncMarkerCodec.java   
@Override
public void encode(BsonWriter writer, SyncMarker marker, EncoderContext encoderContext) {
    Document document = new Document();
    if(marker.getStartTime()!=null){
        document.append(SyncAttrs.START_TIME, marker.getStartTime());
    }
    document.append(SyncAttrs.ROWS_READ, marker.getRowsRead());
    if(marker.isAllRowsFetchedFromDb()){
        document.append(SyncAttrs.ALL_ROWS_FETCHED, marker.isAllRowsFetchedFromDb());
    }
    document.append(SyncAttrs.ROWS_DUMPED, marker.getRowsDumped());
    document.append(SyncAttrs.TOTAL_ROWS, marker.getTotalRows());
    if(marker.getEndTime()!=null){
        document.append(SyncAttrs.END_TIME, marker.getEndTime());
    }   
    documentCodec.encode(writer, document, encoderContext);
}
项目:polymorphia    文件:SpecialFieldsMapCodec.java   
@Override
public void encode(BsonWriter writer, T map, EncoderContext encoderContext) {
    if (map == null) {
        writer.writeNull();
    }
    else {
        writer.writeStartDocument();
        for (Map.Entry<String, Object> entry : map.entrySet()) {
            writer.writeName(entry.getKey());
            Object value = entry.getValue();

            Codec fieldMappingCodec = fieldMappingCodecs.get(entry.getKey());
            if (fieldMappingCodec != null) {
                fieldMappingCodec.encode(writer, value, encoderContext);
            } else {
                if (value != null) {
                    Codec codec = codecRegistry.get(value.getClass());
                    codec.encode(writer, value, encoderContext);
                } else {
                    writer.writeNull();
                }
            }
        }
        writer.writeEndDocument();
    }
}
项目:polymorphia    文件:CodecResolverTest.java   
@Override
public void encodeFields(BsonWriter writer, T instance, EncoderContext encoderContext) {
    // first persist meta document
    documentMetaCodec.encodeFields(writer, instance.getMeta(), encoderContext);

    // only persist data property if and only if properties exist
    Map<String, MappedField> persistenceFields = getPersistenceFields();
    if (!persistenceFields.isEmpty()) {
        writer.writeName("data");
        writer.writeStartDocument();

        for (MappedField persistenceField : persistenceFields.values()) {
            if (!"meta".equals(persistenceField.getMappedFieldName())) {
                persistenceField.encode(writer, instance, encoderContext);
            }
        }
        writer.writeEndDocument();
    }
}
项目:BsonMapper    文件:BsonArrayConverter.java   
private void writeValuesToBson(BsonWriter bsonWriter, Field field, Collection fieldValue, Class<?> componentType) {
    for (Object value : fieldValue) {
        if (value == null) {
            continue;
        }
        Class<?> valueClazz = value.getClass();
        if (Utils.isArrayType(valueClazz)) {
            encode(bsonWriter, field, value);
            continue;
        }
        if (componentType.isInstance(value)) {
            if (BsonValueConverterRepertory.isCanConverterValueType(componentType)) {
                BsonValueConverterRepertory.getByteIOConverterByClazz(componentType).encode(bsonWriter, value);
            } else {
                BsonValueConverterRepertory.getBsonDocumentConverter().encode(bsonWriter, value);
            }
        } else {
            throw new BsonMapperConverterException(String.format("array field has element which has different type with declaring componentType.field name: %s", field.getName()));
        }
    }
}
项目:bson-codecs-jsr310    文件:LocalDateTimeCodec.java   
@Override
public void encode(
        BsonWriter writer,
        LocalDateTime value,
        EncoderContext encoderContext) {

    writer.writeDateTime(
            value.toInstant(UTC)
                 .toEpochMilli()
    );
}
项目:bson-codecs-jsr310    文件:ZoneOffsetCodec.java   
@Override
public void encode(
        BsonWriter writer,
        ZoneOffset value,
        EncoderContext encoderContext) {

    writer.writeInt32(value.getTotalSeconds());
}
项目:bson-codecs-jsr310    文件:LocalTimeCodec.java   
@Override
public void encode(
        BsonWriter writer,
        LocalTime value,
        EncoderContext encoderContext) {

    writer.writeDateTime(
            value.atDate(ofEpochDay(0L))
                 .toInstant(UTC)
                 .toEpochMilli()
    );
}
项目:bson-codecs-jsr310    文件:MonthDayCodec.java   
@Override
public void encode(
        BsonWriter writer,
        MonthDay value,
        EncoderContext encoderContext) {

    writer.writeDecimal128(parse(format(
            "%d.%02d",
            value.getMonthValue(),
            value.getDayOfMonth()
    )));
}
项目:bson-codecs-jsr310    文件:LocalDateCodec.java   
@Override
public void encode(
        BsonWriter writer,
        LocalDate value,
        EncoderContext encoderContext) {

    writer.writeDateTime(
            value.atStartOfDay()
                 .toInstant(UTC)
                 .toEpochMilli()
    );
}
项目:bson-codecs-jsr310    文件:OffsetTimeCodec.java   
@Override
public void encode(
        BsonWriter writer,
        OffsetTime value,
        EncoderContext encoderContext) {

    writer.writeString(value.toString());
}
项目:bson-codecs-jsr310    文件:YearCodec.java   
@Override
public void encode(
        BsonWriter writer,
        Year value,
        EncoderContext encoderContext) {

    writer.writeInt32(value.getValue());
}
项目:bson-codecs-jsr310    文件:YearMonthCodec.java   
@Override
public void encode(
        BsonWriter writer,
        YearMonth value,
        EncoderContext encoderContext) {

    writer.writeDecimal128(parse(format(
            "%d.%02d",
            value.getYear(),
            value.getMonthValue()
    )));
}
项目:bson-codecs-jsr310    文件:InstantCodec.java   
@Override
public void encode(
        BsonWriter writer,
        Instant value,
        EncoderContext encoderContext) {

    writer.writeDateTime(
            value.toEpochMilli()
    );
}
项目:bson-codecs-jsr310    文件:ZonedDateTimeCodec.java   
@Override
public void encode(
        BsonWriter writer,
        ZonedDateTime value,
        EncoderContext encoderContext) {

    writer.writeString(value.toString());
}
项目:BsonMapper    文件:BsonDocumentConverterTest.java   
@Test
public void testByteIOEncode() throws Exception {
    BasicOutputBuffer bsonOutput = new BasicOutputBuffer();
    BsonWriter bsonWriter = new BsonBinaryWriter(bsonOutput);
    BsonValueConverterRepertory.getBsonDocumentConverter().encode(bsonWriter, getObject());
    BsonReader bsonReader = new BsonBinaryReader(new ByteBufferBsonInput(bsonOutput.getByteBuffers().get(0)));
    BsonTest bsonTest = BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonReader, BsonTest.class, BsonMapperConfig.DEFALUT);
    System.out.println(bsonTest);
}
项目:bson-codecs-jsr310    文件:DurationCodec.java   
@Override
public void encode(
        BsonWriter writer,
        Duration value,
        EncoderContext encoderContext) {

    writer.writeDecimal128(parse(format(
            "%d.%09d",
            value.getSeconds(),
            value.getNano()
    )));
}
项目:mongodb-rdbms-sync    文件:SyncNodeDetailsCodec.java   
@Override
public void encode(BsonWriter bsonWriter, SyncNodeDetails nodeAndEvent, EncoderContext context) {
    Document document = new Document();
    if (nodeAndEvent.getNode() != null) {
        document.append("node", nodeAndEvent.getNode());
    }
    if (nodeAndEvent.getEvent() != null) {
        document.append("events", nodeAndEvent.getEvent());
    }
    documentCodec.encode(bsonWriter, document, context);
}
项目:polymorphia    文件:MappedField.java   
public void encode(BsonWriter writer, T instance, EncoderContext encoderContext) {
    LOGGER.debug("Encode field : " + getMappedFieldName());
    if (field.getType().isPrimitive()) {
        if (isLockingVersionField()) {
            writeLockingVersion(writer, instance);
        } else {
            primitiveType.encode(writer, instance, encoderContext, this);
        }
    } else if (codec != null) {
        F fieldValue = getFieldValue(instance);
        if (fieldValue == null) {
            switch (encodeNullHandlingStrategy) {
                case CODEC: {
                    if (codec instanceof TypeCodec) {
                        TypeCodec<F> typeCodec = (TypeCodec) codec;
                        fieldValue = typeCodec.defaultInstance();
                    }
                    break;
                }
                case KEEP_NULL:
                    break;

            }
        }

        if (encodeNulls || fieldValue != null) {
            writer.writeName(getMappedFieldName());
            if (fieldValue == null) {
                writer.writeNull();
            } else {
                codec.encode(writer, fieldValue, encoderContext);
            }
        }
    }
}
项目:polymorphia    文件:MappedField.java   
private void writeLockingVersion(BsonWriter writer, T instance) {
    try {
        writer.writeName(getMappedFieldName());
        int lockingVersion = field.getInt(instance) + 1;
        writer.writeInt32(lockingVersion);
    } catch (IllegalAccessException e) {
        LOGGER.warn("IllegalAccessException while writeLockingVersion field " + field.getName(), e);
    }
}
项目:polymorphia    文件:MappedField.java   
default <T> void encode(BsonWriter writer, T instance, EncoderContext encoderContext, MappedField mappedField) {
    try {
        writer.writeName(mappedField.getMappedFieldName());
        encodeInternal(writer, instance, mappedField.getField());
    } catch (IllegalAccessException e) {
        LOGGER.warn("Cannot access mappedField. ", mappedField, e);
    }
}
项目:polymorphia    文件:BasicReflectionCodec.java   
@Override
public void encodeFields(BsonWriter writer, T instance, EncoderContext encoderContext) {
    preEncode(instance);
    for (MappedField persistenceField : persistenceFields.values()) {
        persistenceField.encode(writer, instance, encoderContext);
    }
}
项目:polymorphia    文件:PolymorphicCodec.java   
@Override
default void encode(BsonWriter writer, T value, EncoderContext encoderContext) {
    if (value == null) {
        writer.writeNull();
    }
    else {
        writer.writeStartDocument();
        encodeFields(writer, value, encoderContext);
        writer.writeEndDocument();
    }
}
项目:polymorphia    文件:ArrayCodec.java   
private void encodeDimension(BsonWriter writer, Object array, EncoderContext encoderContext, Class<?> componentType) {
    boolean encodeLastDimension;
    Class<?> childComponentType = componentType.getComponentType();
    encodeLastDimension = !childComponentType.isArray();

    if (childComponentType == byte.class) {
        arrayElementCodec.encode(writer, array, encoderContext);
    } else {
        writer.writeStartArray();

        if (encodeLastDimension) {
            if (isPrimitive) {
                arrayElementCodec.encode(writer, array, encoderContext);
            } else {

                for (int i = 0; i < Array.getLength(array); i++) {
                    arrayElementCodec.encode(writer, Array.get(array, i), encoderContext);
                }
            }
        } else {
            for (int i = 0; i < Array.getLength(array); i++) {
                encodeDimension(writer, Array.get(array, i), encoderContext, childComponentType);
            }
        }
        writer.writeEndArray();
    }
}
项目:polymorphia    文件:SimpleMapTypeCodec.java   
@Override
public void encode(BsonWriter writer, Map<String, V> map, EncoderContext encoderContext) {
    writer.writeStartDocument();
    for (Map.Entry<String, V> entry : map.entrySet()) {
        writer.writeName(entry.getKey());
        valueTypeCodec.encode(writer, entry.getValue(), encoderContext);
    }
    writer.writeEndDocument();
}
项目:polymorphia    文件:ComplexMapTypeCodec.java   
@Override
public void encode(BsonWriter writer, Map<K, V> map, EncoderContext encoderContext) {
    writer.writeStartArray();
    for (Map.Entry<K, V> entry : map.entrySet()) {
        writer.writeStartDocument();
        writer.writeName("key");
        keyTypeCodec.encode(writer, entry.getKey(), encoderContext);
        writer.writeName("value");
        valueTypeCodec.encode(writer, entry.getValue(), encoderContext);
        writer.writeEndDocument();
    }
    writer.writeEndArray();
}
项目: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());
}
项目:polymorphia    文件:CollectionTypeCodec.java   
@Override
public void encode(BsonWriter writer, C value, EncoderContext encoderContext) {
    writer.writeStartArray();
    for (V o : value) {
        typeCodec.encode(writer, o, encoderContext);
    }
    writer.writeEndArray();
}
项目:polymorphia    文件:TypeCodecProviderTest.java   
@Override
public void encode(BsonWriter writer, Set<String> value, EncoderContext encoderContext) {
    StringBuilder sb = new StringBuilder();
    for (String s : value) {
        sb.append(s).append('#');
    }
    writer.writeString(sb.toString());
}
项目:polymorphia    文件:TypeCodecProviderTest.java   
@Override
public void encode(BsonWriter writer, CustomType<T> value, EncoderContext encoderContext) {
    writer.writeStartDocument();
    writer.writeName("name");
    nameCodec.encode(writer, value.getANameForTheList(), encoderContext);

    writer.writeName("list");
    listCodec.encode(writer, value, encoderContext);

    writer.writeName("innerType");
    innerTypeCodec.encode(writer, value.getInnerType(), encoderContext);
    writer.writeEndDocument();
}
项目:BsonMapper    文件:BsonDocumentConverter.java   
public void encode(BsonWriter bsonWriter, Object object) {
    bsonWriter.writeStartDocument();
    Map<String, Field> bsonNameFieldInfoMap = getBsonNameFieldInfoMap(object.getClass());
    for (Entry<String, Field> entry : bsonNameFieldInfoMap.entrySet()) {
        Field field = entry.getValue();
        Object fieldValue = Utils.getFieldValue(field, object);
        if (fieldValue == null || Utils.isIgnored(field)) {
            continue;
        }
        String bsonName = entry.getKey();
        bsonWriter.writeName(bsonName);
        Class<?> fieldType = field.getType();
        if (Utils.isArrayType(fieldType)) {
            BsonValueConverterRepertory.getBsonArrayConverter().encode(bsonWriter, field, fieldValue);
            continue;
        }
        if (BsonValueConverterRepertory.isCanConverterValueType(fieldType)) {
            if (Utils.fieldIsObjectId(field)) {
                if (fieldType == String.class) {
                    fieldValue = new StringObjectId(new ObjectId((String) fieldValue));
                    fieldType = StringObjectId.class;
                }
            }
            BsonByteIOConverter<Object> valueConverter = BsonValueConverterRepertory.getByteIOConverterByClazz(fieldType);
            if (valueConverter != null) {
                valueConverter.encode(bsonWriter, fieldValue);
            } else {
                //              maybe log warn message to remind user add converter
            }
        } else {
            BsonValueConverterRepertory.getBsonDocumentConverter().encode(bsonWriter, fieldValue);
        }
    }
    bsonWriter.writeEndDocument();
}
项目:BsonMapper    文件:DefaultBsonMapper.java   
@Override
public BsonOutput writeToBsonOutput(Object object) {
    if (object == null) {
        return null;
    }
    BsonOutput bsonOutput = new BasicOutputBuffer();
    BsonWriter bsonBinaryWriter = new BsonBinaryWriter(new BsonWriterSettings(bsonMapperConfig.getMaxMapperLayerNum()),
            new BsonBinaryWriterSettings(bsonMapperConfig.getMaxDocumentSizeForBsonWriter()), bsonOutput);
    BsonValueConverterRepertory.getBsonDocumentConverter().encode(bsonBinaryWriter, object);
    return bsonOutput;
}
项目: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    文件:BsonArrayConverter.java   
public void encode(BsonWriter bsonWriter, Field field, Object fieldValue) {
    bsonWriter.writeStartArray();
    Class<?> fieldType = field.getType();
    if (fieldType.isArray()) {
        handleArrayForEncodeWriter(bsonWriter, field, (Object[]) fieldValue);
    } else if (Collection.class.isAssignableFrom(fieldType)) {
        handleCollectionForEncodeWriter(bsonWriter, field, (Collection) fieldValue);
    } else {
        throw new BsonMapperConverterException("exception should be never happen.the field:" + Utils.getBsonName(field) + "should be array or Collection");
    }
    bsonWriter.writeEndArray();
}
项目:BsonMapper    文件:BsonDateConverter.java   
@Override
public void encode(BsonWriter bsonWriter, Date value) {
    bsonWriter.writeDateTime(value.getTime());
}
项目:tapir    文件:SipMessageCodec.java   
@Override
public void encode(BsonWriter writer, SipMessage sipMessage, EncoderContext encoderContext) {
    throw new UnsupportedOperationException();
}