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

com.dottydingo.hyperion.service.marshall.EndpointMarshaller Maven / Gradle / Ivy

The newest version!
package com.dottydingo.hyperion.service.marshall;

import com.dottydingo.hyperion.exception.BadRequestException;
import com.dottydingo.hyperion.exception.InternalException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.InputStream;
import java.io.OutputStream;

/**
 */
public class EndpointMarshaller
{
    private ObjectMapper objectMapper;

    public EndpointMarshaller()
    {
        try
        {
            objectMapper = new ObjectMapperBuilder().getObject();
        }
        catch (Exception ignore){}
    }

    public void setObjectMapper(ObjectMapper objectMapper)
    {
        this.objectMapper = objectMapper;
    }

    public  T unmarshall(InputStream inputStream, Class type)
    {
        try
        {
            return objectMapper.readValue(inputStream,type);
        }
        catch (Exception e)
        {
            throw new BadRequestException(String.format("Error unmarshalling request: %s",e.getMessage()),e);
        }
    }

    public  RequestContext unmarshallWithContext(InputStream inputStream, Class type)
    {
        try
        {
            JsonNode jsonNode = objectMapper.readTree(inputStream);
            T value = objectMapper.convertValue(jsonNode,type);

            return new RequestContext(value,jsonNode.fieldNames());
        }
        catch (Exception e)
        {
            throw new BadRequestException(String.format("Error unmarshalling request: %s",e.getMessage()),e);
        }
    }


    public  void marshall(OutputStream outputStream, T value)
    {
        try
        {
            objectMapper.writeValue(outputStream,value);
        }
        catch(Exception e)
        {
            throw new InternalException("Error marhsalling response.",e);
        }

    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy