01: package com.icesoft.faces.webapp.http.common.standard;
02:
03: import com.icesoft.faces.webapp.http.common.Request;
04: import com.icesoft.faces.webapp.http.common.RequestProxy;
05: import com.icesoft.faces.webapp.http.common.Response;
06: import com.icesoft.faces.webapp.http.common.ResponseHandler;
07: import com.icesoft.faces.webapp.http.common.ResponseProxy;
08: import com.icesoft.faces.webapp.http.common.Server;
09:
10: import java.io.IOException;
11: import java.io.InputStream;
12: import java.io.OutputStream;
13: import java.util.zip.GZIPOutputStream;
14:
15: public class CompressingServer implements Server {
16: private Server server;
17:
18: public CompressingServer(Server server) {
19: this .server = server;
20: }
21:
22: public void service(Request request) throws Exception {
23: String acceptEncodingHeader = request
24: .getHeader("Accept-Encoding");
25: if (acceptEncodingHeader != null
26: && (acceptEncodingHeader.indexOf("gzip") >= 0 || acceptEncodingHeader
27: .indexOf("compress") >= 0)) {
28: server.service(new CompressingRequest(request));
29: } else {
30: server.service(request);
31: }
32: }
33:
34: public void shutdown() {
35: server.shutdown();
36: }
37:
38: private class CompressingRequest extends RequestProxy {
39: public CompressingRequest(Request request) {
40: super (request);
41: }
42:
43: public void respondWith(final ResponseHandler handler)
44: throws Exception {
45: request.respondWith(new ResponseHandler() {
46: public void respond(Response response) throws Exception {
47: CompressingResponse compressingResponse = new CompressingResponse(
48: response);
49: handler.respond(compressingResponse);
50: compressingResponse.finishCompression();
51: }
52: });
53: }
54: }
55:
56: private class CompressingResponse extends ResponseProxy {
57: private GZIPOutputStream output;
58:
59: public CompressingResponse(Response response) {
60: super (response);
61: response.setHeader("Content-Encoding", "gzip");
62: }
63:
64: public OutputStream writeBody() throws IOException {
65: return output = new GZIPOutputStream(response.writeBody());
66: }
67:
68: public void writeBodyFrom(InputStream in) throws IOException {
69: copy(in, writeBody());
70: }
71:
72: public void finishCompression() throws IOException {
73: if (output != null) {
74: output.finish();
75: }
76: }
77: }
78:
79: private static void copy(InputStream input, OutputStream output)
80: throws IOException {
81: byte[] buf = new byte[4096];
82: int len = 0;
83: while ((len = input.read(buf)) > -1)
84: output.write(buf, 0, len);
85: }
86: }
|