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.RawMessageDecoder;
025import org.apache.avro.message.RawMessageEncoder;
026import org.apache.avro.reflect.ReflectData;
027
028/**
029 * Avro Binary format, there is no header, the schema must be the same for encoder and decoder.
030 *
031 * @since 10.2
032 */
033public class AvroBinaryCodec<T> implements Codec<T> {
034    public static final String NAME = "avroBinary";
035
036    protected final Class<T> messageClass;
037
038    protected final Schema schema;
039
040    protected final RawMessageEncoder<T> encoder;
041
042    protected final RawMessageDecoder<T> decoder;
043
044    public AvroBinaryCodec(Class<T> messageClass) {
045        this.messageClass = messageClass;
046        schema = ReflectData.get().getSchema(messageClass);
047        encoder = new RawMessageEncoder<>(ReflectData.get(), schema);
048        decoder = new RawMessageDecoder<>(ReflectData.get(), schema);
049    }
050
051    @Override
052    public String getName() {
053        return NAME;
054    }
055
056    @Override
057    public byte[] encode(T object) {
058        try {
059            return encoder.encode(object).array();
060        } catch (IOException e) {
061            throw new IllegalArgumentException(e);
062        }
063    }
064
065    @Override
066    public T decode(byte[] data) {
067        try {
068            return decoder.decode(data, null);
069        } catch (IOException | IndexOutOfBoundsException e) {
070            throw new IllegalArgumentException(e);
071        }
072    }
073}