Created
April 17, 2018 15:04
-
-
Save ept/df43936a2d15e42a6c35698fca124f63 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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