1 /* 2 * Copyright 2008 Netflix, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package net.oauth.http; 18 19 import java.io.IOException; 20 import java.io.InputStream; 21 import java.util.Map; 22 import java.util.zip.GZIPInputStream; 23 import java.util.zip.InflaterInputStream; 24 25 /** 26 * A decorator that handles Content-Encoding. 27 * @hide 28 */ 29 public class HttpMessageDecoder extends HttpResponseMessage { 30 31 /** 32 * Decode the given message if necessary and possible. 33 * 34 * @return a decorator that decodes the body of the given message; or the 35 * given message if this class can't decode it. 36 */ 37 public static HttpResponseMessage decode(HttpResponseMessage message) 38 throws IOException { 39 if (message != null) { 40 String encoding = getEncoding(message); 41 if (encoding != null) { 42 return new HttpMessageDecoder(message, encoding); 43 } 44 } 45 return message; 46 } 47 48 public static final String GZIP = "gzip"; 49 public static final String DEFLATE = "deflate"; 50 public static final String ACCEPTED = GZIP + "," + DEFLATE; 51 52 private static String getEncoding(HttpMessage message) { 53 String encoding = message.getHeader(CONTENT_ENCODING); 54 if (encoding == null) { 55 // That's easy. 56 } else if (GZIP.equalsIgnoreCase(encoding) 57 || ("x-" + GZIP).equalsIgnoreCase(encoding)) { 58 return GZIP; 59 } else if (DEFLATE.equalsIgnoreCase(encoding)) { 60 return DEFLATE; 61 } 62 return null; 63 } 64 65 private HttpMessageDecoder(HttpResponseMessage in, String encoding) 66 throws IOException { 67 super(in.method, in.url); 68 this.headers.addAll(in.headers); 69 removeHeaders(CONTENT_ENCODING); // handled here 70 removeHeaders(CONTENT_LENGTH); // unpredictable 71 InputStream body = in.getBody(); 72 if (body != null) { 73 if (encoding == GZIP) { 74 body = new GZIPInputStream(body); 75 } else if (encoding == DEFLATE) { 76 body = new InflaterInputStream(body); 77 } else { 78 assert false; 79 } 80 } 81 this.body = body; 82 this.in = in; 83 } 84 85 private final HttpResponseMessage in; 86 87 @Override 88 public void dump(Map<String, Object> into) throws IOException { 89 in.dump(into); 90 } 91 92 @Override 93 public int getStatusCode() throws IOException { 94 return in.getStatusCode(); 95 } 96 97 } 98