The new Android client, featuring:
[zxing.git] / android / src / com / google / zxing / client / android / AndroidHttpClient.java
1 /*
2  * Copyright (C) 2008 ZXing authors
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 com.google.zxing.client.android;
18
19 import android.util.Log;
20 import org.apache.http.Header;
21 import org.apache.http.HttpEntity;
22 import org.apache.http.HttpEntityEnclosingRequest;
23 import org.apache.http.HttpException;
24 import org.apache.http.HttpHost;
25 import org.apache.http.HttpMessage;
26 import org.apache.http.HttpRequest;
27 import org.apache.http.HttpRequestInterceptor;
28 import org.apache.http.HttpResponse;
29 import org.apache.http.client.HttpClient;
30 import org.apache.http.client.ResponseHandler;
31 import org.apache.http.client.methods.HttpUriRequest;
32 import org.apache.http.client.params.HttpClientParams;
33 import org.apache.http.client.protocol.ClientContext;
34 import org.apache.http.conn.ClientConnectionManager;
35 import org.apache.http.conn.scheme.PlainSocketFactory;
36 import org.apache.http.conn.scheme.Scheme;
37 import org.apache.http.conn.scheme.SchemeRegistry;
38 import org.apache.http.conn.ssl.SSLSocketFactory;
39 import org.apache.http.entity.AbstractHttpEntity;
40 import org.apache.http.entity.ByteArrayEntity;
41 import org.apache.http.impl.client.DefaultHttpClient;
42 import org.apache.http.impl.client.RequestWrapper;
43 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
44 import org.apache.http.params.BasicHttpParams;
45 import org.apache.http.params.HttpConnectionParams;
46 import org.apache.http.params.HttpParams;
47 import org.apache.http.params.HttpProtocolParams;
48 import org.apache.http.protocol.BasicHttpContext;
49 import org.apache.http.protocol.BasicHttpProcessor;
50 import org.apache.http.protocol.HttpContext;
51
52 import java.io.ByteArrayOutputStream;
53 import java.io.IOException;
54 import java.io.InputStream;
55 import java.io.OutputStream;
56 import java.net.URI;
57 import java.util.zip.GZIPInputStream;
58 import java.util.zip.GZIPOutputStream;
59
60 /**
61  * <p>Subclass of the Apache {@link DefaultHttpClient} that is configured with
62  * reasonable default settings and registered schemes for Android, and
63  * also lets the user add {@link HttpRequestInterceptor} classes.
64  * Don't create this directly, use the {@link #newInstance} factory method.</p>
65  * <p/>
66  * <p>This client processes cookies but does not retain them by default.
67  * To retain cookies, simply add a cookie store to the HttpContext:
68  * <pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre>
69  * </p>
70  */
71 public final class AndroidHttpClient implements HttpClient {
72
73   // Gzip of data shorter than this probably won't be worthwhile
74   public static final long DEFAULT_SYNC_MIN_GZIP_BYTES = 256;
75
76   private static final String TAG = "AndroidHttpClient";
77
78
79   /**
80    * Set if HTTP requests are blocked from being executed on this thread
81    */
82   private static final ThreadLocal<Boolean> sThreadBlocked =
83       new ThreadLocal<Boolean>();
84
85   /**
86    * Interceptor throws an exception if the executing thread is blocked
87    */
88   private static final HttpRequestInterceptor sThreadCheckInterceptor =
89       new HttpRequestInterceptor() {
90         public void process(HttpRequest request, HttpContext context) {
91           if (sThreadBlocked.get() != null && sThreadBlocked.get()) {
92             throw new RuntimeException("This thread forbids HTTP requests");
93           }
94         }
95       };
96
97   /**
98    * Create a new HttpClient with reasonable defaults (which you can update).
99    *
100    * @param userAgent to report in your HTTP requests.
101    * @return AndroidHttpClient for you to use for all your requests.
102    */
103   public static AndroidHttpClient newInstance(String userAgent) {
104     HttpParams params = new BasicHttpParams();
105
106     // Turn off stale checking.  Our connections break all the time anyway,
107     // and it's not worth it to pay the penalty of checking every time.
108     HttpConnectionParams.setStaleCheckingEnabled(params, false);
109
110     // Default connection and socket timeout of 20 seconds.  Tweak to taste.
111     HttpConnectionParams.setConnectionTimeout(params, 20 * 1000);
112     HttpConnectionParams.setSoTimeout(params, 20 * 1000);
113     HttpConnectionParams.setSocketBufferSize(params, 8192);
114
115     // Don't handle redirects -- return them to the caller.  Our code
116     // often wants to re-POST after a redirect, which we must do ourselves.
117     HttpClientParams.setRedirecting(params, false);
118
119     // Set the specified user agent and register standard protocols.
120     HttpProtocolParams.setUserAgent(params, userAgent);
121     SchemeRegistry schemeRegistry = new SchemeRegistry();
122     schemeRegistry.register(new Scheme("http",
123         PlainSocketFactory.getSocketFactory(), 80));
124     schemeRegistry.register(new Scheme("https",
125         SSLSocketFactory.getSocketFactory(), 443));
126     ClientConnectionManager manager =
127         new ThreadSafeClientConnManager(params, schemeRegistry);
128
129     // We use a factory method to modify superclass initialization
130     // parameters without the funny call-a-static-method dance.
131     return new AndroidHttpClient(manager, params);
132   }
133
134   private final HttpClient delegate;
135
136   private RuntimeException mLeakedException = new IllegalStateException(
137       "AndroidHttpClient created and never closed");
138
139   private AndroidHttpClient(ClientConnectionManager ccm, HttpParams params) {
140     this.delegate = new DefaultHttpClient(ccm, params) {
141       @Override
142       protected BasicHttpProcessor createHttpProcessor() {
143         // Add interceptor to prevent making requests from main thread.
144         BasicHttpProcessor processor = super.createHttpProcessor();
145         processor.addRequestInterceptor(sThreadCheckInterceptor);
146         processor.addRequestInterceptor(new CurlLogger());
147
148         return processor;
149       }
150
151       @Override
152       protected HttpContext createHttpContext() {
153         // Same as DefaultHttpClient.createHttpContext() minus the
154         // cookie store.
155         HttpContext context = new BasicHttpContext();
156         context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes());
157         context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs());
158         context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider());
159         return context;
160       }
161     };
162   }
163
164   @Override
165   protected void finalize() throws Throwable {
166     super.finalize();
167     if (mLeakedException != null) {
168       Log.e(TAG, "Leak found", mLeakedException);
169       mLeakedException = null;
170     }
171   }
172
173   /**
174    * Block this thread from executing HTTP requests.
175    * Used to guard against HTTP requests blocking the main application thread.
176    *
177    * @param blocked if HTTP requests run on this thread should be denied
178    */
179   public static void setThreadBlocked(boolean blocked) {
180     sThreadBlocked.set(blocked);
181   }
182
183   /**
184    * Modifies a request to indicate to the server that we would like a
185    * gzipped response.  (Uses the "Accept-Encoding" HTTP header.)
186    *
187    * @param request the request to modify
188    * @see #getUngzippedContent
189    */
190   public static void modifyRequestToAcceptGzipResponse(HttpMessage request) {
191     request.addHeader("Accept-Encoding", "gzip");
192   }
193
194   /**
195    * Gets the input stream from a response entity.  If the entity is gzipped
196    * then this will get a stream over the uncompressed data.
197    *
198    * @param entity the entity whose content should be read
199    * @return the input stream to read from
200    * @throws IOException
201    */
202   public static InputStream getUngzippedContent(HttpEntity entity) throws IOException {
203     InputStream responseStream = entity.getContent();
204     if (responseStream == null) {
205       return responseStream;
206     }
207     Header header = entity.getContentEncoding();
208     if (header == null) {
209       return responseStream;
210     }
211     String contentEncoding = header.getValue();
212     if (contentEncoding == null) {
213       return responseStream;
214     }
215     if (contentEncoding.contains("gzip")) responseStream = new GZIPInputStream(responseStream);
216     return responseStream;
217   }
218
219   /**
220    * Release resources associated with this client.  You must call this,
221    * or significant resources (sockets and memory) may be leaked.
222    */
223   public void close() {
224     if (mLeakedException != null) {
225       getConnectionManager().shutdown();
226       mLeakedException = null;
227     }
228   }
229
230   public HttpParams getParams() {
231     return delegate.getParams();
232   }
233
234   public ClientConnectionManager getConnectionManager() {
235     return delegate.getConnectionManager();
236   }
237
238   public HttpResponse execute(HttpUriRequest request) throws IOException {
239     return delegate.execute(request);
240   }
241
242   public HttpResponse execute(HttpUriRequest request, HttpContext context) throws IOException {
243     return delegate.execute(request, context);
244   }
245
246   public HttpResponse execute(HttpHost target, HttpRequest request) throws IOException {
247     return delegate.execute(target, request);
248   }
249
250   public HttpResponse execute(HttpHost target, HttpRequest request,
251                               HttpContext context) throws IOException {
252     return delegate.execute(target, request, context);
253   }
254
255   public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler) throws IOException {
256     return delegate.execute(request, responseHandler);
257   }
258
259   public <T> T execute(HttpUriRequest request, ResponseHandler<? extends T> responseHandler, HttpContext context)
260       throws IOException {
261     return delegate.execute(request, responseHandler, context);
262   }
263
264   public <T> T execute(HttpHost target, HttpRequest request, ResponseHandler<? extends T> responseHandler)
265       throws IOException {
266     return delegate.execute(target, request, responseHandler);
267   }
268
269   public <T> T execute(HttpHost target, HttpRequest request,
270                        ResponseHandler<? extends T> responseHandler,
271                        HttpContext context)
272       throws IOException {
273     return delegate.execute(target, request, responseHandler, context);
274   }
275
276   /**
277    * Compress data to send to server.
278    * Creates a Http Entity holding the gzipped data.
279    * The data will not be compressed if it is too short.
280    *
281    * @param data The bytes to compress
282    * @return Entity holding the data
283    */
284   public static AbstractHttpEntity getCompressedEntity(byte data[]) throws IOException {
285     AbstractHttpEntity entity;
286     if (data.length < getMinGzipSize()) {
287       entity = new ByteArrayEntity(data);
288     } else {
289       ByteArrayOutputStream arr = new ByteArrayOutputStream();
290       OutputStream zipper = new GZIPOutputStream(arr);
291       zipper.write(data);
292       zipper.close();
293       entity = new ByteArrayEntity(arr.toByteArray());
294       entity.setContentEncoding("gzip");
295     }
296     return entity;
297   }
298
299   /**
300    * Retrieves the minimum size for compressing data.
301    * Shorter data will not be compressed.
302    */
303   public static long getMinGzipSize() {
304     return DEFAULT_SYNC_MIN_GZIP_BYTES;
305   }
306
307   /* cURL logging support. */
308
309   /**
310    * Logging tag and level.
311    */
312   private static class LoggingConfiguration {
313
314     private final String tag;
315     private final int level;
316
317     private LoggingConfiguration(String tag, int level) {
318       this.tag = tag;
319       this.level = level;
320     }
321
322     /**
323      * Returns true if logging is turned on for this configuration.
324      */
325     private boolean isLoggable() {
326       return Log.isLoggable(tag, level);
327     }
328
329     /**
330      * Prints a message using this configuration.
331      */
332     private void println(String message) {
333       Log.println(level, tag, message);
334     }
335   }
336
337   /**
338    * cURL logging configuration.
339    */
340   private volatile LoggingConfiguration curlConfiguration;
341
342   /**
343    * Enables cURL request logging for this client.
344    *
345    * @param name  to log messages with
346    * @param level at which to log messages (see {@link android.util.Log})
347    */
348   public void enableCurlLogging(String name, int level) {
349     if (name == null) {
350       throw new NullPointerException("name");
351     }
352     if (level < Log.VERBOSE || level > Log.ASSERT) {
353       throw new IllegalArgumentException("Level is out of range ["
354           + Log.VERBOSE + ".." + Log.ASSERT + "]");
355     }
356
357     curlConfiguration = new LoggingConfiguration(name, level);
358   }
359
360   /**
361    * Disables cURL logging for this client.
362    */
363   public void disableCurlLogging() {
364     curlConfiguration = null;
365   }
366
367   /**
368    * Logs cURL commands equivalent to requests.
369    */
370   private class CurlLogger implements HttpRequestInterceptor {
371     public void process(HttpRequest request, HttpContext context)
372         throws HttpException, IOException {
373       LoggingConfiguration configuration = curlConfiguration;
374       if (configuration != null
375           && configuration.isLoggable()
376           && request instanceof HttpUriRequest) {
377         configuration.println(toCurl((HttpUriRequest) request));
378       }
379     }
380
381     /**
382      * Generates a cURL command equivalent to the given request.
383      */
384     private String toCurl(HttpUriRequest request) throws IOException {
385       StringBuilder builder = new StringBuilder();
386
387       builder.append("curl ");
388
389       for (Header header : request.getAllHeaders()) {
390         builder.append("--header \"");
391         builder.append(header.toString().trim());
392         builder.append("\" ");
393       }
394
395       URI uri = request.getURI();
396
397       // If this is a wrapped request, use the URI from the original
398       // request instead. getURI() on the wrapper seems to return a
399       // relative URI. We want an absolute URI.
400       if (request instanceof RequestWrapper) {
401         HttpRequest original = ((RequestWrapper) request).getOriginal();
402         if (original instanceof HttpUriRequest) {
403           uri = ((HttpUriRequest) original).getURI();
404         }
405       }
406
407       builder.append('"');
408       builder.append(uri);
409       builder.append('"');
410
411       if (request instanceof HttpEntityEnclosingRequest) {
412         HttpEntityEnclosingRequest entityRequest =
413             (HttpEntityEnclosingRequest) request;
414         HttpEntity entity = entityRequest.getEntity();
415         if (entity != null && entity.isRepeatable()) {
416           if (entity.getContentLength() < 1024) {
417             ByteArrayOutputStream stream = new ByteArrayOutputStream();
418             entity.writeTo(stream);
419             String entityString = stream.toString();
420             // TODO: Check the content type, too.
421             builder.append(" --data-ascii \"").append(entityString).append('"');
422           } else {
423             builder.append(" [TOO MUCH DATA TO INCLUDE]");
424           }
425         }
426       }
427
428       return builder.toString();
429     }
430   }
431
432 }