Skip to content

Instantly share code, notes, and snippets.

@ept ept/AvroTest.java
Created Apr 17, 2018

Embed
What would you like to do?
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecordBuilder;
import org.apache.avro.io.BinaryDecoder;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DecoderFactory;
import org.apache.avro.io.EncoderFactory;
public class AvroTest {
public static Schema WRITER_SCHEMA = new Schema.Parser().parse("{" +
"\"namespace\": \"com.martinkl.avro\", " +
"\"type\": \"record\", " +
"\"name\": \"Test\", " +
"\"fields\": [" +
"{\"name\": \"enumTest\", \"type\": " +
"{\"type\": \"enum\", \"name\": \"EnumTest\", \"symbols\": [\"ONE\", \"TWO\", \"THREE\", \"FOUR\"]}}" +
"]}");
public static Schema READER_SCHEMA = new Schema.Parser().parse("{" +
"\"namespace\": \"com.martinkl.avro\", " +
"\"type\": \"record\", " +
"\"name\": \"Test\", " +
"\"fields\": [" +
"{\"name\": \"enumTest\", \"type\": " +
"{\"type\": \"enum\", \"name\": \"EnumTest\", \"symbols\": [\"ONE\", \"TWO\", \"THREE\"]}}, " +
"{\"name\": \"newField\", \"type\": [\"null\", \"string\"], \"default\": null}" +
"]}");
public static int main(String[] args) throws IOException {
Schema enumType = READER_SCHEMA.getField("enumTest").schema();
GenericData.Record record = new GenericRecordBuilder(WRITER_SCHEMA)
.set("enumTest", new GenericData.EnumSymbol(enumType, "ONE"))
.build();
System.out.println("Before encoding: " + record);
// Encode the record with the writer schema
ByteArrayOutputStream output = new ByteArrayOutputStream();
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(output, null);
new GenericDatumWriter<>(WRITER_SCHEMA).write(record, encoder);
encoder.flush();
// Decode the record with the reader schema
BinaryDecoder decoder = DecoderFactory.get().binaryDecoder(output.toByteArray(), null);
Object obj = new GenericDatumReader<>(WRITER_SCHEMA, READER_SCHEMA).read(null, decoder);
System.out.println("After decoding: " + obj);
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.