/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache license, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.internna.iwebmvc.core.jee.gzip;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.GZIPOutputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
/**
* A servlet filter that compresses the response contents.
*
* @author Jayson Falkner [http://www.jspbook.com/]
* @author Jose Noheda
*/
public class GZIPResponseStream extends ServletOutputStream {
private int bufferSize = 100000;
protected OutputStream bufferedOutput = new ByteArrayOutputStream();
protected HttpServletResponse response = null;
protected ServletOutputStream output = null;
public GZIPResponseStream(HttpServletResponse response) throws IOException {
super();
this.response = response;
this.output = response.getOutputStream();
}
@Override
public void close() throws IOException {
if (bufferedOutput instanceof ByteArrayOutputStream) {
ByteArrayOutputStream compressedContent = new ByteArrayOutputStream();
GZIPOutputStream gzipstream = new GZIPOutputStream(compressedContent);
gzipstream.write(((ByteArrayOutputStream) bufferedOutput).toByteArray());
gzipstream.finish();
byte[] compressedBytes = compressedContent.toByteArray();
response.setContentLength(compressedBytes.length);
response.addHeader("Content-Encoding", "gzip");
output.write(compressedBytes);
} else ((GZIPOutputStream) bufferedOutput).finish();
output.flush();
output.close();
}
@Override
public void flush() throws IOException {
bufferedOutput.flush();
}
public void write(int b) throws IOException {
checkBufferSize(1);
bufferedOutput.write((byte) b);
}
@Override
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte b[], int off, int len) throws IOException {
checkBufferSize(len);
bufferedOutput.write(b, off, len);
}
private void checkBufferSize(int length) throws IOException {
if (bufferedOutput instanceof ByteArrayOutputStream) {
ByteArrayOutputStream baos = (ByteArrayOutputStream) bufferedOutput;
if (baos.size() + length > bufferSize) {
response.addHeader("Content-Encoding", "gzip");
bufferedOutput = new GZIPOutputStream(output);
bufferedOutput.write(baos.toByteArray());
}
}
}
}