From ec2378b278c463646d9ad9c4fdd9e1057018174c Mon Sep 17 00:00:00 2001 From: belugabehr <12578579+belugabehr@users.noreply.github.com> Date: Sun, 6 Oct 2024 20:44:04 -0400 Subject: [PATCH] AVRO-4073: Create Convenience toBytes Method for Datum Writer (#3197) --- .../java/org/apache/avro/io/DatumWriter.java | 16 ++++++++++++++++ .../apache/avro/specific/TestSpecificData.java | 14 ++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/lang/java/avro/src/main/java/org/apache/avro/io/DatumWriter.java b/lang/java/avro/src/main/java/org/apache/avro/io/DatumWriter.java index f1e57626912..050c25b467f 100644 --- a/lang/java/avro/src/main/java/org/apache/avro/io/DatumWriter.java +++ b/lang/java/avro/src/main/java/org/apache/avro/io/DatumWriter.java @@ -17,6 +17,7 @@ */ package org.apache.avro.io; +import java.io.ByteArrayOutputStream; import java.io.IOException; import org.apache.avro.Schema; @@ -36,4 +37,19 @@ public interface DatumWriter { * the schema from the datum to the output. */ void write(D datum, Encoder out) throws IOException; + + /** + * Convenience method to Write a datum to a byte array. Traverse the schema, + * depth first, writing each leaf value in the schema from the datum to the byte + * array. + * + * @param datum The datum to serialize + * @return The serialized datum stored in an array of bytes + */ + default byte[] toByteArray(D datum) throws IOException { + try (ByteArrayOutputStream out = new ByteArrayOutputStream(128)) { + write(datum, EncoderFactory.get().directBinaryEncoder(out, null)); + return out.toByteArray(); + } + } } diff --git a/lang/java/avro/src/test/java/org/apache/avro/specific/TestSpecificData.java b/lang/java/avro/src/test/java/org/apache/avro/specific/TestSpecificData.java index 5c8cad85331..1d9d58b0518 100644 --- a/lang/java/avro/src/test/java/org/apache/avro/specific/TestSpecificData.java +++ b/lang/java/avro/src/test/java/org/apache/avro/specific/TestSpecificData.java @@ -179,6 +179,20 @@ void nonStringable() throws Exception { } } + @Test + void testToByteArray() throws Exception { + final Schema string = Schema.create(Type.STRING); + final DatumWriter writer = new SpecificDatumWriter<>(string); + + try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) { + final Encoder encoder = EncoderFactory.get().directBinaryEncoder(baos, null); + writer.write("test", encoder); + + final byte[] bytes = writer.toByteArray("test"); + assertArrayEquals(baos.toByteArray(), bytes); + } + } + @Test void classNameContainingReservedWords() { final Schema schema = Schema.createRecord("AnyName", null, "db.public.table", false);