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

com.vladkrava.converter.http.AvroJsonHttpMessageConverter Maven / Gradle / Ivy

Go to download

Enables conversion of Apache Avro object into popular data formats: JSON, XML, etc

The newest version!
package com.vladkrava.converter.http;

import java.io.IOException;

import org.apache.avro.specific.SpecificRecordBase;
import org.apache.commons.compress.utils.IOUtils;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;

import com.vladkrava.converter.serialization.AvroDeserializer;
import com.vladkrava.converter.serialization.AvroSerializer;
import com.vladkrava.converter.serialization.DataSerializationException;

/**
 * This converter supports application/avro-json format with {@code DEFAULT_CHARSET} character set.
 *
 * @author Vlad Krava - [email protected]
 * @see AbstractAvroHttpMessageConverter
 * @see SpecificRecordBase
 * @since 1.0.0-SNAPSHOT
 */
public class AvroJsonHttpMessageConverter extends AbstractAvroHttpMessageConverter {

    private final AvroSerializer avroSerializer;
    private final AvroDeserializer avroDeserializer;

    public AvroJsonHttpMessageConverter() {
        super(AVRO_JSON_MEDIA_TYPE);

        this.avroSerializer = new AvroSerializer<>();
        this.avroDeserializer = new AvroDeserializer<>();
    }

    /**
     * Reading accepted message and providing deserialization
     *
     * @param aClass       - target Avro object type
     * @param inputMessage - accepted message
     * @return {@code T} - converted Avro object
     * @throws IOException - on read/write issues
     */
    @SuppressWarnings("unchecked")
    @Override
    protected T readInternal(final Class aClass, HttpInputMessage inputMessage) throws IOException {
        T result = null;
        final byte[] data = IOUtils.toByteArray(inputMessage.getBody());
        if (data != null && data.length > 0) {
            try {
                result = (T) avroDeserializer.deserialize(data, aClass);
            } catch (DataSerializationException e) {
                logger.error(e.getMessage(), e);
            }
        }
        return result;
    }

    /**
     * Serializing and writing Avro object into outgoing message
     *
     * @param t                 - Avro object
     * @param httpOutputMessage - outgoing message
     * @throws IOException - on read/write issues
     */
    @Override
    protected void writeInternal(final T t, final HttpOutputMessage httpOutputMessage) throws IOException {
        try {
            final byte[] data = avroSerializer.serialize(t);
            httpOutputMessage.getBody().write(data);
        } catch (DataSerializationException e) {
            logger.error(e.getMessage(), e);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy