AvroEncoderUtil.java org::apache::iceberg::avro::AvroEncoderUtil org::apache::iceberg::avro /* *LicensedtotheApacheSoftwareFoundation(ASF)underone *ormorecontributorlicenseagreements.SeetheNOTICEfile *distributedwiththisworkforadditionalinformation *regardingcopyrightownership.TheASFlicensesthisfile *toyouundertheApacheLicense,Version2.0(the *"License");youmaynotusethisfileexceptincompliance *withtheLicense.YoumayobtainacopyoftheLicenseat * *http://www.apache.org/licenses/LICENSE-2.0 * *Unlessrequiredbyapplicablelaworagreedtoinwriting, *softwaredistributedundertheLicenseisdistributedonan *"ASIS"BASIS,WITHOUTWARRANTIESORCONDITIONSOFANY *KIND,eitherexpressorimplied.SeetheLicenseforthe *specificlanguagegoverningpermissionsandlimitations *undertheLicense. */ packageorg.apache.iceberg.avro; importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.DataInputStream; importjava.io.DataOutputStream; importjava.io.IOException; importorg.apache.avro.LogicalTypes; importorg.apache.avro.Schema; importorg.apache.avro.io.BinaryDecoder; importorg.apache.avro.io.BinaryEncoder; importorg.apache.avro.io.DatumReader; importorg.apache.avro.io.DatumWriter; importorg.apache.avro.io.DecoderFactory; importorg.apache.avro.io.EncoderFactory; importorg.apache.iceberg.relocated.com.google.common.base.Preconditions; publicclassAvroEncoderUtil{ privateAvroEncoderUtil(){} static{ LogicalTypes.register(LogicalMap.NAME,schema->LogicalMap.get()); } privatestaticfinalbyte[]MAGIC_BYTES=newbyte[]{(byte)0xC2,(byte)0x01}; publicstatic<T>byte[]encode(Tdatum,SchemaavroSchema)throwsIOException{ try(ByteArrayOutputStreamout=newByteArrayOutputStream()){ DataOutputStreamdataOut=newDataOutputStream(out); //Writethemagicbytes dataOut.write(MAGIC_BYTES); //Writeavroschema dataOut.writeUTF(avroSchema.toString()); //Encodethedatumwithavroschema. BinaryEncoderencoder=EncoderFactory.get().binaryEncoder(out,null); DatumWriter<T>writer=newGenericAvroWriter<>(avroSchema); writer.write(datum,encoder); encoder.flush(); returnout.toByteArray(); } } publicstatic<T>Tdecode(byte[]data)throwsIOException{ try(ByteArrayInputStreamin=newByteArrayInputStream(data,0,data.length)){ DataInputStreamdataInput=newDataInputStream(in); //Readthemagicbytes byteheader0=dataInput.readByte(); byteheader1=dataInput.readByte(); Preconditions.checkState( header0==MAGIC_BYTES[0]&&header1==MAGIC_BYTES[1], "Unrecognizedheaderbytes:0x%02X0x%02X", header0, header1); //Readavroschema SchemaavroSchema=newSchema.Parser().parse(dataInput.readUTF()); //Decodethedatumwiththeparsedavroschema. BinaryDecoderbinaryDecoder=DecoderFactory.get().binaryDecoder(in,null); DatumReader<T>reader=newGenericAvroReader<>(avroSchema); reader.setSchema(avroSchema); returnreader.read(null,binaryDecoder); } } }