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.
5 package org.chromium.components.devtools_bridge.apiary;
7 import android.util.JsonReader;
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;
16 import java.io.IOException;
17 import java.io.InputStreamReader;
20 * Base class for a ResponseHandler that reads response with JsonReader. Like BasicResponseHandler
21 * throws HttpResponseException if response code >= 300.
23 * It catchs JsonReader's runtime exception (IllegalStateException and IllegalArgumentException)
24 * and wraps them into ResponseFormatException.
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());
36 public final T handleResponse(HttpResponse response)
37 throws IOException, ClientProtocolException {
38 checkStatus(response);
39 HttpEntity entity = response.getEntity();
41 throw new ClientProtocolException("Missing content");
43 JsonReader reader = new JsonReader(new InputStreamReader(entity.getContent()));
45 T result = readResponse(reader);
49 throw new ClientProtocolException("Missing result");
53 } catch (IllegalStateException e) {
54 throw new ResponseFormatException(e);
55 } catch (IllegalArgumentException e) {
56 throw new ResponseFormatException(e);
60 public abstract T readResponse(JsonReader reader)
61 throws IOException, ResponseFormatException;
63 public static class ResponseFormatException extends ClientProtocolException {
64 public ResponseFormatException(RuntimeException readerException) {
65 super(readerException);
68 public ResponseFormatException() {}