Upstream version 11.40.271.0
[platform/framework/web/crosswalk.git] / src / components / devtools_bridge / android / java / src / org / chromium / components / devtools_bridge / apiary / JsonResponseHandler.java
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package org.chromium.components.devtools_bridge.apiary;
6
7 import android.util.JsonReader;
8
9 import org.apache.http.HttpEntity;
10 import org.apache.http.HttpResponse;
11 import org.apache.http.StatusLine;
12 import org.apache.http.client.ClientProtocolException;
13 import org.apache.http.client.HttpResponseException;
14 import org.apache.http.client.ResponseHandler;
15
16 import java.io.IOException;
17 import java.io.InputStreamReader;
18
19 /**
20  * Base class for a ResponseHandler that reads response with JsonReader. Like BasicResponseHandler
21  * throws HttpResponseException if response code >= 300.
22  *
23  * It catchs JsonReader's runtime exception (IllegalStateException and IllegalArgumentException)
24  * and wraps them into ResponseFormatException.
25  */
26 abstract class JsonResponseHandler<T> implements ResponseHandler<T> {
27     public static void checkStatus(HttpResponse response) throws HttpResponseException {
28         StatusLine statusLine = response.getStatusLine();
29         if (response.getStatusLine().getStatusCode() >= 300) {
30             throw new HttpResponseException(
31                     statusLine.getStatusCode(), statusLine.getReasonPhrase());
32         }
33     }
34
35     @Override
36     public final T handleResponse(HttpResponse response)
37             throws IOException, ClientProtocolException {
38         checkStatus(response);
39         HttpEntity entity = response.getEntity();
40         if (entity == null) {
41             throw new ClientProtocolException("Missing content");
42         }
43         JsonReader reader = new JsonReader(new InputStreamReader(entity.getContent()));
44         try {
45             T result = readResponse(reader);
46             reader.close();
47
48             if (result == null) {
49                 throw new ClientProtocolException("Missing result");
50             }
51
52             return result;
53         } catch (IllegalStateException e) {
54             throw new ResponseFormatException(e);
55         } catch (IllegalArgumentException e) {
56             throw new ResponseFormatException(e);
57         }
58     }
59
60     public abstract T readResponse(JsonReader reader)
61             throws IOException, ResponseFormatException;
62
63     public static class ResponseFormatException extends ClientProtocolException {
64         public ResponseFormatException(RuntimeException readerException) {
65             super(readerException);
66         }
67
68         public ResponseFormatException() {}
69     }
70 }