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