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