/** * @param input avro object * @return textual representation of the schema of the given {@code input} avro object */ @Override protected String getSchemaText(Object input) { Schema schema = AvroUtils.computeSchema(input); return schema.toString(); }
public static Schema computeSchema(Object input) { Schema schema = null; if (input instanceof GenericContainer) { schema = ((GenericContainer) input).getSchema(); } else { schema = AvroUtils.getSchemaForPrimitives(input); } return schema; }
@Override public void handlePayloadSerialization(OutputStream outputStream, Object input) { try { Schema schema = AvroUtils.computeSchema(input); Schema.Type schemaType = schema.getType(); if (Schema.Type.BYTES.equals(schemaType)) { // incase of byte arrays, no need to go through avro as there is not much to optimize and avro is expecting // the payload to be ByteBuffer instead of a byte array outputStream.write((byte[]) input); } else if (Schema.Type.STRING.equals(schemaType)) { // get UTF-8 bytes and directly send those over instead of using avro. outputStream.write(input.toString().getBytes("UTF-8")); } else { BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(outputStream, null); DatumWriter<Object> writer; boolean isSpecificRecord = input instanceof SpecificRecord; if (isSpecificRecord) { writer = new SpecificDatumWriter<>(schema); } else { writer = new GenericDatumWriter<>(schema); } writer.write(input, encoder); encoder.flush(); } } catch (IOException e) { throw new AvroRetryableException(e); } catch (RuntimeException e) { throw new AvroException(e); } }
@Override public void handlePayloadSerialization(OutputStream outputStream, Object input) { try { Schema schema = AvroUtils.computeSchema(input); if (input instanceof byte[]) { outputStream.write((byte[]) input); } else { BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(outputStream, null); DatumWriter<Object> writer; if (input instanceof SpecificRecord) { writer = new SpecificDatumWriter<>(schema); } else { writer = new GenericDatumWriter<>(schema); } writer.write(input, encoder); encoder.flush(); } } catch (IOException e) { throw new AvroRetryableException("Error serializing Avro message", e); } catch (RuntimeException e) { // avro serialization can throw AvroRuntimeException, NullPointerException, // ClassCastException, etc throw new AvroException("Error serializing Avro message", e); } }