001 /*
002 * Copyright 2003-2008 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * You are receiving this code free of charge, which represents many hours of
017 * effort from other individuals and corporations. As a responsible member
018 * of the community, you are asked (but not required) to donate any
019 * enhancements or improvements back to the community under a similar open
020 * source license. Thank you. -TMN
021 */
022 package groovyx.net.http;
023
024 import static groovyx.net.http.ContentEncoding.Type.GZIP;
025
026 import java.io.IOException;
027 import java.io.InputStream;
028 import java.util.zip.GZIPInputStream;
029
030 import org.apache.http.HttpEntity;
031 import org.apache.http.entity.HttpEntityWrapper;
032
033 /**
034 * Content encoding used to handle GZIP responses.
035 * @author <a href='mailto:tnichols@enernoc.com'>Tom Nichols</a>
036 */
037 public class GZIPEncoding extends ContentEncoding {
038
039 /**
040 * Returns the {@link Type#GZIP} encoding string which is added to the
041 * <code>Accept</code> header by the base class.
042 */
043 @Override
044 public String getContentEncoding() {
045 return GZIP.toString();
046 }
047
048 /**
049 * Wraps the raw entity in a {@link GZIPDecompressingEntity}.
050 */
051 @Override
052 public HttpEntity wrapResponseEntity( HttpEntity raw ) {
053 return new GZIPDecompressingEntity( raw );
054 }
055
056 /**
057 * Entity used to interpret a GZIP-encoded response
058 * @author <a href='mailto:tnichols@enernoc.com'>Tom Nichols</a>
059 */
060 protected static class GZIPDecompressingEntity extends HttpEntityWrapper {
061
062 public GZIPDecompressingEntity(final HttpEntity entity) {
063 super(entity);
064 }
065
066 /**
067 * returns a {@link GZIPInputStream} which wraps the original entity's
068 * content stream
069 * @see HttpEntity#getContent()
070 */
071 @Override
072 public InputStream getContent() throws IOException, IllegalStateException {
073 return new GZIPInputStream( wrappedEntity.getContent() );
074 }
075
076 /**
077 * @return -1
078 */
079 @Override
080 public long getContentLength() {
081 // length of un-gzipped content is not known
082 return -1;
083 }
084 }
085 }