diff --git a/hadoop-hdds/common/src/main/java/org/apache/hadoop/utils/db/CodecRegistry.java b/hadoop-hdds/common/src/main/java/org/apache/hadoop/utils/db/CodecRegistry.java index afa72ad6390..1dd18420b10 100644 --- a/hadoop-hdds/common/src/main/java/org/apache/hadoop/utils/db/CodecRegistry.java +++ b/hadoop-hdds/common/src/main/java/org/apache/hadoop/utils/db/CodecRegistry.java @@ -44,16 +44,13 @@ public class CodecRegistry { * @param Type of the return value. * @return the object with the parsed field data */ - public T asObject(byte[] rawData, Class format) throws IOException { + public T asObject(byte[] rawData, Class format) + throws IOException { if (rawData == null) { return null; } - if (valueCodecs.containsKey(format)) { - return (T) valueCodecs.get(format).fromPersistedFormat(rawData); - } else { - throw new IllegalStateException( - "Codec is not registered for type: " + format); - } + Codec codec = getCodec(format); + return (T) codec.fromPersistedFormat(rawData); } /** @@ -66,14 +63,39 @@ public class CodecRegistry { public byte[] asRawData(T object) throws IOException { Preconditions.checkNotNull(object, "Null value shouldn't be persisted in the database"); + Codec codec = getCodec(object); + return codec.toPersistedFormat(object); + } + + /** + * Get codec for the typed object including class and subclass. + * @param object typed object. + * @return Codec for the typed object. + * @throws IOException + */ + private Codec getCodec(T object) throws IOException { Class format = (Class) object.getClass(); + return getCodec(format); + } + + + /** + * Get codec for the typed object including class and subclass. + * @param Type of the typed object. + * @return Codec for the typed object. + * @throws IOException + */ + private Codec getCodec(Class format) throws IOException { + Codec codec; if (valueCodecs.containsKey(format)) { - Codec codec = (Codec) valueCodecs.get(format); - return codec.toPersistedFormat(object); + codec = (Codec) valueCodecs.get(format); + } else if (valueCodecs.containsKey(format.getSuperclass())) { + codec = (Codec) valueCodecs.get(format.getSuperclass()); } else { throw new IllegalStateException( "Codec is not registered for type: " + format); } + return codec; } /**