/**
 * 
 */
package it.mice.voila.runtime.web.restws;

import java.io.IOException;
import java.io.InputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;

/**
 *
 */
//@Component
public class MappingJacksonCompressHttpMessageConverter extends MappingJacksonHttpMessageConverter {
	/** {@inheritDoc}
	 * @see org.springframework.http.converter.AbstractHttpMessageConverter#readInternal(java.lang.Class, org.springframework.http.HttpInputMessage)
	 */
	@Override
	protected Object readInternal(Class<? extends Object> clazz, HttpInputMessage inputMessage)
			throws IOException, HttpMessageNotReadableException {
		return super.readInternal(clazz, decompress(inputMessage));
	}
	
	protected HttpInputMessage decompress(final HttpInputMessage inputMessage) {
		return new HttpInputMessage() {
			public HttpHeaders getHeaders() {
				return inputMessage.getHeaders();
			}
			public InputStream getBody() throws IOException {
				InputStream body = inputMessage.getBody();
				if (!(body instanceof InflaterInputStream)) {
					String contentEncoding = inputMessage.getHeaders().getFirst("content-encoding");
					if ("deflate".equals(contentEncoding)) {
						body = new InflaterInputStream(body);
					} else if ("gzip".equals(contentEncoding)) {
						body = new GZIPInputStream(body);
					}
				}
				return body;
			}
		};
	}
}
