@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(); }
@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 T decode(BsonReader reader, DecoderContext decoderContext) { T map = newInstance(); reader.readStartDocument(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { String key = reader.readName(); Object value; Codec fieldMappingCodec = fieldMappingCodecs.get(key); if (fieldMappingCodec != null) { value = fieldMappingCodec.decode(reader, decoderContext); } else { value = readValue(reader, decoderContext); } map.put(key, value); } reader.readEndDocument(); return map; }
@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; }
private Object handleArrayForBsonReader(BsonReader bsonReader, Field field, BsonMapperConfig bsonMapperConfig) { Class<?> fieldType = field.getType(); ArrayList<Object> arrayList = new ArrayList<Object>(); bsonReader.readStartArray(); while (bsonReader.readBsonType() != BsonType.END_OF_DOCUMENT) { BsonType currentBsonType = bsonReader.getCurrentBsonType(); if (currentBsonType == BsonType.NULL) { continue; } if (currentBsonType == BsonType.ARRAY) { arrayList.add(decode(bsonReader, field, bsonMapperConfig)); } else { Object javaValue; if (currentBsonType == BsonType.DOCUMENT) { javaValue = BsonValueConverterRepertory.getBsonDocumentConverter().decode(bsonReader, fieldType.getComponentType(), bsonMapperConfig); } else { javaValue = BsonValueConverterRepertory.getByteIOConverterByBsonType(currentBsonType).decode(bsonReader); } arrayList.add(javaValue); } } bsonReader.readEndArray(); return arrayList.toArray((Object[]) Array.newInstance(fieldType.getComponentType(), 0)); }
@Override public LocalDateTime decode( BsonReader reader, DecoderContext decoderContext) { return ofEpochMilli(reader.readDateTime()) .atOffset(UTC) .toLocalDateTime(); }
@Override public ZoneOffset decode( BsonReader reader, DecoderContext decoderContext) { return ofTotalSeconds(reader.readInt32()); }
@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); }
@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()); }
@Override public final InetAddress decode(final BsonReader reader, final DecoderContext decoderContext) { try { return InetAddress.getByName(reader.readString()); } catch (Exception e) { throw new IllegalArgumentException(e); } }
@Override public SipMessage decode(BsonReader reader, DecoderContext decoderContext) { Document document = codec.decode(reader, decoderContext); SipMessage message = new SipMessage(); message.setId(document.getObjectId("_id").toHexString()); message.setMillis(document.getLong("millis")); Object nanos = document.get("nanos"); if (nanos != null) { message.setNanos((Integer) nanos); } String srcIp = document.getString("src_ip"); message.setSrcIp(srcIp); message.setSrcPort(document.getInteger("src_port")); message.setSrcHost(document.getString("src_host")); String dstIp = document.getString("dst_ip"); message.setDstIp(dstIp); message.setDstPort(document.getInteger("dst_port")); message.setDstHost(document.getString("dst_host")); message.setMethod(document.getString("method")); message.setCallId(document.getString("call_id")); message.setCaller(document.getString("caller")); message.setCallee(document.getString("callee")); Object payload = document.get("payload"); if (payload != null) { message.setPayload((String) payload); } return message; }
@Override public SyncError decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncError error = new SyncError(document.getString(SyncAttrs.ERROR_MESSAGE)); error.setThreadName(document.getString(SyncAttrs.THREAD_NAME)); error.setFullStackTrace(document.getString(SyncAttrs.TRACE)); return error; }
@SuppressWarnings("rawtypes") @Override public OracleToMongoEvent decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMapAndEventDecoder decoder = new SyncMapAndEventDecoder(); SyncEvent event = decoder.decodeSyncEvent(document); return (OracleToMongoEvent) event; }
@Override public SyncConnectionInfo decode(BsonReader reader, DecoderContext decoderContext) { SyncConnectionInfo con = new SyncConnectionInfo(); Map<String, Double> hostToPortMap=null; Document document = documentCodec.decode(reader, decoderContext); con.setConnectionId(document.getObjectId(String.valueOf(ConnectionInfoAttributes._id))); con.setConnectionName(document.getString(String.valueOf(ConnectionInfoAttributes.connectionName))); con.setDbName(document.getString(String.valueOf(ConnectionInfoAttributes.dbName))); con.setDbType(document.getString(String.valueOf(ConnectionInfoAttributes.dbType))); /* try { if(document.get(String.valueOf(ConnectionInfoAttributes.password))!=null){ //if(!(document.get(String.valueOf(ConnectionInfoAttributes.password)) instanceof String)) con.setPassword(EncryptorDecryptor.decrypt(((Binary)document.get(String.valueOf(ConnectionInfoAttributes.password))).getData())); else con.setPassword(document.getString(String.valueOf(ConnectionInfoAttributes.password))); } } catch (Exception e) { e.printStackTrace(); }*/ con.setPassword(document.getString(String.valueOf(ConnectionInfoAttributes.password))); con.setUserName(document.getString(String.valueOf(ConnectionInfoAttributes.userName))); con.setUrl(document.getString(String.valueOf(ConnectionInfoAttributes.url))); @SuppressWarnings("unchecked") List<Document> hostToPortMapDoc = (List<Document>) document.get(String.valueOf(ConnectionInfoAttributes.hostToPortMap)); if( hostToPortMapDoc !=null && !hostToPortMapDoc.isEmpty()){ hostToPortMap = new HashMap<String, Double>(); for(Document doc : hostToPortMapDoc){ hostToPortMap.put(doc.getString(String.valueOf(ConnectionInfoAttributes.host)), doc.getDouble(String.valueOf(ConnectionInfoAttributes.port))); } con.setHostToPortMap(hostToPortMap); } logger.info("Decoder finished. Created Object is : "+con); return con; }
@SuppressWarnings("rawtypes") @Override public OracleToMongoGridFsEvent decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMapAndEventDecoder decoder = new SyncMapAndEventDecoder(); SyncEvent event = decoder.decodeSyncEvent(document); return (OracleToMongoGridFsEvent) event; }
@Override public SyncEvent decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMapAndEventDecoder decoder = new SyncMapAndEventDecoder(); SyncEvent event = decoder.decodeSyncEvent(document); return event; }
@Override public OracleToMongoSyncEvent decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMapAndEventDecoder decoder = new SyncMapAndEventDecoder(); @SuppressWarnings("rawtypes") SyncEvent event = decoder.decodeSyncEvent(document); return (OracleToMongoSyncEvent) event; }
@Override public MongoToOracleSyncEvent decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMapAndEventDecoder decoder = new SyncMapAndEventDecoder(); MongoToOracleSyncEvent event = (MongoToOracleSyncEvent) decoder.decodeSyncEvent(document); return event; }
@SuppressWarnings("unchecked") @Override public SyncUser decode(BsonReader reader, DecoderContext decoderContext) { logger.info("Start of decode method"); SyncUser user = new SyncUser(); Document document = documentCodec.decode(reader, decoderContext); user.setUserid(document.getString(String.valueOf(UserDetailAttributes._id))); user.setSourceDbMap((Map<String, Set<String>>) document.get(String.valueOf(UserDetailAttributes.sourceDbMap))); user.setTargetDbMap((Map<String, Set<String>>) document.get(String.valueOf(UserDetailAttributes.targetDbMap))); user.setUserRoles((List<String>) document.get("roles")); logger.info("Decode completed. Object formed is "+user.toString()); return user; }
@Override public OracleToMongoGridFsEvent decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMapAndEventGridFsDecoder decoder = new SyncMapAndEventGridFsDecoder(); OracleToMongoGridFsEvent event = decoder.decodeSyncEvent(document); return event; }
@Override public SyncUserSession decode(BsonReader reader, DecoderContext decoderContext) { SyncUserSession sessionData= new SyncUserSession(); Document document = documentCodec.decode(reader, decoderContext); sessionData.setSessionId(document.getString(String.valueOf(SessionAttributes._id))); sessionData.setLoginTime(document.getDate(String.valueOf(SessionAttributes.loginTime))); sessionData.setUserid(document.getString(String.valueOf(SessionAttributes.userid))); sessionData.setClientIPAddress(document.getString(String.valueOf(SessionAttributes.clientIPAddress))); sessionData.setClientAgent(document.getString(String.valueOf(SessionAttributes.clientAgent))); sessionData.setClientHostName(document.getString(String.valueOf(SessionAttributes.clientHostName))); return sessionData; }
@Override public MongoToOracleEvent decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMapAndEventDecoder decoder = new SyncMapAndEventDecoder(); MongoToOracleEvent event = (MongoToOracleEvent) decoder.decodeSyncEvent(document); return event; }
@Override public SyncMarker decode(BsonReader reader, DecoderContext decoderContext) { Document document = documentCodec.decode(reader, decoderContext); SyncMarker marker = new SyncMarker(); marker.setAllRowsFetchedFromDb(document.getBoolean(SyncAttrs.ALL_ROWS_FETCHED, false)); marker.setTotalRows(document.getInteger(SyncAttrs.TOTAL_ROWS, -1)); marker.setRowsDumped(document.getInteger(SyncAttrs.ROWS_DUMPED, 0)); marker.setRowsRead(document.getInteger(SyncAttrs.ROWS_READ, 0)); marker.setStartTime(document.getDate(SyncAttrs.START_TIME)); marker.setEndTime(document.getDate(SyncAttrs.END_TIME)); return marker; }
default <T> void decode(BsonReader reader, T instance, DecoderContext decoderContext, MappedField mappedField) { try { if (checkBsonTypeAndSkipOnMisMatch(reader)) { decodeInternal(reader, instance, mappedField.getField()); } } catch (IllegalAccessException e) { LOGGER.warn("Could not decode mappedField.", mappedField, e); } }
default boolean checkBsonTypeAndSkipOnMisMatch(BsonReader reader) { if (getBsonType().equals(reader.getCurrentBsonType())) { return true; } else { LOGGER.warn("Expected {} from reader but got {}. Skipping value.", getBsonType(), reader.getCurrentBsonType()); reader.skipValue(); } return false; }
@Override default T decode(BsonReader reader, DecoderContext decoderContext) { T newInstance; if (reader.getCurrentBsonType() == null || reader.getCurrentBsonType() == BsonType.DOCUMENT) { reader.readStartDocument(); newInstance = decodeFields(reader, decoderContext, newInstance()); reader.readEndDocument(); return newInstance; } else { LOGGER.error("Expected to read document but reader is in state {}. Skipping value!", reader.getCurrentBsonType()); reader.skipValue(); return null; } }
private Object readValue(final BsonReader reader, final DecoderContext decoderContext) { BsonType bsonType = reader.getCurrentBsonType(); if (bsonType == BsonType.NULL) { reader.readNull(); return null; } else if (bsonType == BsonType.ARRAY) { return readList(reader, decoderContext); } else if (bsonType == BsonType.BINARY && BsonBinarySubType.isUuid(reader.peekBinarySubType()) && reader.peekBinarySize() == 16) { return codecRegistry.get(UUID.class).decode(reader, decoderContext); } return bsonTypeCodecMap.get(bsonType).decode(reader, decoderContext); }
@Override public Object decode(BsonReader reader, DecoderContext decoderContext) { List<Boolean> arrayList = new ArrayList(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { arrayList.add(reader.readBoolean()); } boolean[] booleans = new boolean[arrayList.size()]; int i = 0; for (boolean aPrimitiveBoolean : arrayList) { booleans[i++] = aPrimitiveBoolean; } return booleans; }
@Override public Object decode(BsonReader reader, DecoderContext decoderContext) { List<Character> arrayList = new ArrayList(); while (reader.readBsonType() != BsonType.END_OF_DOCUMENT) { arrayList.add((char) reader.readInt32()); } char[] chars = new char[arrayList.size()]; int i = 0; for (char aPrimitive : arrayList) { chars[i++] = aPrimitive; } return chars; }