From fb55c1c97e61c412583ea2f17ef7cc05aa7b8850 Mon Sep 17 00:00:00 2001 From: Vineet Singh <78719701+Vineet829@users.noreply.github.com> Date: Sat, 14 Nov 2026 09:43:35 +0530 Subject: [PATCH 1/5] Fix #343: add Avro read feature for Single Object Encoding --- avro/README.md | 19 + .../dataformat/avro/AvroReadFeature.java | 18 +- .../jackson/dataformat/avro/AvroSchema.java | 45 +- .../dataformat/avro/deser/AvroParserImpl.java | 29 +- .../dataformat/avro/deser/RootReader.java | 13 +- .../avro/SingleObjectEncoding343Test.java | 485 ++++++++++++++++++ .../tofix/SingleObjectEncoding343Test.java | 107 ---- release-notes/CREDITS | 12 + release-notes/VERSION | 7 + 9 files changed, 619 insertions(+), 116 deletions(-) create mode 100644 avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java delete mode 100644 avro/src/test/java/tools/jackson/dataformat/avro/tofix/SingleObjectEncoding343Test.java diff --git a/avro/README.md b/avro/README.md index ab8b63591..5382e4c92 100644 --- a/avro/README.md +++ b/avro/README.md @@ -101,6 +101,25 @@ Employee empl = mapper.reader(Employee.class) .readValue(avroData); ``` +### Reading Single Object Encoding + +Avro "Single Object Encoding" (written by Avro's `BinaryMessageEncoder`, and by `toByteBuffer()` +of classes compiled from Avro schemas) adds a 10-byte header before each value: a 2-byte marker +and the fingerprint of the writer schema. To read such values, enable +`AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` (since 3.4): + +```java +byte[] message = ... ; // as written by BinaryMessageEncoder +Employee empl = mapper.readerFor(Employee.class) + .with(schema) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .readValue(message); +``` + +The header of each value is verified: reading fails if its fingerprint is not that of the +writer schema used for reading. The feature needs to be enabled explicitly because the header +can not be reliably detected from content. + ## Writing avro data Writing Avro-encoded data follows similar pattern: diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java index 5a1af1fcb..ae12d4a2a 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java @@ -16,7 +16,23 @@ public enum AvroReadFeature *

* Enabled by default to preserve the existing behavior. */ - AVRO_BUFFERING(true) + AVRO_BUFFERING(true), + + /** + * Feature that tells parser that each root-level value is in Avro "Single Object + * Encoding" (as written by {@code BinaryMessageEncoder} of Apache Avro lib): + * preceded by a header of 2-byte marker ({@code 0xC3 0x01}) and 8-byte + * fingerprint of the writer schema. Parser fails with + * {@link tools.jackson.core.exc.StreamReadException} if the marker is wrong, or the + * fingerprint is not that of the writer schema used for reading + * (see {@link AvroSchema#getWriterFingerprint()}). + *

+ * Disabled by default, since the header can not be reliably detected: + * "raw" content may start with the same two bytes. + * + * @since 3.4 + */ + READ_SINGLE_OBJECT_ENCODING(false) ; private final boolean _defaultState; diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java index 5a593f472..a7a72c952 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java @@ -7,6 +7,7 @@ import org.apache.avro.SchemaCompatibility; import org.apache.avro.SchemaCompatibility.SchemaCompatibilityType; import org.apache.avro.SchemaCompatibility.SchemaPairCompatibility; +import org.apache.avro.SchemaNormalization; import tools.jackson.core.FormatSchema; import tools.jackson.core.JsonParser; @@ -36,6 +37,8 @@ public class AvroSchema implements FormatSchema */ protected final AtomicReference _reader = new AtomicReference<>(); + private final AtomicReference _writerFingerprint = new AtomicReference<>(); + public AvroSchema(Schema asch) { _writerSchema = asch; @@ -97,7 +100,7 @@ public AvroSchema withReaderSchema(AvroSchema readerSchema) throw DatabindException.from((JsonParser) null, String.format("Incompatible writer/reader schemas: %s", comp.getDescription())); } - return Resolving.create(w, r); + return Resolving.create(w, r, _fingerprintSchema()); } private boolean _schemaNamesEqual(Schema w, Schema r) @@ -135,7 +138,7 @@ public AvroSchema withUnsafeReaderSchema(AvroSchema readerSchema) return this; } w = Schema.applyAliases(w, r); - return Resolving.create(w, r); + return Resolving.create(w, r, _fingerprintSchema()); } @Override @@ -148,6 +151,27 @@ public String getSchemaType() { */ public Schema getAvroSchema() { return _writerSchema; } + /** + * Accessor for the 64-bit ("CRC-64-AVRO") fingerprint of the writer schema: the one + * that the header of Avro "Single Object Encoding" contains. With a reader schema, + * it is that of the writer schema as given (without aliases of the reader schema). + * + * @since 3.4 + */ + public long getWriterFingerprint() + { + Long fingerprint = _writerFingerprint.get(); + if (fingerprint == null) { + fingerprint = SchemaNormalization.parsingFingerprint64(_fingerprintSchema()); + _writerFingerprint.set(fingerprint); + } + return fingerprint; + } + + Schema _fingerprintSchema() { + return _writerSchema; + } + /* /********************************************************************** /* Factory methods @@ -207,14 +231,22 @@ private final static class Resolving extends AvroSchema { private final Schema _readerSchema; - public Resolving(Schema writer, Schema reader) + private final Schema _originalWriterSchema; + + public Resolving(Schema writer, Schema reader, Schema originalWriter) { super(writer); _readerSchema = reader; + _originalWriterSchema = originalWriter; } - public static Resolving create(Schema writer, Schema reader) { - return new Resolving(writer, reader); + public static Resolving create(Schema writer, Schema reader, Schema originalWriter) { + return new Resolving(writer, reader, originalWriter); + } + + @Override + Schema _fingerprintSchema() { + return _originalWriterSchema; } @Override @@ -244,7 +276,8 @@ public boolean equals(Object o) { if ((o == null) || o.getClass() != getClass()) return false; Resolving other = (Resolving) o; return _writerSchema.equals(other._writerSchema) - && _readerSchema.equals(other._readerSchema); + && _readerSchema.equals(other._readerSchema) + && _originalWriterSchema.equals(other._originalWriterSchema); } } } diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java b/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java index 88f5494d7..8687e2956 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java @@ -9,6 +9,7 @@ import tools.jackson.core.io.IOContext; import tools.jackson.core.sym.PropertyNameMatcher; import tools.jackson.dataformat.avro.AvroParser; +import tools.jackson.dataformat.avro.AvroReadFeature; import tools.jackson.dataformat.avro.AvroSchema; /** @@ -28,6 +29,8 @@ public abstract class AvroParserImpl */ protected final static int LONGEST_NON_CHUNKED_BINARY_READ = 250_000; + private final static int SINGLE_OBJECT_HEADER_LENGTH = 10; + /* /********************************************************************** /* Decoding state @@ -194,7 +197,10 @@ public int nextNameMatch(PropertyNameMatcher matcher) throws JacksonException @Override public final void _initSchema(AvroSchema schema) throws JacksonException { - _avroContext = new RootReader(this, schema.getReader()); + Long singleObjectFingerprint = isEnabled(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + ? schema.getWriterFingerprint() + : null; + _avroContext = new RootReader(this, schema.getReader(), singleObjectFingerprint); } /* @@ -521,6 +527,27 @@ public long getRemainingElements() */ } + final void _readSingleObjectHeader(long expectedFingerprint) throws IOException + { + decodeFixed(SINGLE_OBJECT_HEADER_LENGTH); + final byte[] header = _binaryValue; + _binaryValue = null; + if ((header[0] != (byte) 0xC3) || (header[1] != (byte) 0x01)) { + _reportError(String.format( +"Invalid Avro Single Object Encoding header: expected marker bytes 0xC3 0x01, got 0x%02X 0x%02X", + header[0] & 0xFF, header[1] & 0xFF)); + } + long fingerprint = 0L; + for (int i = SINGLE_OBJECT_HEADER_LENGTH - 1; i >= 2; --i) { + fingerprint = (fingerprint << 8) | (header[i] & 0xFFL); + } + if (fingerprint != expectedFingerprint) { + _reportError(String.format( +"Avro Single Object Encoding schema fingerprint mismatch: value has 0x%016X, writer schema used for reading has 0x%016X", + fingerprint, expectedFingerprint)); + } + } + /* /********************************************************************** /* Methods for AvroReadContext implementations: decoding int diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java index e6b5d6418..8a692f5bb 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java @@ -13,13 +13,20 @@ public class RootReader extends AvroReadContext { private final AvroParserImpl _parser; private final AvroStructureReader _valueReader; + private final Long _singleObjectFingerprint; public RootReader(AvroParserImpl parser, AvroStructureReader valueReader) { + this(parser, valueReader, null); + } + + RootReader(AvroParserImpl parser, + AvroStructureReader valueReader, Long singleObjectFingerprint) { super(null, null); _type = TYPE_ROOT; _parser = parser; _valueReader = valueReader; + _singleObjectFingerprint = singleObjectFingerprint; } @Override @@ -29,10 +36,14 @@ public JsonToken nextToken() throws IOException { if (_parser.checkInputEnd()) { // 26-Aug-2019, tatu: As per [dataformats-binary#177], 0-field Records consume // no content, and if so we MUST NOT indicate end-of-content: - if (!_valueReader.consumesNoContent()) { + // [dataformats-binary#343]: unless each value has a header + if ((_singleObjectFingerprint != null) || !_valueReader.consumesNoContent()) { return null; } } + if (_singleObjectFingerprint != null) { + _parser._readSingleObjectHeader(_singleObjectFingerprint); + } return _valueReader.newReader(this, _parser).nextToken(); } diff --git a/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java new file mode 100644 index 000000000..16c6f9b47 --- /dev/null +++ b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java @@ -0,0 +1,485 @@ +package tools.jackson.dataformat.avro; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.EOFException; +import java.nio.ByteBuffer; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.apache.avro.Schema; +import org.apache.avro.SchemaNormalization; +import org.apache.avro.generic.GenericData; +import org.apache.avro.generic.GenericDatumWriter; +import org.apache.avro.generic.GenericRecord; +import org.apache.avro.generic.GenericRecordBuilder; +import org.apache.avro.io.BinaryEncoder; +import org.apache.avro.io.DatumWriter; +import org.apache.avro.io.EncoderFactory; +import org.apache.avro.message.BinaryMessageEncoder; +import org.junit.jupiter.api.Test; + +import tools.jackson.core.JacksonException; +import tools.jackson.core.JsonParser; +import tools.jackson.core.JsonToken; +import tools.jackson.core.StreamReadConstraints; +import tools.jackson.core.exc.StreamConstraintsException; +import tools.jackson.core.exc.StreamReadException; +import tools.jackson.databind.DeserializationFeature; +import tools.jackson.databind.JsonNode; +import tools.jackson.databind.MappingIterator; +import tools.jackson.databind.ObjectReader; +import tools.jackson.dataformat.avro.testsupport.ThrottledInputStream; + +import static org.junit.jupiter.api.Assertions.*; + +// [dataformats-binary#343]: reading Avro "Single Object Encoding" +public class SingleObjectEncoding343Test extends AvroTestBase +{ + private final static String SCHEMA_JSON = "{" + + "\"type\": \"record\"," + + "\"name\": \"SampleRecord\"," + + "\"fields\": [" + + " {\"name\": \"name\", \"type\": \"string\"}" + + "]}"; + + private final static String OTHER_SCHEMA_JSON = "{" + + "\"type\": \"record\"," + + "\"name\": \"OtherRecord\"," + + "\"fields\": [" + + " {\"name\": \"name\", \"type\": \"string\"}" + + "]}"; + + private final Schema APACHE_SCHEMA = new Schema.Parser().parse(SCHEMA_JSON); + + private final AvroSchema JACKSON_SCHEMA = new AvroSchema(APACHE_SCHEMA); + + private final AvroMapper[] MAPPERS = new AvroMapper[] { + newMapper(), + newApacheMapper(), + new AvroMapper(AvroFactory.builderWithApacheDecoder() + .disable(AvroReadFeature.AVRO_BUFFERING).build()) + }; + + @Test + public void testReadSingleObjectEncoding() throws Exception + { + // Encode using Apache Avro's Single Object Encoding (BinaryMessageEncoder), + // which is what SpecificRecord.toByteBuffer() uses in Apache Avro 1.8+. + byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); + assertEquals((byte) 0xC3, bytes[0], "First magic byte should be 0xC3"); + assertEquals((byte) 0x01, bytes[1], "Second magic byte should be 0x01"); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = singleObjectReader(mapper).readTree(bytes); + assertNotNull(result); + assertEquals("apm", result.get("name").asString()); + } + } + + @Test + public void testReadSequenceOfSingleObjectValues() throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(encodeSingleObject(APACHE_SCHEMA, "a")); + out.write(encodeSingleObject(APACHE_SCHEMA, "bc")); + byte[] bytes = out.toByteArray(); + + for (AvroMapper mapper : MAPPERS) { + try (MappingIterator it = singleObjectReader(mapper) + .forType(JsonNode.class).readValues(bytes)) { + List values = it.readAll(); + assertEquals(2, values.size()); + assertEquals("a", values.get(0).get("name").asString()); + assertEquals("bc", values.get(1).get("name").asString()); + } + try (MappingIterator it = singleObjectReader(mapper) + .forType(JsonNode.class).readValues(new ThrottledInputStream(bytes, 3))) { + List values = it.readAll(); + assertEquals(2, values.size()); + assertEquals("a", values.get(0).get("name").asString()); + assertEquals("bc", values.get(1).get("name").asString()); + } + } + } + + @Test + public void testReadSingleObjectEncodingFromStream() throws Exception + { + byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = singleObjectReader(mapper) + .readTree(new ByteArrayInputStream(bytes)); + assertEquals("apm", result.get("name").asString()); + } + } + + @Test + public void testReadWithReaderSchema() throws Exception + { + Schema readerSchema = new Schema.Parser().parse("{" + + "\"type\": \"record\"," + + "\"name\": \"SampleRecord\"," + + "\"fields\": [" + + " {\"name\": \"name\", \"type\": \"string\"}," + + " {\"name\": \"count\", \"type\": \"int\", \"default\": 7}" + + "]}"); + AvroSchema resolving = JACKSON_SCHEMA.withReaderSchema(new AvroSchema(readerSchema)); + byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = mapper.reader(resolving) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .readTree(bytes); + assertEquals("apm", result.get("name").asString()); + assertEquals(7, result.get("count").asInt()); + } + } + + @Test + public void testReadWithReaderSchemaAliases() throws Exception + { + Schema writerSchema = new Schema.Parser().parse("{" + + "\"type\": \"record\"," + + "\"name\": \"OldRecord\"," + + "\"fields\": [" + + " {\"name\": \"oldName\", \"type\": \"string\"}" + + "]}"); + Schema readerSchema = new Schema.Parser().parse("{" + + "\"type\": \"record\"," + + "\"name\": \"NewRecord\", \"aliases\": [\"OldRecord\"]," + + "\"fields\": [" + + " {\"name\": \"newName\", \"type\": \"string\", \"aliases\": [\"oldName\"]}" + + "]}"); + Schema otherReaderSchema = new Schema.Parser().parse("{" + + "\"type\": \"record\"," + + "\"name\": \"NewRecord\", \"aliases\": [\"OldRecord\"]," + + "\"fields\": [" + + " {\"name\": \"newName\", \"type\": \"string\", \"aliases\": [\"oldName\"]}," + + " {\"name\": \"count\", \"type\": \"int\", \"default\": 7}" + + "]}"); + GenericRecord record = new GenericData.Record(writerSchema); + record.put("oldName", "apm"); + byte[] bytes = toByteArray(new BinaryMessageEncoder( + GenericData.get(), writerSchema).encode(record)); + + final AvroSchema reader = new AvroSchema(readerSchema); + final AvroSchema otherReader = new AvroSchema(otherReaderSchema); + final AvroSchema[] schemas = new AvroSchema[] { + new AvroSchema(writerSchema).withReaderSchema(reader), + new AvroSchema(writerSchema).withUnsafeReaderSchema(reader), + new AvroSchema(writerSchema).withReaderSchema(reader).withReaderSchema(otherReader), + new AvroSchema(writerSchema).withReaderSchema(reader).withUnsafeReaderSchema(otherReader) + }; + final long fingerprint = new AvroSchema(writerSchema).getWriterFingerprint(); + for (AvroSchema schema : schemas) { + assertEquals(fingerprint, schema.getWriterFingerprint()); + } + final AvroSchema renamed = new AvroSchema(new Schema.Parser().parse("{" + + "\"type\": \"record\"," + + "\"name\": \"NewRecord\"," + + "\"fields\": [" + + " {\"name\": \"newName\", \"type\": \"string\"}" + + "]}")).withReaderSchema(otherReader); + assertNotEquals(fingerprint, renamed.getWriterFingerprint()); + assertNotEquals(new AvroSchema(writerSchema).withReaderSchema(otherReader), renamed); + for (AvroMapper mapper : MAPPERS) { + for (AvroSchema schema : schemas) { + JsonNode result = mapper.reader(schema) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .readTree(bytes); + assertEquals("apm", result.get("newName").asString()); + } + JsonNode result = mapper.reader(schemas[2]) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .readTree(bytes); + assertEquals(7, result.get("count").asInt()); + } + } + + @Test + public void testReadEmptyRecords() throws Exception + { + Schema emptySchema = new Schema.Parser().parse( + "{\"type\": \"record\", \"name\": \"Empty\", \"fields\": []}"); + BinaryMessageEncoder encoder = + new BinaryMessageEncoder<>(GenericData.get(), emptySchema); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(toByteArray(encoder.encode(new GenericData.Record(emptySchema)))); + out.write(toByteArray(encoder.encode(new GenericData.Record(emptySchema)))); + byte[] bytes = out.toByteArray(); + assertEquals(20, bytes.length); + + for (AvroMapper mapper : MAPPERS) { + try (MappingIterator it = mapper.reader(new AvroSchema(emptySchema)) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .forType(JsonNode.class).readValues(bytes)) { + assertEquals(0, it.nextValue().size()); + assertEquals(0, it.nextValue().size()); + assertFalse(it.hasNextValue()); + } + } + } + + @Test + public void testFailForTruncatedHeader() throws Exception + { + byte[] bytes = Arrays.copyOf(encodeSingleObject(APACHE_SCHEMA, "apm"), 6); + + for (AvroMapper mapper : MAPPERS) { + JacksonException e = assertThrows(JacksonException.class, + () -> singleObjectReader(mapper).readTree(bytes)); + // Apache decoder reports end-of-input as `EOFException`, wrapped + if (!(e.getCause() instanceof EOFException)) { + verifyException(e, "end-of-input"); + } + } + } + + @Test + public void testFailForMissingHeader() throws Exception + { + byte[] bytes = encodeBinary(APACHE_SCHEMA, "no header in this one"); + byte[] otherVersion = encodeSingleObject(APACHE_SCHEMA, "apm"); + otherVersion[1] = 0x02; + byte[] otherMarker = encodeSingleObject(APACHE_SCHEMA, "apm"); + otherMarker[0] = (byte) 0xC2; + + for (AvroMapper mapper : MAPPERS) { + StreamReadException e = assertThrows(StreamReadException.class, + () -> singleObjectReader(mapper).readTree(bytes)); + verifyException(e, "Invalid Avro Single Object Encoding header"); + + e = assertThrows(StreamReadException.class, + () -> singleObjectReader(mapper).readTree(otherVersion)); + verifyException(e, "Invalid Avro Single Object Encoding header"); + verifyException(e, "got 0xC3 0x02"); + + e = assertThrows(StreamReadException.class, + () -> singleObjectReader(mapper).readTree(otherMarker)); + verifyException(e, "Invalid Avro Single Object Encoding header"); + verifyException(e, "got 0xC2 0x01"); + } + } + + @Test + public void testFailForFingerprintMismatch() throws Exception + { + Schema otherSchema = new Schema.Parser().parse(OTHER_SCHEMA_JSON); + byte[] bytes = encodeSingleObject(otherSchema, "apm"); + String fingerprints = String.format( + "value has 0x%016X, writer schema used for reading has 0x%016X", + SchemaNormalization.parsingFingerprint64(otherSchema), + SchemaNormalization.parsingFingerprint64(APACHE_SCHEMA)); + + for (AvroMapper mapper : MAPPERS) { + StreamReadException e = assertThrows(StreamReadException.class, + () -> singleObjectReader(mapper).readTree(bytes)); + verifyException(e, "schema fingerprint mismatch"); + verifyException(e, fingerprints); + } + } + + @Test + public void testFailForValueWithoutHeaderInSequence() throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(encodeSingleObject(APACHE_SCHEMA, "a")); + out.write(encodeBinary(APACHE_SCHEMA, "no header in this one")); + byte[] bytes = out.toByteArray(); + + for (AvroMapper mapper : MAPPERS) { + try (MappingIterator it = singleObjectReader(mapper) + .forType(JsonNode.class).readValues(bytes)) { + assertEquals("a", it.nextValue().get("name").asString()); + StreamReadException e = assertThrows(StreamReadException.class, + () -> it.nextValue()); + verifyException(e, "Invalid Avro Single Object Encoding header"); + } + } + } + + @Test + public void testHeadersCountForMaxDocumentLength() throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (int i = 0; i < 3; ++i) { + out.write(encodeSingleObject(APACHE_SCHEMA, "abc")); + } + byte[] bytes = out.toByteArray(); + assertEquals(42, bytes.length); + + for (int maxLength : new int[] { 41, 42 }) { + StreamReadConstraints constraints = StreamReadConstraints.builder() + .maxDocumentLength(maxLength).build(); + for (AvroFactoryBuilder b : new AvroFactoryBuilder[] { + AvroFactory.builderWithNativeDecoder(), + AvroFactory.builderWithApacheDecoder(), + AvroFactory.builderWithApacheDecoder().disable(AvroReadFeature.AVRO_BUFFERING) }) { + ObjectReader r = singleObjectReader(new AvroMapper( + b.streamReadConstraints(constraints).build())) + .forType(JsonNode.class); + try (MappingIterator it = r.readValues(new ByteArrayInputStream(bytes))) { + if (maxLength < bytes.length) { + assertThrows(StreamConstraintsException.class, () -> it.readAll()); + } else { + assertEquals(3, it.readAll().size()); + } + } + } + } + } + + @Test + public void testWriterFingerprintSameAsApache() throws Exception + { + Schema schema = new Schema.Parser().parse(a2q("{" + +"'type':'record','name':'Order','namespace':'com.example.orders'," + +"'doc':'An order','aliases':['OldOrder'],'custom':'value'," + +"'fields':[" + +" {'name':'id','type':{'type':'string','logicalType':'uuid'}," + +" 'default':'00000000-0000-0000-0000-000000000000','doc':'Id','aliases':['key']}," + +" {'name':'created','type':{'type':'long','logicalType':'timestamp-millis'},'default':0}," + +" {'name':'amount','type':{'type':'bytes','logicalType':'decimal','precision':9,'scale':2}," + +" 'default':''}," + +" {'name':'status','type':{'type':'enum','name':'Status','namespace':'com.example.common'," + +" 'symbols':['NEW','DONE'],'default':'NEW'},'default':'DONE','order':'descending'}," + +" {'name':'code','type':{'type':'fixed','name':'Code','size':2},'default':'ab'}," + +" {'name':'tags','type':{'type':'map'," + +" 'values':{'type':'array','items':'com.example.common.Status'}},'default':{}}," + +" {'name':'next','type':['null','Order'],'default':null}," + +" {'name':'line','type':{'type':'record','name':'Line'," + +" 'fields':[{'name':'qty','type':'int','default':1}]},'default':{'qty':2}}" + +"]}")); + byte[] bytes = toByteArray(new BinaryMessageEncoder(GenericData.get(), schema) + .encode(new GenericRecordBuilder(schema).build())); + long fingerprint = 0L; + for (int i = 9; i >= 2; --i) { + fingerprint = (fingerprint << 8) | (bytes[i] & 0xFFL); + } + assertEquals(fingerprint, new AvroSchema(schema).getWriterFingerprint()); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = mapper.reader(new AvroSchema(schema)) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .readTree(bytes); + assertEquals("DONE", result.get("status").asString()); + assertEquals(2, result.get("line").get("qty").asInt()); + } + } + + @Test + public void testReadNonRecordRoots() throws Exception + { + final Object[][] cases = new Object[][] { + { "'string'", "abc", "\"abc\"" }, + { "'long'", 123L, "123" }, + { "'null'", null, "null" }, + { "['null','string']", "x", "\"x\"" }, + { "{'type':'array','items':'int'}", List.of(1, 2), "[1,2]" }, + { "{'type':'map','values':'int'}", Map.of("k", 3), "{\"k\":3}" }, + { "{'type':'enum','name':'Size','symbols':['S','M']}", + new GenericData.EnumSymbol(null, "M"), "\"M\"" }, + { "{'type':'fixed','name':'Pair','size':2}", + new GenericData.Fixed(null, new byte[] { 1, 2 }), "\"AQI=\"" } + }; + for (Object[] c : cases) { + final Schema schema = new Schema.Parser().parse(a2q((String) c[0])); + final byte[] value = toByteArray(new BinaryMessageEncoder(GenericData.get(), schema) + .encode(c[1])); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + out.write(value); + out.write(value); + final byte[] bytes = out.toByteArray(); + + for (AvroMapper mapper : MAPPERS) { + ObjectReader r = mapper.reader(new AvroSchema(schema)) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .without(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + for (boolean stream : new boolean[] { false, true }) { + try (JsonParser p = stream + ? r.createParser(new ThrottledInputStream(bytes, 3)) + : r.createParser(bytes)) { + assertEquals(c[2], r.readTree(p).toString()); + assertEquals(c[2], r.readTree(p).toString()); + assertNull(p.nextToken()); + } + } + } + } + } + + @Test + public void testHeaderNotExposedAsBinaryValue() throws Exception + { + byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); + Schema stringSchema = Schema.create(Schema.Type.STRING); + byte[] base64 = toByteArray(new BinaryMessageEncoder(GenericData.get(), stringSchema) + .encode("AQI=")); + + for (AvroMapper mapper : MAPPERS) { + try (JsonParser p = singleObjectReader(mapper).createParser(bytes)) { + assertToken(JsonToken.START_OBJECT, p.nextToken()); + assertNull(p.getEmbeddedObject()); + } + byte[] value = mapper.readerFor(byte[].class) + .with(new AvroSchema(stringSchema)) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + .readValue(base64); + assertArrayEquals(new byte[] { 1, 2 }, value); + } + } + + /** + * Contrast: regular Avro binary encoding (NOT Single Object Encoding) works fine. + */ + @Test + public void testReadRegularBinaryEncoding() throws Exception + { + byte[] bytes = encodeBinary(APACHE_SCHEMA, "apm"); + // First byte should be 0x06 (zigzag VarInt for length 3), not 0xC3 + assertEquals((byte) 0x06, bytes[0]); + + for (AvroMapper mapper : MAPPERS) { + JsonNode result = mapper.reader(JACKSON_SCHEMA).readTree(bytes); + assertNotNull(result); + assertEquals("apm", result.get("name").asString()); + } + } + + private ObjectReader singleObjectReader(AvroMapper mapper) { + return mapper.reader(JACKSON_SCHEMA) + .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING); + } + + private static byte[] encodeSingleObject(Schema schema, String name) throws Exception + { + BinaryMessageEncoder encoder = + new BinaryMessageEncoder<>(GenericData.get(), schema); + return toByteArray(encoder.encode(record(schema, name))); + } + + private static byte[] encodeBinary(Schema schema, String name) throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BinaryEncoder binaryEncoder = EncoderFactory.get().binaryEncoder(out, null); + DatumWriter writer = new GenericDatumWriter<>(schema); + writer.write(record(schema, name), binaryEncoder); + binaryEncoder.flush(); + return out.toByteArray(); + } + + private static GenericRecord record(Schema schema, String name) { + GenericRecord record = new GenericData.Record(schema); + record.put("name", name); + return record; + } + + private static byte[] toByteArray(ByteBuffer buf) { + byte[] bytes = new byte[buf.remaining()]; + buf.get(bytes); + return bytes; + } +} diff --git a/avro/src/test/java/tools/jackson/dataformat/avro/tofix/SingleObjectEncoding343Test.java b/avro/src/test/java/tools/jackson/dataformat/avro/tofix/SingleObjectEncoding343Test.java deleted file mode 100644 index 20ad613a1..000000000 --- a/avro/src/test/java/tools/jackson/dataformat/avro/tofix/SingleObjectEncoding343Test.java +++ /dev/null @@ -1,107 +0,0 @@ -package tools.jackson.dataformat.avro.tofix; - -import java.io.ByteArrayOutputStream; -import java.nio.ByteBuffer; - -import org.apache.avro.Schema; -import org.apache.avro.generic.GenericData; -import org.apache.avro.generic.GenericDatumWriter; -import org.apache.avro.generic.GenericRecord; -import org.apache.avro.io.BinaryEncoder; -import org.apache.avro.io.DatumWriter; -import org.apache.avro.io.EncoderFactory; -import org.apache.avro.message.BinaryMessageEncoder; - -import org.junit.jupiter.api.Test; - -import tools.jackson.databind.JsonNode; -import tools.jackson.dataformat.avro.AvroMapper; -import tools.jackson.dataformat.avro.AvroSchema; -import tools.jackson.dataformat.avro.testutil.failure.JacksonTestFailureExpected; - -import static org.junit.jupiter.api.Assertions.*; - -/** - * Reproducer for [dataformats-binary#343]: decoding data encoded with Apache Avro's - * Single Object Encoding (magic bytes 0xC3 0x01 + 8-byte schema fingerprint + payload) - * fails with "Invalid length indicator for String: -98". - */ -public class SingleObjectEncoding343Test -{ - private static final String SCHEMA_JSON = "{" - + "\"type\": \"record\"," - + "\"name\": \"SampleRecord\"," - + "\"fields\": [" - + " {\"name\": \"name\", \"type\": \"string\"}" - + "]}"; - - private final AvroMapper MAPPER = new AvroMapper(); - - /** - * Test showing the failure: data encoded with Apache Avro's BinaryMessageEncoder - * (Single Object Encoding) cannot be decoded by Jackson's AvroMapper. - * The first two bytes are the magic 0xC3 0x01 which decode as zigzag VarInt -98, - * causing "Invalid length indicator for String: -98". - */ - @JacksonTestFailureExpected - @Test - public void testReadSingleObjectEncoding() throws Exception - { - Schema apacheSchema = new Schema.Parser().parse(SCHEMA_JSON); - AvroSchema jacksonSchema = new AvroSchema(apacheSchema); - - // Encode using Apache Avro's Single Object Encoding (BinaryMessageEncoder), - // which is what SpecificRecord.toByteBuffer() uses in Apache Avro 1.8+. - // The encoded bytes start with magic: 0xC3 0x01 - BinaryMessageEncoder encoder = - new BinaryMessageEncoder<>(GenericData.get(), apacheSchema); - GenericRecord record = new GenericData.Record(apacheSchema); - record.put("name", "apm"); - ByteBuffer encoded = encoder.encode(record); - byte[] bytes = toByteArray(encoded); - - // Verify the magic bytes are present (the root cause of the failure) - assertEquals((byte) 0xC3, bytes[0], "First magic byte should be 0xC3"); - assertEquals((byte) 0x01, bytes[1], "Second magic byte should be 0x01"); - - // This currently fails with: - // "Invalid length indicator for String: -98" - // because Jackson tries to decode 0xC3 0x01 as a zigzag VarInt string length - JsonNode result = MAPPER.reader(jacksonSchema).readTree(bytes); - assertNotNull(result); - assertEquals("apm", result.get("name").asString()); - } - - /** - * Contrast: regular Avro binary encoding (NOT Single Object Encoding) works fine. - */ - @Test - public void testReadRegularBinaryEncoding() throws Exception - { - Schema apacheSchema = new Schema.Parser().parse(SCHEMA_JSON); - AvroSchema jacksonSchema = new AvroSchema(apacheSchema); - - // Encode using regular binary encoder (no SOE header) - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BinaryEncoder binaryEncoder = EncoderFactory.get().binaryEncoder(out, null); - DatumWriter writer = new GenericDatumWriter<>(apacheSchema); - GenericRecord record = new GenericData.Record(apacheSchema); - record.put("name", "apm"); - writer.write(record, binaryEncoder); - binaryEncoder.flush(); - byte[] bytes = out.toByteArray(); - - // First byte should be 0x06 (zigzag VarInt for length 3), not 0xC3 - assertEquals((byte) 0x06, bytes[0]); - - JsonNode result = MAPPER.reader(jacksonSchema).readTree(bytes); - assertNotNull(result); - assertEquals("apm", result.get("name").asString()); - } - - private static byte[] toByteArray(ByteBuffer buf) { - byte[] bytes = new byte[buf.remaining()]; - buf.get(bytes); - return bytes; - } -} diff --git a/release-notes/CREDITS b/release-notes/CREDITS index bcf7e47cd..26973d684 100644 --- a/release-notes/CREDITS +++ b/release-notes/CREDITS @@ -125,3 +125,15 @@ Dhanraj E (@Dhanu-dynamic) * Contributed #901: (avro) Apache decoder allocates buffer for full declared length of `string` value or Map key before reading content (3.1.9) + +@birTiwana + +* Reported #343: (avro) Add `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` to decode Avro + "Single Object Encoding" + (3.4.0) + +Vineet Singh (@Vineet829) + +* Contributed #343: (avro) Add `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` to decode Avro + "Single Object Encoding" + (3.4.0) diff --git a/release-notes/VERSION b/release-notes/VERSION index 817c21e99..35ecad3f6 100644 --- a/release-notes/VERSION +++ b/release-notes/VERSION @@ -14,6 +14,13 @@ implementations) === Releases === ------------------------------------------------------------------------ +3.4.0 (not yet released) + +#343: (avro) Add `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` to decode Avro + "Single Object Encoding" (as written by `BinaryMessageEncoder`) + (reported by @birTiwana) + (contributed by @Vineet829) + 3.3.0 (07-Nov-2026) #398: (protobuf) Add `ProtobufReadFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE` From c5eab7b9223dcbe32d1d948d26aa931b6d5f1dcf Mon Sep 17 00:00:00 2001 From: Tatu Saloranta Date: Mon, 23 Nov 2026 17:55:57 -0800 Subject: [PATCH 2/5] Document strict fingerprint check; minor AvroSchema cleanups (#343) - Javadoc for READ_SINGLE_OBJECT_ENCODING: the schema used must be the exact writer schema (by Parsing Canonical Form), not just a compatible one - Cache writer fingerprint in a plain long + volatile flag instead of AtomicReference - Include original writer schema in Resolving.hashCode(), to match equals() Co-Authored-By: Claude Opus 5.5 --- .../dataformat/avro/AvroReadFeature.java | 9 ++++++++ .../jackson/dataformat/avro/AvroSchema.java | 22 +++++++++++++------ 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java index ae12d4a2a..c653b2c08 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroReadFeature.java @@ -27,6 +27,15 @@ public enum AvroReadFeature * fingerprint is not that of the writer schema used for reading * (see {@link AvroSchema#getWriterFingerprint()}). *

+ * Note that the check is strict: schema used for reading (or, with + * {@link AvroSchema#withReaderSchema}, the writer schema given) must be the exact + * schema used for writing, as determined by its "Parsing Canonical Form", and + * not just a compatible one. For example, a schema generated with + * {@link AvroMapper#schemaFor} that differs from the writer schema in name or + * namespace of a named type will fail the check, even if the content itself could be + * decoded with it. Unlike Avro's {@code BinaryMessageDecoder} there is no + * lookup of alternate writer schemas by fingerprint. + *

* Disabled by default, since the header can not be reliably detected: * "raw" content may start with the same two bytes. * diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java index 656d45223..e735c60ca 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java @@ -41,7 +41,14 @@ public class AvroSchema implements FormatSchema */ protected final AtomicReference _reader = new AtomicReference<>(); - private final AtomicReference _writerFingerprint = new AtomicReference<>(); + /** + * Lazily calculated fingerprint of the writer schema; only valid once + * {@link #_writerFingerprintSet} is {@code true}. + */ + private long _writerFingerprint; + + // Written after `_writerFingerprint` and read before it, to make it visible + private volatile boolean _writerFingerprintSet; /** * Outcomes of resolving type ids (as used by {@link AvroStructureReader}s of @@ -182,12 +189,12 @@ public String getSchemaType() { */ public long getWriterFingerprint() { - Long fingerprint = _writerFingerprint.get(); - if (fingerprint == null) { - fingerprint = SchemaNormalization.parsingFingerprint64(_fingerprintSchema()); - _writerFingerprint.set(fingerprint); + // Racy but benign: concurrent calls would calculate the same value + if (!_writerFingerprintSet) { + _writerFingerprint = SchemaNormalization.parsingFingerprint64(_fingerprintSchema()); + _writerFingerprintSet = true; } - return fingerprint; + return _writerFingerprint; } Schema _fingerprintSchema() { @@ -365,7 +372,8 @@ public String toString() { @Override public int hashCode() { - return super.hashCode() ^ _readerSchema.hashCode(); + return super.hashCode() ^ _readerSchema.hashCode() + ^ _originalWriterSchema.hashCode(); } @Override From f95967edd15cfb89b7a64a2bffc254a4c1bfc5b6 Mon Sep 17 00:00:00 2001 From: Tatu Saloranta Date: Sun, 29 Nov 2026 17:33:48 -0800 Subject: [PATCH 3/5] Add `@since 3.4` to new members for #343 Co-Authored-By: Claude Opus 5.5 --- .../jackson/dataformat/avro/AvroSchema.java | 29 ++++++++++++++++++- .../dataformat/avro/deser/AvroParserImpl.java | 12 ++++++++ .../dataformat/avro/deser/RootReader.java | 9 ++++++ 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java index e735c60ca..4f493f701 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/AvroSchema.java @@ -44,10 +44,16 @@ public class AvroSchema implements FormatSchema /** * Lazily calculated fingerprint of the writer schema; only valid once * {@link #_writerFingerprintSet} is {@code true}. + * + * @since 3.4 */ private long _writerFingerprint; - // Written after `_writerFingerprint` and read before it, to make it visible + /** + * Written after {@link #_writerFingerprint} and read before it, to make it visible. + * + * @since 3.4 + */ private volatile boolean _writerFingerprintSet; /** @@ -197,6 +203,12 @@ public long getWriterFingerprint() return _writerFingerprint; } + /** + * Accessor for the writer schema whose fingerprint {@link #getWriterFingerprint()} + * returns. + * + * @since 3.4 + */ Schema _fingerprintSchema() { return _writerSchema; } @@ -336,8 +348,17 @@ private final static class Resolving extends AvroSchema { private final Schema _readerSchema; + /** + * Writer schema as given, before aliases of the reader schema were applied: + * needed for calculating its fingerprint. + * + * @since 3.4 + */ private final Schema _originalWriterSchema; + /** + * @since 3.4 + */ public Resolving(Schema writer, Schema reader, Schema originalWriter) { super(writer); @@ -345,10 +366,16 @@ public Resolving(Schema writer, Schema reader, Schema originalWriter) _originalWriterSchema = originalWriter; } + /** + * @since 3.4 + */ public static Resolving create(Schema writer, Schema reader, Schema originalWriter) { return new Resolving(writer, reader, originalWriter); } + /** + * @since 3.4 + */ @Override Schema _fingerprintSchema() { return _originalWriterSchema; diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java b/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java index 8687e2956..b787c364d 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/deser/AvroParserImpl.java @@ -29,6 +29,12 @@ public abstract class AvroParserImpl */ protected final static int LONGEST_NON_CHUNKED_BINARY_READ = 250_000; + /** + * Length of the Avro "Single Object Encoding" header: 2-byte marker followed by + * 8-byte schema fingerprint. + * + * @since 3.4 + */ private final static int SINGLE_OBJECT_HEADER_LENGTH = 10; /* @@ -527,6 +533,12 @@ public long getRemainingElements() */ } + /** + * Method called to read and verify the Avro "Single Object Encoding" header + * preceding a root-level value. + * + * @since 3.4 + */ final void _readSingleObjectHeader(long expectedFingerprint) throws IOException { decodeFixed(SINGLE_OBJECT_HEADER_LENGTH); diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java index 8a692f5bb..7c9b89506 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java @@ -13,6 +13,12 @@ public class RootReader extends AvroReadContext { private final AvroParserImpl _parser; private final AvroStructureReader _valueReader; + /** + * Fingerprint of the writer schema, if each root-level value is expected to + * have Avro "Single Object Encoding" header; {@code null} if not. + * + * @since 3.4 + */ private final Long _singleObjectFingerprint; public RootReader(AvroParserImpl parser, @@ -20,6 +26,9 @@ public RootReader(AvroParserImpl parser, this(parser, valueReader, null); } + /** + * @since 3.4 + */ RootReader(AvroParserImpl parser, AvroStructureReader valueReader, Long singleObjectFingerprint) { super(null, null); From 0d46dc9b6e068cb032764919f4dd52d6dab41dbd Mon Sep 17 00:00:00 2001 From: Tatu Saloranta Date: Sun, 29 Nov 2026 17:39:10 -0800 Subject: [PATCH 4/5] Make new `RootReader` constructor public, deprecate old one (#343) Co-Authored-By: Claude Opus 5.5 --- .../jackson/dataformat/avro/deser/RootReader.java | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java index 7c9b89506..ca3dda630 100644 --- a/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java +++ b/avro/src/main/java/tools/jackson/dataformat/avro/deser/RootReader.java @@ -13,6 +13,7 @@ public class RootReader extends AvroReadContext { private final AvroParserImpl _parser; private final AvroStructureReader _valueReader; + /** * Fingerprint of the writer schema, if each root-level value is expected to * have Avro "Single Object Encoding" header; {@code null} if not. @@ -21,15 +22,22 @@ public class RootReader extends AvroReadContext */ private final Long _singleObjectFingerprint; + /** + * @deprecated Since 3.4 use {@link #RootReader(AvroParserImpl, AvroStructureReader, Long)} + */ + @Deprecated // since 3.4 public RootReader(AvroParserImpl parser, AvroStructureReader valueReader) { this(parser, valueReader, null); } /** + * @param singleObjectFingerprint Fingerprint of the writer schema, if each root-level + * value is expected to have Avro "Single Object Encoding" header; {@code null} if not + * * @since 3.4 */ - RootReader(AvroParserImpl parser, + public RootReader(AvroParserImpl parser, AvroStructureReader valueReader, Long singleObjectFingerprint) { super(null, null); _type = TYPE_ROOT; From a3af12898b596f7417f9ef1f5c5770315984c833 Mon Sep 17 00:00:00 2001 From: Tatu Saloranta Date: Sun, 29 Nov 2026 17:51:50 -0800 Subject: [PATCH 5/5] Simplify #343 test; align release notes with issue title Co-Authored-By: Claude Opus 5.5 --- .../avro/SingleObjectEncoding343Test.java | 392 ++++++++---------- release-notes/CREDITS | 8 +- release-notes/VERSION | 4 +- 3 files changed, 171 insertions(+), 233 deletions(-) diff --git a/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java index 16c6f9b47..bb312c4c6 100644 --- a/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java +++ b/avro/src/test/java/tools/jackson/dataformat/avro/SingleObjectEncoding343Test.java @@ -4,6 +4,7 @@ import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.nio.ByteBuffer; +import java.nio.ByteOrder; import java.util.Arrays; import java.util.List; import java.util.Map; @@ -15,7 +16,6 @@ import org.apache.avro.generic.GenericRecord; import org.apache.avro.generic.GenericRecordBuilder; import org.apache.avro.io.BinaryEncoder; -import org.apache.avro.io.DatumWriter; import org.apache.avro.io.EncoderFactory; import org.apache.avro.message.BinaryMessageEncoder; import org.junit.jupiter.api.Test; @@ -37,184 +37,115 @@ // [dataformats-binary#343]: reading Avro "Single Object Encoding" public class SingleObjectEncoding343Test extends AvroTestBase { - private final static String SCHEMA_JSON = "{" - + "\"type\": \"record\"," - + "\"name\": \"SampleRecord\"," - + "\"fields\": [" - + " {\"name\": \"name\", \"type\": \"string\"}" - + "]}"; - - private final static String OTHER_SCHEMA_JSON = "{" - + "\"type\": \"record\"," - + "\"name\": \"OtherRecord\"," - + "\"fields\": [" - + " {\"name\": \"name\", \"type\": \"string\"}" - + "]}"; - - private final Schema APACHE_SCHEMA = new Schema.Parser().parse(SCHEMA_JSON); - - private final AvroSchema JACKSON_SCHEMA = new AvroSchema(APACHE_SCHEMA); - - private final AvroMapper[] MAPPERS = new AvroMapper[] { - newMapper(), - newApacheMapper(), - new AvroMapper(AvroFactory.builderWithApacheDecoder() - .disable(AvroReadFeature.AVRO_BUFFERING).build()) - }; + private final static Schema SCHEMA = schema( + "{'type':'record','name':'SampleRecord','fields':[{'name':'name','type':'string'}]}"); - @Test - public void testReadSingleObjectEncoding() throws Exception - { - // Encode using Apache Avro's Single Object Encoding (BinaryMessageEncoder), - // which is what SpecificRecord.toByteBuffer() uses in Apache Avro 1.8+. - byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); - assertEquals((byte) 0xC3, bytes[0], "First magic byte should be 0xC3"); - assertEquals((byte) 0x01, bytes[1], "Second magic byte should be 0x01"); + private final static String INVALID_HEADER = "Invalid Avro Single Object Encoding header"; - for (AvroMapper mapper : MAPPERS) { - JsonNode result = singleObjectReader(mapper).readTree(bytes); - assertNotNull(result); - assertEquals("apm", result.get("name").asString()); - } - } + private final AvroMapper[] MAPPERS = Arrays.stream(builders()) + .map(b -> new AvroMapper(b.build())) + .toArray(AvroMapper[]::new); @Test - public void testReadSequenceOfSingleObjectValues() throws Exception + public void testReadSingleObjectEncoding() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(encodeSingleObject(APACHE_SCHEMA, "a")); - out.write(encodeSingleObject(APACHE_SCHEMA, "bc")); - byte[] bytes = out.toByteArray(); + // Single Object Encoding is what `SpecificRecord.toByteBuffer()` uses (Avro 1.8+) + byte[] bytes = encodeSingleObject(SCHEMA, record("apm")); + assertEquals((byte) 0xC3, bytes[0]); + assertEquals((byte) 0x01, bytes[1]); for (AvroMapper mapper : MAPPERS) { - try (MappingIterator it = singleObjectReader(mapper) - .forType(JsonNode.class).readValues(bytes)) { - List values = it.readAll(); - assertEquals(2, values.size()); - assertEquals("a", values.get(0).get("name").asString()); - assertEquals("bc", values.get(1).get("name").asString()); - } - try (MappingIterator it = singleObjectReader(mapper) - .forType(JsonNode.class).readValues(new ThrottledInputStream(bytes, 3))) { - List values = it.readAll(); - assertEquals(2, values.size()); - assertEquals("a", values.get(0).get("name").asString()); - assertEquals("bc", values.get(1).get("name").asString()); - } + ObjectReader r = singleObjectReader(mapper, SCHEMA); + assertEquals("apm", r.readTree(bytes).get("name").asString()); + assertEquals("apm", r.readTree(new ByteArrayInputStream(bytes)).get("name").asString()); } } @Test - public void testReadSingleObjectEncodingFromStream() throws Exception + public void testReadSequenceOfSingleObjectValues() throws Exception { - byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); + byte[] bytes = concat(encodeSingleObject(SCHEMA, record("a")), + encodeSingleObject(SCHEMA, record("bc"))); for (AvroMapper mapper : MAPPERS) { - JsonNode result = singleObjectReader(mapper) - .readTree(new ByteArrayInputStream(bytes)); - assertEquals("apm", result.get("name").asString()); + ObjectReader r = singleObjectReader(mapper, SCHEMA).forType(JsonNode.class); + assertNames(r.readValues(bytes), "a", "bc"); + assertNames(r.readValues(new ThrottledInputStream(bytes, 3)), "a", "bc"); } } @Test public void testReadWithReaderSchema() throws Exception { - Schema readerSchema = new Schema.Parser().parse("{" - + "\"type\": \"record\"," - + "\"name\": \"SampleRecord\"," - + "\"fields\": [" - + " {\"name\": \"name\", \"type\": \"string\"}," - + " {\"name\": \"count\", \"type\": \"int\", \"default\": 7}" - + "]}"); - AvroSchema resolving = JACKSON_SCHEMA.withReaderSchema(new AvroSchema(readerSchema)); - byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); + Schema readerSchema = schema("{'type':'record','name':'SampleRecord','fields':[" + + "{'name':'name','type':'string'}," + + "{'name':'count','type':'int','default':7}]}"); + AvroSchema resolving = new AvroSchema(SCHEMA).withReaderSchema(new AvroSchema(readerSchema)); + byte[] bytes = encodeSingleObject(SCHEMA, record("apm")); for (AvroMapper mapper : MAPPERS) { - JsonNode result = mapper.reader(resolving) - .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) - .readTree(bytes); + JsonNode result = singleObjectReader(mapper, resolving).readTree(bytes); assertEquals("apm", result.get("name").asString()); assertEquals(7, result.get("count").asInt()); } } + // Aliases of reader schema are applied to writer schema, but must not change + // its fingerprint @Test public void testReadWithReaderSchemaAliases() throws Exception { - Schema writerSchema = new Schema.Parser().parse("{" - + "\"type\": \"record\"," - + "\"name\": \"OldRecord\"," - + "\"fields\": [" - + " {\"name\": \"oldName\", \"type\": \"string\"}" - + "]}"); - Schema readerSchema = new Schema.Parser().parse("{" - + "\"type\": \"record\"," - + "\"name\": \"NewRecord\", \"aliases\": [\"OldRecord\"]," - + "\"fields\": [" - + " {\"name\": \"newName\", \"type\": \"string\", \"aliases\": [\"oldName\"]}" - + "]}"); - Schema otherReaderSchema = new Schema.Parser().parse("{" - + "\"type\": \"record\"," - + "\"name\": \"NewRecord\", \"aliases\": [\"OldRecord\"]," - + "\"fields\": [" - + " {\"name\": \"newName\", \"type\": \"string\", \"aliases\": [\"oldName\"]}," - + " {\"name\": \"count\", \"type\": \"int\", \"default\": 7}" - + "]}"); + Schema writerSchema = schema("{'type':'record','name':'OldRecord','fields':[" + + "{'name':'oldName','type':'string'}]}"); + AvroSchema reader = new AvroSchema(schema( + "{'type':'record','name':'NewRecord','aliases':['OldRecord'],'fields':[" + + "{'name':'newName','type':'string','aliases':['oldName']}]}")); + AvroSchema otherReader = new AvroSchema(schema( + "{'type':'record','name':'NewRecord','aliases':['OldRecord'],'fields':[" + + "{'name':'newName','type':'string','aliases':['oldName']}," + + "{'name':'count','type':'int','default':7}]}")); GenericRecord record = new GenericData.Record(writerSchema); record.put("oldName", "apm"); - byte[] bytes = toByteArray(new BinaryMessageEncoder( - GenericData.get(), writerSchema).encode(record)); - - final AvroSchema reader = new AvroSchema(readerSchema); - final AvroSchema otherReader = new AvroSchema(otherReaderSchema); - final AvroSchema[] schemas = new AvroSchema[] { - new AvroSchema(writerSchema).withReaderSchema(reader), - new AvroSchema(writerSchema).withUnsafeReaderSchema(reader), - new AvroSchema(writerSchema).withReaderSchema(reader).withReaderSchema(otherReader), - new AvroSchema(writerSchema).withReaderSchema(reader).withUnsafeReaderSchema(otherReader) + byte[] bytes = encodeSingleObject(writerSchema, record); + + AvroSchema writer = new AvroSchema(writerSchema); + AvroSchema[] schemas = new AvroSchema[] { + writer.withReaderSchema(reader), + writer.withUnsafeReaderSchema(reader), + writer.withReaderSchema(reader).withReaderSchema(otherReader), + writer.withReaderSchema(reader).withUnsafeReaderSchema(otherReader) }; - final long fingerprint = new AvroSchema(writerSchema).getWriterFingerprint(); for (AvroSchema schema : schemas) { - assertEquals(fingerprint, schema.getWriterFingerprint()); + assertEquals(writer.getWriterFingerprint(), schema.getWriterFingerprint()); } - final AvroSchema renamed = new AvroSchema(new Schema.Parser().parse("{" - + "\"type\": \"record\"," - + "\"name\": \"NewRecord\"," - + "\"fields\": [" - + " {\"name\": \"newName\", \"type\": \"string\"}" - + "]}")).withReaderSchema(otherReader); - assertNotEquals(fingerprint, renamed.getWriterFingerprint()); - assertNotEquals(new AvroSchema(writerSchema).withReaderSchema(otherReader), renamed); + // Writer schema that equals the aliased one has a different fingerprint, + // and so the resolving schemas must not be equal either + AvroSchema renamed = new AvroSchema(schema("{'type':'record','name':'NewRecord','fields':[" + + "{'name':'newName','type':'string'}]}")).withReaderSchema(otherReader); + assertNotEquals(writer.getWriterFingerprint(), renamed.getWriterFingerprint()); + assertNotEquals(writer.withReaderSchema(otherReader), renamed); + for (AvroMapper mapper : MAPPERS) { for (AvroSchema schema : schemas) { - JsonNode result = mapper.reader(schema) - .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) - .readTree(bytes); - assertEquals("apm", result.get("newName").asString()); + assertEquals("apm", singleObjectReader(mapper, schema).readTree(bytes) + .get("newName").asString()); } - JsonNode result = mapper.reader(schemas[2]) - .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) - .readTree(bytes); - assertEquals(7, result.get("count").asInt()); + assertEquals(7, singleObjectReader(mapper, schemas[2]).readTree(bytes) + .get("count").asInt()); } } + // 0-field records consume no content, but their headers do @Test public void testReadEmptyRecords() throws Exception { - Schema emptySchema = new Schema.Parser().parse( - "{\"type\": \"record\", \"name\": \"Empty\", \"fields\": []}"); - BinaryMessageEncoder encoder = - new BinaryMessageEncoder<>(GenericData.get(), emptySchema); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(toByteArray(encoder.encode(new GenericData.Record(emptySchema)))); - out.write(toByteArray(encoder.encode(new GenericData.Record(emptySchema)))); - byte[] bytes = out.toByteArray(); + Schema emptySchema = schema("{'type':'record','name':'Empty','fields':[]}"); + byte[] value = encodeSingleObject(emptySchema, new GenericData.Record(emptySchema)); + byte[] bytes = concat(value, value); assertEquals(20, bytes.length); for (AvroMapper mapper : MAPPERS) { - try (MappingIterator it = mapper.reader(new AvroSchema(emptySchema)) - .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + try (MappingIterator it = singleObjectReader(mapper, emptySchema) .forType(JsonNode.class).readValues(bytes)) { assertEquals(0, it.nextValue().size()); assertEquals(0, it.nextValue().size()); @@ -226,11 +157,11 @@ public void testReadEmptyRecords() throws Exception @Test public void testFailForTruncatedHeader() throws Exception { - byte[] bytes = Arrays.copyOf(encodeSingleObject(APACHE_SCHEMA, "apm"), 6); + byte[] bytes = Arrays.copyOf(encodeSingleObject(SCHEMA, record("apm")), 6); for (AvroMapper mapper : MAPPERS) { JacksonException e = assertThrows(JacksonException.class, - () -> singleObjectReader(mapper).readTree(bytes)); + () -> singleObjectReader(mapper, SCHEMA).readTree(bytes)); // Apache decoder reports end-of-input as `EOFException`, wrapped if (!(e.getCause() instanceof EOFException)) { verifyException(e, "end-of-input"); @@ -241,42 +172,37 @@ public void testFailForTruncatedHeader() throws Exception @Test public void testFailForMissingHeader() throws Exception { - byte[] bytes = encodeBinary(APACHE_SCHEMA, "no header in this one"); - byte[] otherVersion = encodeSingleObject(APACHE_SCHEMA, "apm"); + byte[] otherVersion = encodeSingleObject(SCHEMA, record("apm")); otherVersion[1] = 0x02; - byte[] otherMarker = encodeSingleObject(APACHE_SCHEMA, "apm"); + byte[] otherMarker = encodeSingleObject(SCHEMA, record("apm")); otherMarker[0] = (byte) 0xC2; + byte[] noHeader = encodeBinary(record("no header in this one")); for (AvroMapper mapper : MAPPERS) { - StreamReadException e = assertThrows(StreamReadException.class, - () -> singleObjectReader(mapper).readTree(bytes)); - verifyException(e, "Invalid Avro Single Object Encoding header"); - - e = assertThrows(StreamReadException.class, - () -> singleObjectReader(mapper).readTree(otherVersion)); - verifyException(e, "Invalid Avro Single Object Encoding header"); - verifyException(e, "got 0xC3 0x02"); - - e = assertThrows(StreamReadException.class, - () -> singleObjectReader(mapper).readTree(otherMarker)); - verifyException(e, "Invalid Avro Single Object Encoding header"); - verifyException(e, "got 0xC2 0x01"); + ObjectReader r = singleObjectReader(mapper, SCHEMA); + verifyException(assertThrows(StreamReadException.class, () -> r.readTree(noHeader)), + INVALID_HEADER); + verifyException(assertThrows(StreamReadException.class, () -> r.readTree(otherVersion)), + INVALID_HEADER + ": expected marker bytes 0xC3 0x01, got 0xC3 0x02"); + verifyException(assertThrows(StreamReadException.class, () -> r.readTree(otherMarker)), + INVALID_HEADER + ": expected marker bytes 0xC3 0x01, got 0xC2 0x01"); } } @Test public void testFailForFingerprintMismatch() throws Exception { - Schema otherSchema = new Schema.Parser().parse(OTHER_SCHEMA_JSON); - byte[] bytes = encodeSingleObject(otherSchema, "apm"); + Schema otherSchema = schema( + "{'type':'record','name':'OtherRecord','fields':[{'name':'name','type':'string'}]}"); + byte[] bytes = encodeSingleObject(otherSchema, record("apm")); String fingerprints = String.format( "value has 0x%016X, writer schema used for reading has 0x%016X", SchemaNormalization.parsingFingerprint64(otherSchema), - SchemaNormalization.parsingFingerprint64(APACHE_SCHEMA)); + SchemaNormalization.parsingFingerprint64(SCHEMA)); for (AvroMapper mapper : MAPPERS) { StreamReadException e = assertThrows(StreamReadException.class, - () -> singleObjectReader(mapper).readTree(bytes)); + () -> singleObjectReader(mapper, SCHEMA).readTree(bytes)); verifyException(e, "schema fingerprint mismatch"); verifyException(e, fingerprints); } @@ -285,18 +211,15 @@ public void testFailForFingerprintMismatch() throws Exception @Test public void testFailForValueWithoutHeaderInSequence() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(encodeSingleObject(APACHE_SCHEMA, "a")); - out.write(encodeBinary(APACHE_SCHEMA, "no header in this one")); - byte[] bytes = out.toByteArray(); + byte[] bytes = concat(encodeSingleObject(SCHEMA, record("a")), + encodeBinary(record("no header in this one"))); for (AvroMapper mapper : MAPPERS) { - try (MappingIterator it = singleObjectReader(mapper) + try (MappingIterator it = singleObjectReader(mapper, SCHEMA) .forType(JsonNode.class).readValues(bytes)) { assertEquals("a", it.nextValue().get("name").asString()); - StreamReadException e = assertThrows(StreamReadException.class, - () -> it.nextValue()); - verifyException(e, "Invalid Avro Single Object Encoding header"); + verifyException(assertThrows(StreamReadException.class, it::nextValue), + INVALID_HEADER); } } } @@ -304,26 +227,19 @@ public void testFailForValueWithoutHeaderInSequence() throws Exception @Test public void testHeadersCountForMaxDocumentLength() throws Exception { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - for (int i = 0; i < 3; ++i) { - out.write(encodeSingleObject(APACHE_SCHEMA, "abc")); - } - byte[] bytes = out.toByteArray(); + byte[] value = encodeSingleObject(SCHEMA, record("abc")); + byte[] bytes = concat(value, value, value); assertEquals(42, bytes.length); for (int maxLength : new int[] { 41, 42 }) { StreamReadConstraints constraints = StreamReadConstraints.builder() .maxDocumentLength(maxLength).build(); - for (AvroFactoryBuilder b : new AvroFactoryBuilder[] { - AvroFactory.builderWithNativeDecoder(), - AvroFactory.builderWithApacheDecoder(), - AvroFactory.builderWithApacheDecoder().disable(AvroReadFeature.AVRO_BUFFERING) }) { - ObjectReader r = singleObjectReader(new AvroMapper( - b.streamReadConstraints(constraints).build())) - .forType(JsonNode.class); - try (MappingIterator it = r.readValues(new ByteArrayInputStream(bytes))) { + for (AvroFactoryBuilder b : builders()) { + AvroMapper mapper = new AvroMapper(b.streamReadConstraints(constraints).build()); + try (MappingIterator it = singleObjectReader(mapper, SCHEMA) + .forType(JsonNode.class).readValues(new ByteArrayInputStream(bytes))) { if (maxLength < bytes.length) { - assertThrows(StreamConstraintsException.class, () -> it.readAll()); + assertThrows(StreamConstraintsException.class, it::readAll); } else { assertEquals(3, it.readAll().size()); } @@ -332,10 +248,12 @@ public void testHeadersCountForMaxDocumentLength() throws Exception } } + // Fingerprint must be calculated the same way as by Apache Avro lib, for + // schema using all kinds of attributes that are not part of Parsing Canonical Form @Test public void testWriterFingerprintSameAsApache() throws Exception { - Schema schema = new Schema.Parser().parse(a2q("{" + Schema schema = schema("{" +"'type':'record','name':'Order','namespace':'com.example.orders'," +"'doc':'An order','aliases':['OldOrder'],'custom':'value'," +"'fields':[" @@ -352,19 +270,13 @@ public void testWriterFingerprintSameAsApache() throws Exception +" {'name':'next','type':['null','Order'],'default':null}," +" {'name':'line','type':{'type':'record','name':'Line'," +" 'fields':[{'name':'qty','type':'int','default':1}]},'default':{'qty':2}}" - +"]}")); - byte[] bytes = toByteArray(new BinaryMessageEncoder(GenericData.get(), schema) - .encode(new GenericRecordBuilder(schema).build())); - long fingerprint = 0L; - for (int i = 9; i >= 2; --i) { - fingerprint = (fingerprint << 8) | (bytes[i] & 0xFFL); - } + +"]}"); + byte[] bytes = encodeSingleObject(schema, new GenericRecordBuilder(schema).build()); + long fingerprint = ByteBuffer.wrap(bytes, 2, 8).order(ByteOrder.LITTLE_ENDIAN).getLong(); assertEquals(fingerprint, new AvroSchema(schema).getWriterFingerprint()); for (AvroMapper mapper : MAPPERS) { - JsonNode result = mapper.reader(new AvroSchema(schema)) - .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) - .readTree(bytes); + JsonNode result = singleObjectReader(mapper, schema).readTree(bytes); assertEquals("DONE", result.get("status").asString()); assertEquals(2, result.get("line").get("qty").asInt()); } @@ -386,17 +298,12 @@ public void testReadNonRecordRoots() throws Exception new GenericData.Fixed(null, new byte[] { 1, 2 }), "\"AQI=\"" } }; for (Object[] c : cases) { - final Schema schema = new Schema.Parser().parse(a2q((String) c[0])); - final byte[] value = toByteArray(new BinaryMessageEncoder(GenericData.get(), schema) - .encode(c[1])); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - out.write(value); - out.write(value); - final byte[] bytes = out.toByteArray(); + final Schema schema = schema((String) c[0]); + final byte[] value = encodeSingleObject(schema, c[1]); + final byte[] bytes = concat(value, value); for (AvroMapper mapper : MAPPERS) { - ObjectReader r = mapper.reader(new AvroSchema(schema)) - .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + ObjectReader r = singleObjectReader(mapper, schema) .without(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); for (boolean stream : new boolean[] { false, true }) { try (JsonParser p = stream @@ -414,72 +321,103 @@ public void testReadNonRecordRoots() throws Exception @Test public void testHeaderNotExposedAsBinaryValue() throws Exception { - byte[] bytes = encodeSingleObject(APACHE_SCHEMA, "apm"); + byte[] bytes = encodeSingleObject(SCHEMA, record("apm")); Schema stringSchema = Schema.create(Schema.Type.STRING); - byte[] base64 = toByteArray(new BinaryMessageEncoder(GenericData.get(), stringSchema) - .encode("AQI=")); + byte[] base64 = encodeSingleObject(stringSchema, "AQI="); for (AvroMapper mapper : MAPPERS) { - try (JsonParser p = singleObjectReader(mapper).createParser(bytes)) { + try (JsonParser p = singleObjectReader(mapper, SCHEMA).createParser(bytes)) { assertToken(JsonToken.START_OBJECT, p.nextToken()); assertNull(p.getEmbeddedObject()); } - byte[] value = mapper.readerFor(byte[].class) - .with(new AvroSchema(stringSchema)) - .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING) + byte[] value = singleObjectReader(mapper, stringSchema) + .forType(byte[].class) .readValue(base64); assertArrayEquals(new byte[] { 1, 2 }, value); } } - /** - * Contrast: regular Avro binary encoding (NOT Single Object Encoding) works fine. - */ + // Contrast: regular Avro binary encoding (NOT Single Object Encoding) works as before @Test public void testReadRegularBinaryEncoding() throws Exception { - byte[] bytes = encodeBinary(APACHE_SCHEMA, "apm"); - // First byte should be 0x06 (zigzag VarInt for length 3), not 0xC3 + byte[] bytes = encodeBinary(record("apm")); + // First byte is length of String (3 as zigzag VarInt), not 0xC3 assertEquals((byte) 0x06, bytes[0]); for (AvroMapper mapper : MAPPERS) { - JsonNode result = mapper.reader(JACKSON_SCHEMA).readTree(bytes); - assertNotNull(result); + JsonNode result = mapper.reader(new AvroSchema(SCHEMA)).readTree(bytes); assertEquals("apm", result.get("name").asString()); } } - private ObjectReader singleObjectReader(AvroMapper mapper) { - return mapper.reader(JACKSON_SCHEMA) + /* + /********************************************************************** + /* Helper methods + /********************************************************************** + */ + + private static AvroFactoryBuilder[] builders() { + return new AvroFactoryBuilder[] { + AvroFactory.builderWithNativeDecoder(), + AvroFactory.builderWithApacheDecoder(), + AvroFactory.builderWithApacheDecoder().disable(AvroReadFeature.AVRO_BUFFERING) + }; + } + + private static ObjectReader singleObjectReader(AvroMapper mapper, Schema schema) { + return singleObjectReader(mapper, new AvroSchema(schema)); + } + + private static ObjectReader singleObjectReader(AvroMapper mapper, AvroSchema schema) { + return mapper.reader(schema) .with(AvroReadFeature.READ_SINGLE_OBJECT_ENCODING); } - private static byte[] encodeSingleObject(Schema schema, String name) throws Exception + private static void assertNames(MappingIterator it, String... names) throws Exception { - BinaryMessageEncoder encoder = - new BinaryMessageEncoder<>(GenericData.get(), schema); - return toByteArray(encoder.encode(record(schema, name))); + try (it) { + List values = it.readAll(); + assertEquals(names.length, values.size()); + for (int i = 0; i < names.length; ++i) { + assertEquals(names[i], values.get(i).get("name").asString()); + } + } } - private static byte[] encodeBinary(Schema schema, String name) throws Exception - { - ByteArrayOutputStream out = new ByteArrayOutputStream(); - BinaryEncoder binaryEncoder = EncoderFactory.get().binaryEncoder(out, null); - DatumWriter writer = new GenericDatumWriter<>(schema); - writer.write(record(schema, name), binaryEncoder); - binaryEncoder.flush(); - return out.toByteArray(); + private static Schema schema(String json) { + return new Schema.Parser().parse(a2q(json)); } - private static GenericRecord record(Schema schema, String name) { - GenericRecord record = new GenericData.Record(schema); + private static GenericRecord record(String name) { + GenericRecord record = new GenericData.Record(SCHEMA); record.put("name", name); return record; } - private static byte[] toByteArray(ByteBuffer buf) { + private static byte[] encodeSingleObject(Schema schema, Object datum) throws Exception + { + ByteBuffer buf = new BinaryMessageEncoder(GenericData.get(), schema).encode(datum); byte[] bytes = new byte[buf.remaining()]; buf.get(bytes); return bytes; } + + private static byte[] encodeBinary(GenericRecord record) throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null); + new GenericDatumWriter(record.getSchema()).write(record, encoder); + encoder.flush(); + return out.toByteArray(); + } + + private static byte[] concat(byte[]... parts) throws Exception + { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + for (byte[] part : parts) { + out.write(part); + } + return out.toByteArray(); + } } diff --git a/release-notes/CREDITS b/release-notes/CREDITS index c3441d430..a0b8fe4b8 100644 --- a/release-notes/CREDITS +++ b/release-notes/CREDITS @@ -139,12 +139,12 @@ Dhanraj E (@Dhanu-dynamic) @birTiwana -* Reported #343: (avro) Add `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` to decode Avro - "Single Object Encoding" +* Reported #343: (avro) Support Avro "single-object encoding" decoding with + `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` (3.4.0) Vineet Singh (@Vineet829) -* Contributed #343: (avro) Add `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` to decode Avro - "Single Object Encoding" +* Contributed #343: (avro) Support Avro "single-object encoding" decoding with + `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` (3.4.0) diff --git a/release-notes/VERSION b/release-notes/VERSION index dd883c881..b39cd945c 100644 --- a/release-notes/VERSION +++ b/release-notes/VERSION @@ -16,8 +16,8 @@ implementations) 3.4.0 (not yet released) -#343: (avro) Add `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` to decode Avro - "Single Object Encoding" (as written by `BinaryMessageEncoder`) +#343: (avro) Support Avro "single-object encoding" decoding with + `AvroReadFeature.READ_SINGLE_OBJECT_ENCODING` (reported by @birTiwana) (contributed by @Vineet829)