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.exception.HttpConflictException;
23 import davmail.exception.HttpForbiddenException;
24 import davmail.exception.HttpNotFoundException;
25 import davmail.http.HttpClientAdapter;
26 import davmail.util.IOUtil;
27 import org.apache.http.Header;
28 import org.apache.http.HttpEntity;
29 import org.apache.http.HttpResponse;
30 import org.apache.http.HttpStatus;
31 import org.apache.http.client.ResponseHandler;
32 import org.codehaus.jettison.json.JSONException;
33 import org.codehaus.jettison.json.JSONObject;
34
35 import java.io.IOException;
36 import java.io.InputStream;
37 import java.nio.charset.StandardCharsets;
38 import java.util.zip.GZIPInputStream;
39
40
41
42
43 public class JsonResponseHandler implements ResponseHandler<JSONObject> {
44 @Override
45 public JSONObject handleResponse(HttpResponse response) throws IOException {
46 JSONObject jsonResponse = null;
47 Header contentTypeHeader = response.getFirstHeader("Content-Type");
48 if (contentTypeHeader != null && contentTypeHeader.getValue().startsWith("application/json")) {
49 try {
50 jsonResponse = new JSONObject(new String(readResponse(response), StandardCharsets.UTF_8));
51 } catch (JSONException e) {
52 throw new IOException(e.getMessage(), e);
53 }
54 } else {
55 HttpEntity httpEntity = response.getEntity();
56 if (httpEntity != null) {
57 try {
58 return new JSONObject().put("response", new String(readResponse(response), StandardCharsets.UTF_8));
59 } catch (JSONException e) {
60 throw new IOException("Invalid response content");
61 }
62 }
63 }
64
65 if (response.getStatusLine().getStatusCode() >= 400) {
66 String errorMessage = null;
67 if (jsonResponse != null && jsonResponse.optJSONObject("error") != null) {
68 try {
69 JSONObject jsonError = jsonResponse.getJSONObject("error");
70 errorMessage = jsonError.optString("code") + " " + jsonError.optString("message");
71 } catch (JSONException e) {
72
73 }
74 }
75 if (errorMessage == null) {
76 errorMessage = response.getStatusLine().getReasonPhrase();
77 }
78 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_FORBIDDEN) {
79 throw new HttpForbiddenException(errorMessage);
80 }
81 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
82 throw new HttpNotFoundException(errorMessage);
83 }
84 if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CONFLICT) {
85 throw new HttpConflictException(errorMessage);
86 }
87 throw new IOException(errorMessage);
88 }
89 return jsonResponse;
90 }
91
92 protected byte[] readResponse(HttpResponse response) throws IOException {
93 byte[] content;
94 try (InputStream inputStream = response.getEntity().getContent()) {
95 if (HttpClientAdapter.isGzipEncoded(response)) {
96 content = IOUtil.readFully(new GZIPInputStream(inputStream));
97 } else {
98 content = IOUtil.readFully(inputStream);
99 }
100 }
101 return content;
102 }
103 }