forked from intercom/intercom-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHttpClient.java
More file actions
263 lines (224 loc) · 10 KB
/
Copy pathHttpClient.java
File metadata and controls
263 lines (224 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
package io.intercom.api;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.CharStreams;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
class HttpClient {
private static final Logger logger = LoggerFactory.getLogger("intercom-java");
private static final String CLIENT_AGENT_DETAILS = clientAgentDetails();
private static final String USER_AGENT = Intercom.USER_AGENT;
private static final String UTF_8 = "UTF-8";
private static final String APPLICATION_JSON = "application/json";
private static String clientAgentDetails() {
final HashMap<String, String> map = Maps.newHashMap();
final ArrayList<String> propKeys = Lists.newArrayList(
"os.arch", "os.name", "os.version",
"user.language", "user.timezone",
"java.class.version", "java.runtime.version", "java.version",
"java.vm.name", "java.vm.vendor", "java.vm.version");
for (String propKey : propKeys) {
map.put(propKey, System.getProperty(propKey));
}
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
MapperSupport.objectMapper().disable(SerializationFeature.INDENT_OUTPUT).writeValue(baos, map);
} catch (IOException e) {
logger.warn(String.format("could not serialize client agent details [%s]", e.getMessage()), e);
}
return baos.toString();
}
private final ObjectMapper objectMapper;
private final URI uri;
private final Map<String, String> headers;
private final String apiKey = Intercom.getApiKey();
private final HttpConnectorSupplier connection = Intercom.getHttpConnectorSupplier();
public HttpClient(URI uri) {
this(uri, Maps.<String, String>newHashMap());
}
private HttpClient(URI uri, Map<String, String> headers) {
this.uri = uri;
this.headers = headers;
this.objectMapper = MapperSupport.objectMapper();
}
public <T> T get(Class<T> reqres) throws IntercomException {
return get(getJavaType(reqres));
}
<T> T get(JavaType responseType) throws IntercomException {
return executeHttpMethod("GET", null, responseType);
}
public <T> T delete(Class<T> reqres) {
return executeHttpMethod("DELETE", null, getJavaType(reqres));
}
public <T, E> T put(Class<T> reqres, E entity) {
headers.put("Content-Type", APPLICATION_JSON);
return executeHttpMethod("PUT", (E) entity, getJavaType(reqres));
}
public <T, E> T post(Class<T> reqres, E entity) {
headers.put("Content-Type", APPLICATION_JSON);
return executeHttpMethod("POST", entity, getJavaType(reqres));
}
private <T, E> T executeHttpMethod(String method, E entity, JavaType responseType) {
HttpURLConnection conn = null;
try {
conn = initializeConnection(uri, method);
if(entity != null) {
prepareRequestEntity(entity, conn);
}
return runRequest(uri, responseType, conn);
} catch (IOException e) {
return throwLocalException(e);
} finally {
IOUtils.disconnectQuietly(conn);
}
}
private <T> JavaType getJavaType(Class<T> reqres) {
return objectMapper.getTypeFactory().constructType(reqres);
}
// trick java with a dummy return
private <T> T throwLocalException(IOException e) {
throw new IntercomException(String.format("Local exception calling [%s]. Check connectivity and settings. [%s]", uri.toASCIIString(), e.getMessage()), e);
}
private void prepareRequestEntity(Object entity, HttpURLConnection conn) throws IOException {
conn.setDoOutput(true);
OutputStream stream = null;
try {
stream = conn.getOutputStream();
if (logger.isDebugEnabled()) {
logger.info(String.format("api server request --\n%s\n-- ", objectMapper.writeValueAsString(entity)));
}
objectMapper.writeValue(stream, entity);
} finally {
IOUtils.closeQuietly(stream);
}
}
private HttpURLConnection initializeConnection(URI uri, String method) throws IOException {
HttpURLConnection conn = connection.connect(uri);
conn.setRequestMethod(method);
conn = prepareConnection(conn);
conn = applyHeaders(conn);
return conn;
}
private <T> T runRequest(URI uri, JavaType javaType, HttpURLConnection conn) throws IOException {
conn.connect();
final int responseCode = conn.getResponseCode();
if (responseCode >= 200 && responseCode < 300) {
return handleSuccess(javaType, conn, responseCode);
} else {
return handleError(uri, conn, responseCode);
}
}
private <T> T handleError(URI uri, HttpURLConnection conn, int responseCode) throws IOException {
ErrorCollection errors;
try {
errors = objectMapper.readValue(conn.getErrorStream(), ErrorCollection.class);
} catch (IOException e) {
errors = createUnprocessableErrorResponse(e);
}
if (logger.isDebugEnabled()) {
logger.debug("error json follows --\n{}\n-- ", objectMapper.writeValueAsString(errors));
}
return throwException(responseCode, errors);
}
private <T> T handleSuccess(JavaType javaType, HttpURLConnection conn, int responseCode) throws IOException {
if (shouldSkipResponseEntity(javaType, conn, responseCode)) {
return null;
} else {
return readEntity(conn, responseCode, javaType);
}
}
private boolean shouldSkipResponseEntity(JavaType javaType, HttpURLConnection conn, int responseCode) {
return responseCode == 202 || responseCode == 204 || Void.class.equals(javaType.getRawClass()) || "DELETE".equals(conn.getRequestMethod());
}
private <T> T readEntity(HttpURLConnection conn, int responseCode, JavaType javaType) throws IOException {
final InputStream entityStream = conn.getInputStream();
try {
if (logger.isDebugEnabled()) {
final String text = CharStreams.toString(new InputStreamReader(entityStream));
logger.debug("api server response status[{}] --\n{}\n-- ", responseCode, text);
return objectMapper.readValue(text, javaType);
} else {
return objectMapper.readValue(entityStream, javaType);
}
} finally {
IOUtils.closeQuietly(entityStream);
}
}
private <T> T throwException(int responseCode, ErrorCollection errors) {
// bind some well known response codes to exceptions
if (responseCode == 403 || responseCode == 401) {
throw new AuthorizationException(errors);
} else if (responseCode == 429) {
throw new RateLimitException(errors);
} else if (responseCode == 404) {
throw new NotFoundException(errors);
} else if (responseCode == 422) {
throw new InvalidException(errors);
} else if (responseCode == 400 || responseCode == 405 || responseCode == 406) {
throw new ClientException(errors);
} else if (responseCode == 500 || responseCode == 503) {
throw new ServerException(errors);
} else {
throw new IntercomException(errors);
}
}
private HttpURLConnection applyHeaders(HttpURLConnection conn) {
for (Map.Entry<String, String> entry : createHeaders().entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
for (Map.Entry<String, String> entry : createAuthorizationHeaders().entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
return conn;
}
// todo: expose this config
private HttpURLConnection prepareConnection(HttpURLConnection conn) {
conn.setConnectTimeout(Intercom.getConnectionTimeout());
conn.setReadTimeout(Intercom.getRequestTimeout());
conn.setUseCaches(Intercom.isRequestUsingCaches());
return conn;
}
private Map<String, String> createAuthorizationHeaders() {
if (Intercom.getAuthScheme().equals(Intercom.AUTH_BEARER)) {
headers.put("Authorization", "Bearer " + apiKey);
} else if (Intercom.getAuthScheme().equals(Intercom.AUTH_BASIC)) {
final String authString = Intercom.getAppID() + ":" + Intercom.getApiKey();
headers.put("Authorization", "Basic " + Base64.encodeBase64String(authString.getBytes()));
}
return headers;
}
private Map<String, String> createHeaders() {
headers.put("User-Agent", USER_AGENT);
headers.put("X-Client-Platform-Details", CLIENT_AGENT_DETAILS);
headers.put("Accept-Charset", UTF_8);
headers.put("Accept", APPLICATION_JSON);
return headers;
}
private ErrorCollection createUnprocessableErrorResponse(IOException e) {
ErrorCollection errors;
final long grepCode = getGrepCode();
final String msg = String.format("could not parse error response: [%s]", e.getLocalizedMessage());
logger.error(String.format("[%016x] %s", grepCode, msg), e);
Error err = new Error("unprocessable_entity", String.format("%s logged with code [%016x]", msg, grepCode));
errors = new ErrorCollection(Lists.newArrayList(err));
return errors;
}
private long getGrepCode() {
return ThreadLocalRandom.current().nextLong();
}
}