001/*
002 * (C) Copyright 2018 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     bdelbosc
018 */
019package org.nuxeo.lib.stream.codec;
020
021import java.io.IOException;
022
023import org.apache.avro.Schema;
024import org.apache.avro.message.BadHeaderException;
025import org.apache.avro.message.BinaryMessageDecoder;
026import org.apache.avro.message.BinaryMessageEncoder;
027import org.apache.avro.message.SchemaStore;
028import org.apache.avro.reflect.ReflectData;
029
030/**
031 * Avro Single object encoding: magic 2 bytes + schema fingerprint 8 bytes + avro binary. See
032 * https://avro.apache.org/docs/current/spec.html#single_object_encoding When using a SchemaStore the writer and reader
033 * schemas can evolve.
034 *
035 * @since 10.2
036 */
037public class AvroMessageCodec<T> implements Codec<T> {
038    public static final String NAME = "avro";
039
040    protected final Class<T> messageClass;
041
042    protected final Schema schema;
043
044    protected final BinaryMessageEncoder<T> encoder;
045
046    protected final BinaryMessageDecoder<T> decoder;
047
048    public AvroMessageCodec(Class<T> messageClass, SchemaStore store) {
049        this.messageClass = messageClass;
050        schema = ReflectData.get().getSchema(messageClass);
051        encoder = new BinaryMessageEncoder<>(ReflectData.get(), schema);
052        decoder = new BinaryMessageDecoder<>(ReflectData.get(), schema, store);
053    }
054
055    public AvroMessageCodec(Class<T> messageClass) {
056        this(messageClass, null);
057    }
058
059    @Override
060    public String getName() {
061        return NAME;
062    }
063
064    @Override
065    public byte[] encode(T object) {
066        try {
067            return encoder.encode(object).array();
068        } catch (IOException e) {
069            throw new IllegalArgumentException(e);
070        }
071    }
072
073    @Override
074    public T decode(byte[] data) {
075        try {
076            return decoder.decode(data, null);
077        } catch (IOException | BadHeaderException e) {
078            throw new IllegalArgumentException(e);
079        }
080    }
081}