@Override public MonthDay decode( BsonReader reader, DecoderContext decoderContext) { BigDecimal value = reader .readDecimal128() .bigDecimalValue(); int month = value.intValue(); return of( month, value.subtract(new BigDecimal(month)) .scaleByPowerOfTen(2) .intValue() ); }
@Override public YearMonth decode( BsonReader reader, DecoderContext decoderContext) { BigDecimal value = reader .readDecimal128() .bigDecimalValue(); int year = value.intValue(); return of( year, value.subtract(new BigDecimal(year)) .scaleByPowerOfTen(2) .abs() .intValue() ); }
@Override public Duration decode( BsonReader reader, DecoderContext decoderContext) { BigDecimal value = reader .readDecimal128() .bigDecimalValue(); long seconds = value.longValue(); return ofSeconds( seconds, value.subtract(new BigDecimal(seconds)) .scaleByPowerOfTen(9) .abs() .intValue() ); }
/** * Creates a "reader" which is able to deserialize binary data into a immutables instance (using GSON type adapter). */ public static <T> Decoder<T> decoderFor(final Class<T> type, final TypeAdapter<T> adapter) { checkNotNull(type, "type"); checkNotNull(adapter, "adapter"); return new Decoder<T>() { @Override public T decode(BsonReader reader, DecoderContext decoderContext) { if (!(reader instanceof AbstractBsonReader)) { throw new UnsupportedOperationException(String.format("Only readers of type %s supported. Yours is %s", AbstractBsonReader.class.getName(), reader.getClass().getName())); } try { return adapter.read(new org.immutables.mongo.repository.internal.BsonReader((AbstractBsonReader) reader)); } catch (IOException e) { throw new RuntimeException(String.format("Couldn't encode %s", type), e); } } }; }
@SuppressWarnings("rawtypes") @Override public SyncNodeDetails decode(BsonReader bsonReader, DecoderContext context) { Document document = documentCodec.decode(bsonReader, context); SyncNodeDetails nodeAndEvent = new SyncNodeDetails(); SyncNode node = SyncNodeDecoder.decodeNode((Document) document.get("node")); nodeAndEvent.setNode(node); SyncEvent event = null; List<SyncEvent> eventList = new ArrayList<SyncEvent>(); SyncMapAndEventDecoder eventDecoder = new SyncMapAndEventDecoder(); @SuppressWarnings("unchecked") List<Document> list = (List<Document>) document.get("events"); for(Document doc : list){ event = eventDecoder.decodeSyncEvent(doc); eventList.add(event); } nodeAndEvent.setEvent(eventList); return nodeAndEvent; }
@SuppressWarnings("unchecked") @Override public O2MSyncEventLog decode(BsonReader arg0, DecoderContext arg1) { Document document = documentCodec.decode(arg0, arg1); O2MSyncEventLog log = new O2MSyncEventLog(); log.setLogId(document.getObjectId(_ID)); log.setEventId(document.getString(EVENT_ID)); log.setCrOn(document.getDate(CREATED_ON)); log.setSyOn(document.getDate(SYNCED_ON)); log.setStatus(document.getString(STATUS)); log.setOperation(document.getString(OPERATION)); List<Document> filterDocList = (List<Document>) document.get(EVENT_FILTERS); if(filterDocList!=null){ List<O2MSyncEventInfo> filters = new ArrayList<O2MSyncEventInfo>(filterDocList.size()); O2MSyncEventInfo filter = null; for(Document filterDoc : filterDocList){ filter= new O2MSyncEventInfo(); filter.setTableName(filterDoc.getString(TABLE_NAME)); filter.setColumnName(filterDoc.getString(COLUMN_NAME)); filter.setColumnValue(filterDoc.get(COLUMN_VALUE)); filters.add(filter); } log.setEventFilters(filters); } return log; }
@Override public Map<String, V> decode(BsonReader reader, DecoderContext decoderContext) { Map<String, V> map = newInstance(); if (BsonType.DOCUMENT.equals(reader.getCurrentBsonType())) { reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String key = reader.readName(); V value = valueTypeCodec.decode(reader, decoderContext); map.put(key, value); } reader.readEndDocument(); } else { LOGGER.warn("Expected {} from reader but got {}. Skipping value.", BsonType.DOCUMENT, reader.getCurrentBsonType()); reader.skipValue(); } return map; }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { if (BsonType.STRING.equals(reader.getCurrentBsonType())) { String name = reader.readString(); if (name != null) { try { return Enum.valueOf(clazz, name); } catch (IllegalArgumentException e) { LOGGER.warn("Enum value {} could not be determined for enum type {}", name, clazz, e); } } } else { LOGGER.warn("Expected {} from reader but got {}. Skipping value.", BsonType.STRING, reader.getCurrentBsonType()); reader.skipValue(); } return null; }
@Override public LocalDateTime decode( BsonReader reader, DecoderContext decoderContext) { return ofEpochMilli(reader.readDateTime()) .atOffset(UTC) .toLocalDateTime(); }
public void decode(BsonReader reader, T instance, DecoderContext decoderContext) { LOGGER.debug("Decode field : " + getMappedFieldName() + " Signature: " + fieldTypePair.getRealType()); if (field.getType().isPrimitive()) { if (reader.getCurrentBsonType() == BsonType.NULL || reader.getCurrentBsonType() == BsonType.UNDEFINED) { reader.skipValue(); } else { primitiveType.decode(reader, instance, decoderContext, this); } } else if (codec != null) { if (reader.getCurrentBsonType() == BsonType.NULL ) { reader.readNull(); setFieldValue(instance, null); } else if (reader.getCurrentBsonType() == BsonType.UNDEFINED) { reader.skipValue(); } else { F decoded = codec.decode(reader, decoderContext); setFieldValue(instance, decoded); } } }
@Override public Map<K, V> decode(BsonReader reader, DecoderContext decoderContext) { Map<K, V> map = newInstance(); if (BsonType.ARRAY.equals(reader.getCurrentBsonType())) { reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { if (BsonType.DOCUMENT.equals(reader.getCurrentBsonType())) { reader.readStartDocument(); reader.readName(); // don't need the key == "key" K key = keyTypeCodec.decode(reader, decoderContext); reader.readName(); // don't need the key == "value" V value = valueTypeCodec.decode(reader, decoderContext); map.put(key, value); reader.readEndDocument(); } else { LOGGER.warn("Expected {} from reader but got {}. Skipping value.", BsonType.DOCUMENT, reader.getCurrentBsonType()); reader.skipValue(); } } reader.readEndArray(); } else { LOGGER.warn("Expected {} from reader but got {}. Skipping value.", BsonType.ARRAY, reader.getCurrentBsonType()); reader.skipValue(); } return map; }
@Override public CustomType decode(BsonReader reader, DecoderContext decoderContext) { reader.readStartDocument(); reader.readName("name"); String name = nameCodec.decode(reader, decoderContext); reader.readName("list"); List<T> stringArrayList = listCodec.decode(reader, decoderContext); reader.readName("innerType"); InnerType<T> innerType = innerTypeCodec.decode(reader, decoderContext); reader.readEndDocument(); CustomType<T> customType = new CustomType(name); customType.setInnerType(innerType); customType.addAll(stringArrayList); return customType; }
@Override public T decodeFields(BsonReader reader, DecoderContext decoderContext, T instance) { MetaData documentMeta = instance.getMeta(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String fieldName = reader.readName(); if ("data".equals(fieldName)) { reader.readStartDocument(); super.decodeFields(reader, decoderContext, instance); reader.readEndDocument(); } else { MappedField field = documentMetaCodec.getMappedField(fieldName); if (field != null) { field.decode(reader, documentMeta, decoderContext); } else { reader.skipValue(); } } } documentMetaCodec.postDecode(documentMeta); return instance; }
/** * 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)); }
@Test public void method_decode_should_evocate_functions_that_reade_user_attributes() throws Exception { DecoderContext decoderContext = DecoderContext.builder().build(); PowerMockito.when(reader.readString("password")).thenReturn(PASSWORD); PowerMockito.when(reader.readString("phone")).thenReturn(PHONE); PowerMockito.when(reader.readBoolean("enable")).thenReturn(ENABLE); PowerMockito.when(reader.readBoolean("extraction")).thenReturn(EXTRACTIONENABLED); PowerMockito.when(reader.readString("surname")).thenReturn(SURNAME); PowerMockito.when(reader.readString("name")).thenReturn(NAME); PowerMockito.when(reader.readBoolean("adm")).thenReturn(ADMIN); PowerMockito.when(reader.readString("uuid")).thenReturn(UUIDString); PowerMockito.when(reader.readString("email")).thenReturn(EMAIL); PowerMockito.when(reader.readString("acronym")).thenReturn(FIELDCENTERACRONYM); PowerMockito.when(reader.readBsonType()).thenReturn(BsonType.END_OF_DOCUMENT); doThrow(new BsonInvalidOperationException("teste")).when(reader).readNull("fieldCenter"); doThrow(new BsonInvalidOperationException("teste")).when(reader).readNull("extraction"); User userLocal = UserCodec.decode(reader, decoderContext); assertEquals(userLocal.getEmail(),EMAIL); assertEquals(userLocal.getPassword(),PASSWORD); assertEquals(userLocal.getPhone(),PHONE); assertEquals(userLocal.isEnable(),ENABLE); assertEquals(userLocal.isExtractionEnabled(),EXTRACTIONENABLED); assertEquals(userLocal.getName(),NAME); assertEquals(userLocal.getFieldCenter().getAcronym(),FIELDCENTERACRONYM); assertEquals(userLocal.getUuid().toString(),UUID.fromString(UUIDString).toString()); }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { final BsonType type = reader.getCurrentBsonType(); switch(type) { case INT32: return decode(reader.readInt32() != 0); case NULL: return null; case STRING: return decode(Boolean.parseBoolean(reader.readString())); case BOOLEAN: return decode(reader.readBoolean()); //$CASES-OMITTED$ default: final String errMsg = format("Invalid date type, found: %s", type); throw new BsonInvalidOperationException(errMsg); } }
@Override public T decode(BsonReader reader, DecoderContext decoderContext) { final BsonType type = reader.getCurrentBsonType(); switch(type) { case DATE_TIME: return decode(reader.readDateTime()); case DOUBLE: return decode((long) reader.readDouble()); case INT32: return decode(reader.readInt32()); case INT64: return decode(reader.readInt64()); case NULL: return null; case STRING: return decode(Long.valueOf(reader.readString())); //$CASES-OMITTED$ default: final String errMsg = format("Invalid date type, found: %s", type); throw new BsonInvalidOperationException(errMsg); } }
@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()); }
@Override public TestBean decode(BsonReader reader, DecoderContext decoderContext) { reader.readStartDocument(); TestBean pojo = new TestBean(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { switch (reader.readName()) { case "stringField": pojo.setStringField(reader.getCurrentBsonType() != BsonType.NULL ? reader.readString() : null); break; case "longField": pojo.setLongField(reader.readInt64()); break; case "listStringField": pojo.setListStringField(this.decodeGenericList(reader, decoderContext, String.class)); break; case "setStringField": pojo.setSetStringField(this.decodeGenericSet(reader, decoderContext, String.class)); break; default: Assert.fail("Unexpected name " + reader.getCurrentName()); } } reader.readEndDocument(); return pojo; }
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(); }
@Override public VerseBeanImpl decode(BsonReader reader, DecoderContext context) { Document document = this.documentCodec.decode(reader, context); VerseBeanImpl bean = new VerseBeanImpl(); bean.setId(document.getInteger("_id")); ChapterBeanImpl chapter = new ChapterBeanImpl(); chapter.setId(document.getInteger("chapter_id")); bean.setChapter(chapter); bean.setNumber(document.getString("number")); bean.setText(document.getString("text")); Collection<?> coll = document.get("annotations", Collection.class); return bean; }
@Override public BibleBeanImpl decode(BsonReader reader, DecoderContext context) { Document document = this.documentCodec.decode(reader, context); BibleBeanImpl bean = new BibleBeanImpl(); bean.setId(document.getInteger("_id")); bean.setCopyright(document.getString("copyright")); bean.setEdition(document.getString("edition")); bean.setEletronicTranscriptionSource(document.getString("eletronic_transcription_source")); bean.setEletronicTranscriptionSourceUrl(document.getString("eletronic_transcription_source_url")); bean.setLanguage(document.getString("language")); bean.setName(document.getString("name")); bean.setPrintedSource(document.getString("printed_source")); bean.setUrl(document.getString("url")); return bean; }
/** * {@inheritDoc} */ @Override public BlockVector decode(BsonReader reader, DecoderContext decoderContext) { int x = 0; int y = 0; int z = 0; reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String name = reader.readName(); if ("x".equals(name)) x = reader.readInt32(); else if ("y".equals(name)) y = reader.readInt32(); else if ("z".equals(name)) z = reader.readInt32(); else reader.skipValue(); } reader.readEndDocument(); return new BlockVector(x, y, z); }
/** * {@inhericDoc} */ @Override public T decode(BsonReader reader, DecoderContext decoderContext) { T instance = instantiate(); reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String fieldName = reader.readName(); BsoneeBaseSetter<T> bsoneeBaseSetter = settersByName.get(fieldName); if (bsoneeBaseSetter != null) { bsoneeBaseSetter.set(instance, reader, decoderContext); } else { // TODO Check options whether to throw an exception or not. By default we skip it :) logger.warn("No setter for " + fieldName); reader.skipValue(); } } reader.readEndDocument(); return instance; }
/** * {@inheritDoc} */ @Override public DefaultDomain decode(BsonReader reader, DecoderContext decoderContext) { DefaultDomain domain = new DefaultDomain(); reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String name = reader.readName(); if ("players".equals(name)) { reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) domain.addPlayer(UUID.fromString(reader.readString())); reader.readEndArray(); } else if ("groups".equals(name)) { reader.readStartArray(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) domain.addGroup(reader.readString()); reader.readEndArray(); } else { reader.skipValue(); } } reader.readEndDocument(); return domain; }
@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 MonthDay decode(BsonReader reader, DecoderContext decoderContext) { MonthDay monthDay; reader.readStartDocument(); if (this.monthAsString) { monthDay = MonthDay.of(Month.valueOf(reader.readString(this.monthKey)), reader.readInt32(this.dayOfMonthKey)); } else { monthDay = MonthDay.of(reader.readInt32(this.monthKey), reader.readInt32(this.dayOfMonthKey)); } reader.readEndDocument(); return monthDay; }
@Override public Locale decode(BsonReader reader, DecoderContext decoderContext) { reader.readStartDocument(); String language = reader.readString(this.languageKey); String country = ""; String variant = ""; if (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { reader.readName(); country = reader.readString(); if (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { reader.readName(); variant = reader.readString(); } } reader.readEndDocument(); return new Locale(language, country, variant); }
@Override public Period decode( BsonReader reader, DecoderContext decoderContext) { return parse(reader.readString()); }
@Override public ZoneOffset decode( BsonReader reader, DecoderContext decoderContext) { return ofTotalSeconds(reader.readInt32()); }
@Override public LocalTime decode( BsonReader reader, DecoderContext decoderContext) { return ofEpochMilli(reader.readDateTime()) .atOffset(UTC) .toLocalTime(); }
@Override public LocalDate decode( BsonReader reader, DecoderContext decoderContext) { return ofEpochMilli(reader.readDateTime()) .atOffset(UTC) .toLocalDate(); }
@Override public OffsetTime decode( BsonReader reader, DecoderContext decoderContext) { return OffsetTime.parse(reader.readString()); }
@Override public Year decode( BsonReader reader, DecoderContext decoderContext) { return of(reader.readInt32()); }
@Override public Instant decode( BsonReader reader, DecoderContext decoderContext) { return ofEpochMilli(reader.readDateTime()); }
@Override public ZonedDateTime decode( BsonReader reader, DecoderContext decoderContext) { return ZonedDateTime.parse(reader.readString()); }
@Override public OffsetDateTime decode( BsonReader reader, DecoderContext decoderContext) { return parse(reader.readString()); }
private <T> T decodeValue(ByteBuffer byteBuffer, Codec<T> codec) { try (BsonBinaryReader reader = new BsonBinaryReader(byteBuffer)) { reader.readStartDocument(); String name = reader.readName(); assertEquals("value", name); return codec.decode(reader, DecoderContext.builder().build()); } }