Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion avro/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,20 @@ byte[] avroData = mapper.writer(schema)
.writeValueAsBytes(empl);
```

and that's about it, for now.
### Writing Single Object Encoding

Since 3.4, enable `AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING` to write messages for
Apache Avro's `BinaryMessageDecoder` or Jackson's `READ_SINGLE_OBJECT_ENCODING` reader.

```java
byte[] message = mapper.writer(schema)
.with(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING)
.writeValueAsBytes(empl);
```

Each root value gets its own header, including each value written by a `SequenceWriter`.
The default writer produces raw Avro data. Use `AVRO_FILE_OUTPUT` separately for Avro
object container files.

## Avro Logical Types

Expand Down
45 changes: 32 additions & 13 deletions avro/src/main/java/tools/jackson/dataformat/avro/AvroGenerator.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

import tools.jackson.core.*;
import tools.jackson.core.base.GeneratorBase;
import tools.jackson.core.io.GuardedOutputStream;
import tools.jackson.core.io.IOContext;
import tools.jackson.core.util.JacksonFeatureSet;
import tools.jackson.dataformat.avro.apacheimpl.ApacheCodecRecycler;
Expand Down Expand Up @@ -45,6 +46,8 @@ public class AvroGenerator extends GeneratorBase

protected final AvroSchema _rootSchema;

private boolean _singleObjectEncodingRequested;

/*
/**********************************************************************
/* Output state
Expand Down Expand Up @@ -89,14 +92,17 @@ public AvroGenerator(ObjectWriteContext writeCtxt, IOContext ioCtxt,
{
super(writeCtxt, ioCtxt, streamWriteFeatures);
_formatWriteFeatures = avroFeatures;
_singleObjectEncodingRequested = isEnabled(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING);
_output = output;
_streamWriteContext = AvroWriteContext.nullContext();
_apacheCodecRecycler = apacheCodecRecycler;
final boolean buffering = isEnabled(AvroWriteFeature.AVRO_BUFFERING);
OutputStream encoderOutput = isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)
? output : new GuardedOutputStream(output);
BinaryEncoder encoderToReuse = apacheCodecRecycler.acquireEncoder();
_encoder = buffering
? ENCODER_FACTORY.binaryEncoder(output, encoderToReuse)
: ENCODER_FACTORY.directBinaryEncoder(output, encoderToReuse);
? ENCODER_FACTORY.binaryEncoder(encoderOutput, encoderToReuse)
: ENCODER_FACTORY.directBinaryEncoder(encoderOutput, encoderToReuse);
_rootSchema = Objects.requireNonNull(schema, "Can not pass `null` 'schema'");
// start with temporary root...
_streamWriteContext = _rootContext = AvroWriteContext.createRootContext(this,
Expand Down Expand Up @@ -182,6 +188,9 @@ public JacksonFeatureSet<StreamWriteCapability> streamWriteCapabilities() {

public AvroGenerator enable(AvroWriteFeature f) {
_formatWriteFeatures |= f.getMask();
if (f == AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING) {
_singleObjectEncodingRequested = true;
}
return this;
}

Expand Down Expand Up @@ -256,17 +265,32 @@ public JsonGenerator writePropertyId(long id) throws JacksonException {

@Override
public final void flush() {
if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) {
try {
try {
if (_singleObjectEncodingRequested && _encoder != null) {
_encoder.flush();
} else if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) {
_output.flush();
} catch (IOException e) {
throw _wrapIOFailure(e);
}
} catch (IOException e) {
throw _wrapIOFailure(e);
}
}

@Override
protected void _closeInput() throws IOException
{
boolean closeTarget = _ioContext.isResourceManaged()
|| isEnabled(StreamWriteFeature.AUTO_CLOSE_TARGET);
try (OutputStream ownedTarget = closeTarget ? _output : null) {
_finishContent();
if (ownedTarget == null && _output != null
&& isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) {
_output.flush();
}
}
}

private void _finishContent() throws IOException
{
if (isEnabled(StreamWriteFeature.AUTO_CLOSE_CONTENT)) {
AvroWriteContext ctxt;
Expand Down Expand Up @@ -296,13 +320,8 @@ protected void _closeInput() throws IOException
e);
}
}
if (_output != null) {
if (_ioContext.isResourceManaged() || isEnabled(StreamWriteFeature.AUTO_CLOSE_TARGET)) {
_output.close();
} else if (isEnabled(StreamWriteFeature.FLUSH_PASSED_TO_STREAM)) {
// If we can't close it, we should at least flush
_output.flush();
}
if (_encoder.bytesBuffered() > 0) {
_encoder.flush();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,18 @@ public enum AvroWriteFeature
* @since 3.0
*
*/
ADD_NULL_AS_DEFAULT_VALUE_IN_SCHEMA(false)
ADD_NULL_AS_DEFAULT_VALUE_IN_SCHEMA(false),

/**
* Write each root value in Avro Single Object Encoding, with the two-byte marker
* and the little-endian CRC-64-AVRO fingerprint of the writer schema. This allows
* Apache Avro's {@code BinaryMessageDecoder} to read the value.
*<p>
* Disabled by default. Writing a value with {@link #AVRO_FILE_OUTPUT} also enabled fails.
*
* @since 3.4
*/
WRITE_SINGLE_OBJECT_ENCODING(false)
;

private final boolean _defaultState;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import org.apache.avro.Schema;
import org.apache.avro.file.DataFileWriter;
Expand All @@ -10,6 +12,7 @@
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DatumWriter;

import tools.jackson.core.exc.StreamWriteException;
import tools.jackson.dataformat.avro.AvroGenerator;
import tools.jackson.dataformat.avro.AvroWriteFeature;

Expand All @@ -30,6 +33,8 @@ class RootContext
*/
private NonBSGenericDatumWriter<Object> _writer;

private byte[] _singleObjectHeader;

public RootContext(AvroGenerator generator, Schema schema, BinaryEncoder encoder) {
super(TYPE_ROOT, null, generator, schema, null);
_encoder = encoder;
Expand Down Expand Up @@ -84,22 +89,35 @@ public final AvroWriteContext createChildObjectContext(Object currValue) {

@Override
public void writeValue(Object value) throws IOException {
// 19-Jan-2017, tatu: Implemented to allow/support root-level scalars, esp.
// for Avro streams
_writer().write(value, _encoder);
if (_generator.isEnabled(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING)) {
_writeSingleObject(value);
} else {
_writer().write(value, _encoder);
}
}

@Override
public void writeString(String value) throws IOException {
// 19-Jan-2017, tatu: Implemented to allow/support root-level scalars, esp.
// for Avro streams
_writer().write(value, _encoder);
writeValue(value);
}

@Override
public void writeNull() throws IOException {
// 19-Jan-2017, tatu: ... is this even legal?
_writer().write(null, _encoder);
writeValue(null);
}

private void _writeSingleObject(Object value) throws IOException {
if (_generator.isEnabled(AvroWriteFeature.AVRO_FILE_OUTPUT)) {
throw new StreamWriteException(_generator,
"WRITE_SINGLE_OBJECT_ENCODING cannot be combined with AVRO_FILE_OUTPUT");
}
if (_singleObjectHeader == null) {
_singleObjectHeader = ByteBuffer.allocate(10).order(ByteOrder.LITTLE_ENDIAN)
.put((byte) 0xC3).put((byte) 0x01)
.putLong(_generator.getSchema().getWriterFingerprint()).array();
}
_encoder.writeFixed(_singleObjectHeader);
_writer().write(value, _encoder);
}

@SuppressWarnings("resource")
Expand All @@ -108,9 +126,16 @@ public void complete() throws IOException {
final Object rootValue = _rootValue;
_rootValue = null;

// 21-Feb-2017, tatu: As per [dataformats-binary#15], need to ensure schema gets
// written, if using "File" format (not raw "rpc" one)
if (_generator.isEnabled(AvroWriteFeature.WRITE_SINGLE_OBJECT_ENCODING)) {
if (rootValue != null) {
_writeSingleObject(rootValue);
}
return;
}
if (_generator.isEnabled(AvroWriteFeature.AVRO_FILE_OUTPUT)) {
if (_encoder.bytesBuffered() > 0) {
_encoder.flush();
}
OutputStream outputStream = (OutputStream) _generator.streamWriteOutputTarget();
DatumWriter<Object> datumWriter = new NonBSGenericDatumWriter<>(_schema);
DataFileWriter<Object> dataFileWriter = new DataFileWriter<>(datumWriter);
Expand All @@ -120,8 +145,6 @@ public void complete() throws IOException {
dataFileWriter.close();
return;
}
// 19-Jan-2017, tatu: Gets also called for root-level scalar, in which
// case nothing (more) to output.
if (rootValue != null) {
_writer().write(rootValue, _encoder);
}
Expand Down
Loading