1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package davmail.exchange.graph;
21
22 import davmail.http.HttpClientAdapter;
23 import davmail.util.IOUtil;
24 import org.apache.http.Header;
25 import org.apache.http.HttpEntity;
26 import org.apache.http.HttpResponse;
27 import org.apache.http.client.ResponseHandler;
28 import org.codehaus.jettison.json.JSONException;
29 import org.codehaus.jettison.json.JSONObject;
30
31 import java.io.IOException;
32 import java.io.InputStream;
33 import java.nio.charset.StandardCharsets;
34 import java.util.zip.GZIPInputStream;
35
36
37
38
39 public class JsonResponseHandler implements ResponseHandler<JSONObject> {
40 @Override
41 public JSONObject handleResponse(HttpResponse response) throws IOException {
42 JSONObject jsonResponse = null;
43 Header contentTypeHeader = response.getFirstHeader("Content-Type");
44 if (contentTypeHeader != null && contentTypeHeader.getValue().startsWith("application/json")) {
45 try {
46 jsonResponse = new JSONObject(new String(readResponse(response), StandardCharsets.UTF_8));
47 } catch (JSONException e) {
48 throw new IOException(e.getMessage(), e);
49 }
50 } else {
51 HttpEntity httpEntity = response.getEntity();
52 if (httpEntity != null) {
53 try {
54 return new JSONObject().put("response", new String(readResponse(response), StandardCharsets.UTF_8));
55 } catch (JSONException e) {
56 throw new IOException("Invalid response content");
57 }
58 }
59 }
60
61 if (response.getStatusLine().getStatusCode() >= 400) {
62 String errorMessage = null;
63 if (jsonResponse != null && jsonResponse.optJSONObject("error") != null) {
64 try {
65 JSONObject jsonError = jsonResponse.getJSONObject("error");
66 errorMessage = jsonError.optString("code") + " " + jsonError.optString("message");
67 } catch (JSONException e) {
68
69 }
70 }
71 if (errorMessage == null) {
72 errorMessage = response.getStatusLine().getReasonPhrase();
73 }
74 throw new IOException(errorMessage);
75 }
76 return jsonResponse;
77 }
78
79 protected byte[] readResponse(HttpResponse response) throws IOException {
80 byte[] content;
81 try (InputStream inputStream = response.getEntity().getContent()) {
82 if (HttpClientAdapter.isGzipEncoded(response)) {
83 content = IOUtil.readFully(new GZIPInputStream(inputStream));
84 } else {
85 content = IOUtil.readFully(inputStream);
86 }
87 }
88 return content;
89 }
90 }