All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adgear.anoa.read.AvroFixedReader Maven / Gradle / Ivy

Go to download

Core classes for Anoa library, which aims to be a safe, convenient and fast record de/serialization wrapper for the Avro, Thrift and Jackson libraries, using the functional idioms of Java 8. The anoa-core module tries to keep upstream dependencies to a minimum.

There is a newer version: 3.1.2
Show newest version
package com.adgear.anoa.read;

import com.adgear.anoa.AnoaJacksonTypeException;
import com.fasterxml.jackson.core.JsonParser;

import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.specific.SpecificFixed;

import java.io.IOException;
import java.lang.reflect.Constructor;

abstract class AvroFixedReader extends AbstractReader {

  abstract protected F newInstance(byte[] bytes) throws Exception;

  static private ByteArrayReader byteArrayReader = new ByteArrayReader();

  @Override
  protected F read(JsonParser jacksonParser) throws IOException {
    final byte[] array = byteArrayReader.read(jacksonParser);
    if (array == null) {
      return null;
    }
    try {
      return newInstance(array);
    } catch (Exception e) {
      return null;
    }
  }

  @Override
  protected F readStrict(JsonParser jacksonParser) throws AnoaJacksonTypeException, IOException {
    final byte[] array = byteArrayReader.readStrict(jacksonParser);
    if (array == null) {
      return null;
    }
    try {
      return newInstance(array);
    } catch (Exception e) {
      return null;
    }
  }

  static class AvroSpecificFixedReader extends AvroFixedReader {

    final Constructor constructor;

    AvroSpecificFixedReader(Class fixedClass) {
      try {
        this.constructor = fixedClass.getDeclaredConstructor();
      } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
      }
    }

    @Override
    protected F newInstance(byte[] bytes) throws Exception {
      F instance = constructor.newInstance();
      instance.bytes(bytes);
      return instance;
    }
  }

  static class AvroGenericFixedReader extends AvroFixedReader {

    final Schema schema;

    AvroGenericFixedReader(Schema schema) {
      this.schema = schema;
    }

    @Override
    protected GenericData.Fixed newInstance(byte[] bytes) throws Exception {
      return new GenericData.Fixed(schema, bytes);
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy