/* 
 * Copyright 2011 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.android.tr064.net;

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

import org.apache.http.Header;
import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseInterceptor;
import org.apache.http.ParseException;
import org.apache.http.entity.HttpEntityWrapper;
import org.apache.http.protocol.HttpContext;

/**
 *	HttpResponseInterceptor which inflates gzip content
 */
public class GzipHttpResponseInterceptor implements HttpResponseInterceptor
{
	public void process(HttpResponse response, HttpContext context)
			throws HttpException, IOException
	{
        Header contentEncoding = response.getEntity().getContentEncoding();
        if (contentEncoding != null)
        {
        	try
        	{
                HeaderElement[] elements = contentEncoding.getElements();
                for (HeaderElement element : elements)
                {
                    if (element.getName().equalsIgnoreCase("gzip"))
                    {
                        response.setEntity(new GzipHttpEntity(
                        		response.getEntity()));
                        break;
                    }
                }
        	}
        	catch (ParseException e) { /*ignore*/ }
        }
	}

	private class GzipHttpEntity extends HttpEntityWrapper
	{
		public GzipHttpEntity(HttpEntity entity)
		{
			super(entity);
		}

	    @Override
	    public long getContentLength()
	    {
	        return -1;
	    }

	    @Override
	    public InputStream getContent() throws IllegalStateException, IOException
	    {
	        return new GZIPInputStream(wrappedEntity.getContent());
	    }
	}
}
