/** * 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; } }; }
@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); }
@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); }
@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); }
@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); }
@Override public void encode(BsonWriter writer, T value, EncoderContext encoderContext) { if (value == null) { writer.writeNull(); } else { writer.writeStartDocument(); PolymorphicCodec<T> codecForValue = getCodecForClass(value.getClass()); if (codecForValue != null) { writer.writeName(discriminatorKeys.get(codecForValue.getEncoderClass())); writer.writeString(mainDiscriminators.get(codecForValue.getEncoderClass())); codecForValue.encodeFields(writer, value, encoderContext); } else { LOGGER.warn("The value to be encoded has the wrong type {}. This codec can only handle {}", value.getClass(), discriminatorToCodec); } writer.writeEndDocument(); } }
@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(); } }
@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); }
/** * Testing if List<String> can be decoded into a */ @Test public void testResilience() { Codec<EncodingPojo> encodingPojoCodec = codecRegistry.get(EncodingPojo.class); Codec<DecodingPojo> decodingPojoCodec = codecRegistry.get(DecodingPojo.class); EncodingPojo encodingPojo = new EncodingPojo(); encodingPojo.someList = new ArrayList<>(); encodingPojo.someList.add("string1"); encodingPojo.someList.add("string2"); encodingPojo.someList.add("string3"); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); encodingPojoCodec.encode(writer, encodingPojo, EncoderContext.builder().build()); System.out.println(stringWriter.toString()); DecodingPojo decodingPojo = decodingPojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); Assert.assertNotNull(decodingPojo.someList); assertThat(decodingPojo.someList, instanceOf(ListOfStrings.class)); }
@Test public void basicTest() { BasePojo basePojo = new BasePojo(); basePojo.aString = STRING; Codec<BasePojo> primitivePojoCodec = codecRegistry.get(BasePojo.class); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); primitivePojoCodec.encode(writer, basePojo, EncoderContext.builder().build()); LOGGER.info("The encoded json looks like: {}", stringWriter); BasePojo readBasePojo = primitivePojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); // assert that the modified version was actually written to the database Assert.assertEquals(basePojo, readBasePojo); Assert.assertEquals(MODIFIED_STRING, readBasePojo.aString); }
@Test public void testEnums() { Codec<Pojo> pojoCodec = codecRegistry.get(Pojo.class); LovelyDisplayable lovelyDisplayable = LovelyDisplayable.builder().identityProperty("foo").build(); Pojo pojo = Pojo.builder() .simpleEnumProperty(EnumA.TYPE1) .displayable(Arrays.asList(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable)) .build(); StringWriter stringWriter = new StringWriter(); JsonWriter writer = new JsonWriter(stringWriter, new JsonWriterSettings(true)); pojoCodec.encode(writer, pojo, EncoderContext.builder().build()); System.out.println(stringWriter.toString()); Pojo decodedPojo = pojoCodec.decode(new JsonReader(stringWriter.toString()), DecoderContext.builder().build()); MatcherAssert.assertThat(decodedPojo.getDisplayable(), IsIterableContainingInOrder.contains(EnumB.TYPE1, EnumA.TYPE1, EnumA.TYPE3, lovelyDisplayable)); }
@Override public void encode(BsonWriter writer, Participant value, EncoderContext encoderContext) { writer.writeStartDocument(); writer.writeInt64("recruitmentNumber", value.getRecruitmentNumber()); writer.writeString("name", value.getName()); writer.writeString("sex", value.getSex().toString()); writer.writeStartDocument("birthdate"); writer.writeString("objectType", value.getBirthdate().getObjectType()); writer.writeString("value", value.getBirthdate().getFormattedValue()); writer.writeEndDocument(); writer.writeStartDocument("fieldCenter"); writer.writeString("acronym", value.getFieldCenter().getAcronym()); writer.writeEndDocument(); writer.writeEndDocument(); }
@SuppressWarnings("unchecked") public <T> BsonValue toBson(Object value, Class<T> clazz) { if(value == null) { return new BsonNull(); } if(value instanceof BsonValue) { return (BsonValue) value; } final Codec<T> codec = registry.get(clazz); final String key = "value"; final BsonDocument document = new BsonDocument(); final BsonWriter writer = new BsonDocumentWriter(document); writer.writeStartDocument(); writer.writeName(key); codec.encode(writer, (T) value, EncoderContext.builder().build()); writer.writeEndDocument(); return document.get(key); }
public BsonCodecGenerator(Models models) { this.models = models; Elements elems = models.getElemsUtil(); // Reusable things for multiple types objectIdTypeMirror = elems.getTypeElement(ObjectId.class.getCanonicalName()).asType(); bsonBinaryTypeMirror = elems.getTypeElement(BsonBinary.class.getCanonicalName()).asType(); dateTypeMirror = elems.getTypeElement(Date.class.getCanonicalName()).asType(); instantTypeMirror = elems.getTypeElement(Instant.class.getCanonicalName()).asType(); stringTypeMirror = elems.getTypeElement(String.class.getCanonicalName()).asType(); longTypeMirror = elems.getTypeElement(Long.class.getCanonicalName()).asType(); classClassName = ClassName.get(Class.class); bsonWriterParamSpec = ParameterSpec.builder(BsonWriter.class, "writer").addModifiers(Modifier.FINAL).build(); bsonReaderParamSpec = ParameterSpec.builder(BsonReader.class, "reader").addModifiers(Modifier.FINAL).build(); encoderCtxParamSpec = ParameterSpec.builder(EncoderContext.class, "ctx").addModifiers(Modifier.FINAL).build(); decoderCtxParamSpec = ParameterSpec.builder(DecoderContext.class, "ctx").addModifiers(Modifier.FINAL).build(); }
@SuppressWarnings("resource") protected <T> void writeReadCompare(T source, Codec<T> codec) { BasicOutputBuffer bsonOutput = new BasicOutputBuffer(); BsonBinaryWriter writer = new BsonBinaryWriter(bsonOutput); writer.writeStartDocument(); writer.writeName("name"); codec.encode(writer, source, EncoderContext.builder().build()); writer.writeEndDocument(); writer.close(); BsonBinaryReader reader = new BsonBinaryReader( ByteBuffer.wrap(bsonOutput.toByteArray())); reader.readStartDocument(); assertThat(reader.readName()).isEqualTo("name"); T readNow = codec.decode(reader, DecoderContext.builder().build()); assertThat(readNow).isEqualTo(source); }
@Override public void encode(BsonWriter writer, BibleBeanImpl bean, EncoderContext context) { Document document = new Document(); document.put("_id", bean.getId()); document.put("copyright", bean.getCopyright()); document.put("edition", bean.getEdition()); document.put("eletronic_transcription_source", bean.getEletronicTranscriptionSource()); document.put("eletronic_transcription_source_url", bean.getEletronicTranscriptionSourceUrl()); document.put("language", bean.getLanguage()); document.put("name", bean.getName()); document.put("printed_source", bean.getPrintedSource()); document.put("url", bean.getUrl()); this.documentCodec.encode(writer, document, context); }
/** * To be used if and only if it belongs to {@link java.util} package * @param writer * @param coll * @param encoderContext */ @SuppressWarnings({ "unchecked", "rawtypes" }) protected void encode(BsonWriter writer, Collection<?> coll, EncoderContext encoderContext) { writer.writeStartArray(); Iterator<?> iterator = coll.iterator(); while(iterator.hasNext()) { Object next = iterator.next(); if (next == null) { writer.writeNull(); } else { Codec codec = registry.get(next.getClass()); encoderContext.encodeWithChildContext(codec, writer, next); } } writer.writeEndArray(); }
@Override public void encode(BsonWriter writer, List value, EncoderContext encoderContext) { if (value != null && !value.isEmpty()) { writer.writeStartArray(); for (Object a : value) { if (a != null) { Codec codec = this.codecRegistry.get(a.getClass()); encoderContext.encodeWithChildContext(codec, writer, a); } else { writer.writeNull(); } } writer.writeEndArray(); } else { writer.writeNull(); } }
private void addEncodeMethod(Builder classBuilder, List<FieldModel> fieldModel) { MethodSpec.Builder encode = MethodSpec.methodBuilder("encode") .returns(TypeName.VOID).addModifiers(Modifier.PUBLIC) .addAnnotation(Override.class).addParameter(BsonWriter.class, "writer") .addParameter(this.thisType, "value") .addParameter(EncoderContext.class, "encoderContext") .addStatement("writer.writeStartDocument()"); for (FieldModel field : fieldModel) { String getter = "value." + field.methodNameGet() + "()"; String setter = "value." + field.methodNameSet() + "(%s)"; CodeGeneratorContext ctx = new CodeGeneratorContext(field, encode, this.instanceFields, getter, setter); field.codeGen().addEncodeStatements(ctx); } encode.addStatement("writer.writeEndDocument()"); classBuilder.addMethod(encode.build()); }
/** * {@inheritDoc} */ @Override public void encode(BsonWriter writer, DefaultDomain value, EncoderContext encoderContext) { writer.writeStartDocument(); writer.writeName("players"); writer.writeStartArray(); for (UUID uuid : value.getUniqueIds()) writer.writeString(uuid.toString()); writer.writeEndArray(); writer.writeName("groups"); writer.writeStartArray(); for (String group : value.getGroups()) writer.writeString(group); writer.writeEndArray(); writer.writeEndDocument(); }
@Override public void encode(BsonWriter writer, MonetaryAmount value, EncoderContext encoderContext) { writer.writeStartDocument(); writer.writeString(this.currencyKey, value.getCurrency().getCurrencyCode()); BigDecimal number = value.getNumber().numberValue(BigDecimal.class); if (this.zeroPadding == null) { writer.writeString(this.numberKey, number.toString()); } else { writer.writeString(this.numberKey, formatBigDecimal(number)); } writer.writeEndDocument(); }
@Override public void encode( BsonWriter writer, Period value, EncoderContext encoderContext) { writer.writeString(value.toString()); }
@Override public void encode( BsonWriter writer, LocalDateTime value, EncoderContext encoderContext) { writer.writeDateTime( value.toInstant(UTC) .toEpochMilli() ); }
@Override public void encode( BsonWriter writer, ZoneOffset value, EncoderContext encoderContext) { writer.writeInt32(value.getTotalSeconds()); }
@Override public void encode( BsonWriter writer, LocalTime value, EncoderContext encoderContext) { writer.writeDateTime( value.atDate(ofEpochDay(0L)) .toInstant(UTC) .toEpochMilli() ); }
@Override public void encode( BsonWriter writer, MonthDay value, EncoderContext encoderContext) { writer.writeDecimal128(parse(format( "%d.%02d", value.getMonthValue(), value.getDayOfMonth() ))); }
@Override public void encode( BsonWriter writer, LocalDate value, EncoderContext encoderContext) { writer.writeDateTime( value.atStartOfDay() .toInstant(UTC) .toEpochMilli() ); }
@Override public void encode( BsonWriter writer, OffsetTime value, EncoderContext encoderContext) { writer.writeString(value.toString()); }
@Override public void encode( BsonWriter writer, Year value, EncoderContext encoderContext) { writer.writeInt32(value.getValue()); }
@Override public void encode( BsonWriter writer, YearMonth value, EncoderContext encoderContext) { writer.writeDecimal128(parse(format( "%d.%02d", value.getYear(), value.getMonthValue() ))); }
@Override public void encode( BsonWriter writer, Instant value, EncoderContext encoderContext) { writer.writeDateTime( value.toEpochMilli() ); }
@Override public void encode( BsonWriter writer, ZonedDateTime value, EncoderContext encoderContext) { writer.writeString(value.toString()); }
@Override public void encode( BsonWriter writer, OffsetDateTime value, EncoderContext encoderContext) { writer.writeString(value.toString()); }
@Override public void encode( BsonWriter writer, Duration value, EncoderContext encoderContext) { writer.writeDecimal128(parse(format( "%d.%09d", value.getSeconds(), value.getNano() ))); }
private <T> void encodeValue(BsonOutput output, Codec<T> codec, T value) { try (BsonBinaryWriter writer = new BsonBinaryWriter(output)) { writer.writeStartDocument(); writer.writeName("value"); codec.encode(writer, value, EncoderContext.builder().build()); writer.writeEndDocument(); writer.close(); } }
BsonValue toBson() { @SuppressWarnings("unchecked") Encoder<T> encoder = BsonEncoding.encoderFor((Class<T>) value.getClass(), adapter); 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("$"); }
@Override public final void encode(org.bson.BsonWriter writer, Object[] array, EncoderContext encoderContext) { if (codec == null) { codec = new IterableCodec(codecRegistry, bsonTypeClassMap); } codec.encode(writer, Arrays.asList(array), encoderContext); }
@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); }
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); } } } }
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); } }