Source code: org/apache/http/contrib/compress/GzipCompressingEntity.java
1 /*
2 * $HeadURL: https://svn.apache.org/repos/asf/jakarta/httpcomponents/httpcore/tags/4.0-alpha2/src/contrib/org/apache/http/contrib/compress/GzipCompressingEntity.java $
3 * $Revision: 379761 $
4 * $Date: 2006-02-22 14:01:42 +0100 (Wed, 22 Feb 2006) $
5 *
6 * ====================================================================
7 *
8 * Copyright 1999-2006 The Apache Software Foundation
9 *
10 * Licensed under the Apache License, Version 2.0 (the "License");
11 * you may not use this file except in compliance with the License.
12 * You may obtain a copy of the License at
13 *
14 * http://www.apache.org/licenses/LICENSE-2.0
15 *
16 * Unless required by applicable law or agreed to in writing, software
17 * distributed under the License is distributed on an "AS IS" BASIS,
18 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 * See the License for the specific language governing permissions and
20 * limitations under the License.
21 * ====================================================================
22 *
23 * This software consists of voluntary contributions made by many
24 * individuals on behalf of the Apache Software Foundation. For more
25 * information on the Apache Software Foundation, please see
26 * <http://www.apache.org/>.
27 *
28 */
29
30 package org.apache.http.contrib.compress;
31
32 import java.io.IOException;
33 import java.io.InputStream;
34 import java.io.OutputStream;
35 import java.util.zip.GZIPOutputStream;
36
37 import org.apache.http.Header;
38 import org.apache.http.HttpEntity;
39 import org.apache.http.entity.HttpEntityWrapper;
40 import org.apache.http.protocol.HTTP;
41
42 /**
43 + * Wrapping entity that compresses content when {@link #writeTo writing}.
44 + *
45 * @author <a href="mailto:oleg at ural.ru">Oleg Kalnichevski</a>
46 *
47 * @version $Revision: 379761 $
48 *
49 * @since 4.0
50 */
51 public class GzipCompressingEntity extends HttpEntityWrapper {
52
53 private static final String GZIP_CODEC = "gzip";
54
55 public GzipCompressingEntity(final HttpEntity entity) {
56 super(entity);
57 }
58
59 public Header getContentEncoding() {
60 return new Header(HTTP.CONTENT_ENCODING, GZIP_CODEC);
61 }
62
63 public long getContentLength() {
64 return -1;
65 }
66
67 public boolean isChunked() {
68 // force content chunking
69 return true;
70 }
71
72 public void writeTo(final OutputStream outstream) throws IOException {
73 if (outstream == null) {
74 throw new IllegalArgumentException("Output stream may not be null");
75 }
76 GZIPOutputStream gzip = new GZIPOutputStream(outstream);
77 InputStream in = wrappedEntity.getContent();
78 byte[] tmp = new byte[2048];
79 int l;
80 while ((l = in.read(tmp)) != -1) {
81 gzip.write(tmp, 0, l);
82 }
83 gzip.close();
84 }
85
86 } // class GzipCompressingEntity