Wednesday, February 4, 2015

Rest Template handle gzip format

Create new converter for Gzip format:

public class GzipMarshallingHttpMessageConverter extends
        AbstractHttpMessageConverter<DLSSeries> {

    public GzipMarshallingHttpMessageConverter() {
        super(new MediaType("application", "json"));
    }
   
    @Override
    protected boolean supports(Class<?> clazz) {
        return true;
    }

    @Override
    protected DLSSeries readInternal(Class<? extends DLSSeries> clazz,
            HttpInputMessage inputMessage) throws IOException {
        boolean gzip = false;
        HttpHeaders headers = inputMessage.getHeaders();
        List<String> contentEncoding = headers.get("Content-Encoding");

        if (headers != null && contentEncoding != null) {
            for (String contentEncodingStr : contentEncoding) {
                if (contentEncodingStr != null
                        && "gzip".equalsIgnoreCase(contentEncodingStr.trim())) {
                    gzip = true;
                }
            }
        }

        if (gzip) {
            return parseGzipStream(inputMessage.getBody());
        }

        return null;
    }
   
    @Override
    protected void writeInternal(DLSSeries t, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {
        writeToResult(t, outputMessage.getHeaders(), new StreamResult(
                outputMessage.getBody()));

    }
   
    private DLSSeries parseGzipStream(InputStream inputStreamGzip) {
        DLSSeries series = new DLSSeries();
        List<DLSEpisode> episodeList = new ArrayList<DLSEpisode>();
        try {
            InputStream inputStream = new GZIPInputStream(inputStreamGzip);
            ObjectMapper mapper = new ObjectMapper();
            episodeList = mapper.readValue(inputStream, new TypeReference<ArrayList<DLSEpisode>>() {});
            series.setEpisodeList(episodeList);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return series;
    }

    protected void writeToResult(Object o, HttpHeaders headers, Result result)
            throws IOException {
    }
   
    public String convertStreamToString(InputStream is) throws IOException {
        /*
         * To convert the InputStream to String we use the Reader.read(char[]
         * buffer) method. We iterate until the Reader return -1 which means
         * there's no more data to read. We use the StringWriter class to
         * produce the string.
         */
        if (is != null) {
            Writer writer = new StringWriter();

            char[] buffer = new char[1024];
            try {
                Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                int n;
                while ((n = reader.read(buffer)) != -1) {
                    writer.write(buffer, 0, n);
                }
            } finally {
                is.close();
            }
            return writer.toString();
        } else {
            return "";
        }
    }
   
    /** Tracking system operations. */
    private static final Logger LOGGER =  LoggerFactory.getLogger(GzipMarshallingHttpMessageConverter.class);
}


Create RestTemplate instance and add new converter to it:

        RestTemplate restTemplate = new RestTemplate();
        List<HttpMessageConverter<?>> messageConverters = new         ArrayList<HttpMessageConverter<?>>();
        messageConverters.add(new GzipMarshallingHttpMessageConverter());

        restTemplate.setMessageConverters(messageConverters);


Using restTemplate, for example:

            ResponseEntity<DLSSeries> response = null;
           
            try {
                response = restTemplate.exchange(
                        url, HttpMethod.GET, entity, DLSSeries.class);
               
                if(response != null && response.getBody() != null) {
                    DLSSeries series = response.getBody();
                   //do more things here
                }
            } catch(RestClientException e) {
                LOGGER.error(e.getMessage());
            }


P/s: change some example classes to your own classes.

No comments:

Post a Comment