package org.bench4q.recorder.httpcapture.generator;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GzipDecoder extends ContentDecoder {

	public byte[] decodeContent(InputStream inputStream) {
		try {
			GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
			ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

			byte[] buf = new byte[1024];
			int len;
			while ((len = gzipInputStream.read(buf)) > 0) {
				outputStream.write(buf, 0, len);
			}
			return outputStream.toByteArray();
		} catch (IOException e) {
			logger.error("decodeContent", e);
			return null;
		}
	}
	public String decodeContent(InputStream inputStream, Charset charset){
		InputStream is = inputStream;
		GZIPInputStream gzin;
		try {
			gzin = new GZIPInputStream(is);
			InputStreamReader isr = new InputStreamReader(gzin, charset); 
	        java.io.BufferedReader br = new java.io.BufferedReader(isr);
	        StringBuffer sb = new StringBuffer();
	        String tempbf;
	        while ((tempbf = br.readLine()) != null) {
	            sb.append(tempbf);
	            sb.append("\r\n");
	        }
	        isr.close();
	        gzin.close();
	        return sb.toString();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
}
