forked from sendgrid/java-http-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathClient.java
More file actions
455 lines (387 loc) · 11.6 KB
/
Client.java
File metadata and controls
455 lines (387 loc) · 11.6 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
package com.sendgrid;
import java.io.Closeable;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;
import java.util.Arrays;
import java.util.List;
import org.apache.http.Header;
import org.apache.http.HttpMessage;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
/**
* Hack to get DELETE to accept a request body.
*/
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
}
/**
* Class Client allows for quick and easy access any REST or REST-like API.
*/
public class Client implements Closeable {
private CloseableHttpClient httpClient;
private Boolean test;
private boolean createdHttpClient;
/**
* Constructor for using the default CloseableHttpClient.
*/
public Client() {
this.httpClient = HttpClients.createDefault();
this.test = false;
this.createdHttpClient = true;
}
/**
* Constructor for passing in an httpClient, typically for mocking. Passed-in httpClient will not be closed
* by this Client.
*
* @param httpClient
* an Apache CloseableHttpClient
*/
public Client(CloseableHttpClient httpClient) {
this(httpClient, false);
}
/**
* Constructor for passing in a test parameter to allow for http calls.
*
* @param test
* is a Bool
*/
public Client(Boolean test) {
this(HttpClients.createDefault(), test);
}
/**
* Constructor for passing in an httpClient and test parameter to allow for http calls.
*
* @param httpClient
* an Apache CloseableHttpClient
* @param test
* is a Bool
*/
public Client(CloseableHttpClient httpClient, Boolean test) {
this.httpClient = httpClient;
this.test = test;
this.createdHttpClient = true;
}
/**
* Add query parameters to a URL.
*
* @param baseUri
* (e.g. "api.sendgrid.com")
* @param endpoint
* (e.g. "/your/endpoint/path")
* @param queryParams
* map of key, values representing the query parameters
* @throws URISyntaxException
* in of a URI syntax error
*/
public URI buildUri(String baseUri, String endpoint, Map<String, String> queryParams) throws URISyntaxException {
URIBuilder builder = new URIBuilder();
URI uri = null;
if (this.test == true) {
builder.setScheme("http");
} else {
builder.setScheme("https");
}
builder.setHost(baseUri);
builder.setPath(endpoint);
if (queryParams != null) {
String multiValueDelimiter = "&";
for (Map.Entry<String, String> entry : queryParams.entrySet()) {
String value = entry.getValue();
if (value.indexOf(multiValueDelimiter) != -1) {
List<String> values = Arrays.asList(value.split(multiValueDelimiter));
for (String val : values) {
builder.addParameter(entry.getKey(), val);
}
} else {
builder.setParameter(entry.getKey(), entry.getValue());
}
}
}
try {
uri = builder.build();
} catch (URISyntaxException ex) {
throw ex;
}
return uri;
}
/**
* Prepare a Response object from an API call via Apache's HTTP client.
*
* @param response
* from a call to a CloseableHttpClient
* @throws IOException
* in case of a network error
* @return the response object
*/
public Response getResponse(CloseableHttpResponse response) throws IOException {
ResponseHandler<String> handler = new SendGridResponseHandler();
String responseBody = handler.handleResponse(response);
int statusCode = response.getStatusLine().getStatusCode();
Header[] headers = response.getAllHeaders();
Map<String, String> responseHeaders = new HashMap<String, String>();
for (Header h : headers) {
responseHeaders.put(h.getName(), h.getValue());
}
return new Response(statusCode, responseBody, responseHeaders);
}
/**
* Make a GET request and provide the status code, response body and
* response headers.
*
* @param request
* the request object
* @throws URISyntaxException
* in case of a URI syntax error
* @throws IOException
* in case of a network error
* @return the response object
*/
public Response get(Request request) throws URISyntaxException, IOException {
URI uri = null;
HttpGet httpGet = null;
try {
uri = buildUri(request.getBaseUri(), request.getEndpoint(), request.getQueryParams());
httpGet = new HttpGet(uri.toString());
} catch (URISyntaxException ex) {
throw ex;
}
if (request.getHeaders() != null) {
for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
httpGet.setHeader(entry.getKey(), entry.getValue());
}
}
return executeApiCall(httpGet);
}
/**
* Make a POST request and provide the status code, response body and
* response headers.
*
* @param request
* the request object
* @throws URISyntaxException
* in case of a URI syntax error
* @throws IOException
* in case of a network error
* @return the response object
*/
public Response post(Request request) throws URISyntaxException, IOException {
URI uri = null;
HttpPost httpPost = null;
try {
uri = buildUri(request.getBaseUri(), request.getEndpoint(), request.getQueryParams());
httpPost = new HttpPost(uri.toString());
} catch (URISyntaxException ex) {
throw ex;
}
if (request.getHeaders() != null) {
for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
httpPost.setHeader(entry.getKey(), entry.getValue());
}
}
httpPost.setEntity(new StringEntity(request.getBody(), Charset.forName("UTF-8")));
writeContentTypeIfNeeded(request, httpPost);
return executeApiCall(httpPost);
}
/**
* Make a PATCH request and provide the status code, response body and
* response headers.
*
* @param request
* the request object
* @throws URISyntaxException
* in case of a URI syntax error
* @throws IOException
* in case of a network error
* @return the response object
*/
public Response patch(Request request) throws URISyntaxException, IOException {
URI uri = null;
HttpPatch httpPatch = null;
try {
uri = buildUri(request.getBaseUri(), request.getEndpoint(), request.getQueryParams());
httpPatch = new HttpPatch(uri.toString());
} catch (URISyntaxException ex) {
throw ex;
}
if (request.getHeaders() != null) {
for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
httpPatch.setHeader(entry.getKey(), entry.getValue());
}
}
httpPatch.setEntity(new StringEntity(request.getBody(), Charset.forName("UTF-8")));
writeContentTypeIfNeeded(request, httpPatch);
return executeApiCall(httpPatch);
}
/**
* Make a PUT request and provide the status code, response body and
* response headers.
*
* @param request
* the request object
* @throws URISyntaxException
* in case of a URI syntax error
* @throws IOException
* in case of a network error
* @return the response object
*/
public Response put(Request request) throws URISyntaxException, IOException {
URI uri = null;
HttpPut httpPut = null;
try {
uri = buildUri(request.getBaseUri(), request.getEndpoint(), request.getQueryParams());
httpPut = new HttpPut(uri.toString());
} catch (URISyntaxException ex) {
throw ex;
}
if (request.getHeaders() != null) {
for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
httpPut.setHeader(entry.getKey(), entry.getValue());
}
}
httpPut.setEntity(new StringEntity(request.getBody(), Charset.forName("UTF-8")));
writeContentTypeIfNeeded(request, httpPut);
return executeApiCall(httpPut);
}
/**
* Make a DELETE request and provide the status code and response headers.
*
* @param request
* the request object
* @throws URISyntaxException
* in case of a URI syntax error
* @throws IOException
* in case of a network error
* @return the response object
*/
public Response delete(Request request) throws URISyntaxException, IOException {
URI uri = null;
HttpDeleteWithBody httpDelete = null;
try {
uri = buildUri(request.getBaseUri(), request.getEndpoint(), request.getQueryParams());
httpDelete = new HttpDeleteWithBody(uri.toString());
} catch (URISyntaxException ex) {
throw ex;
}
if (request.getHeaders() != null) {
for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
httpDelete.setHeader(entry.getKey(), entry.getValue());
}
}
httpDelete.setEntity(new StringEntity(request.getBody(), Charset.forName("UTF-8")));
writeContentTypeIfNeeded(request, httpDelete);
return executeApiCall(httpDelete);
}
private void writeContentTypeIfNeeded(Request request, HttpMessage httpMessage) {
if (!"".equals(request.getBody())) {
httpMessage.setHeader("Content-Type", "application/json");
}
}
/**
* Makes a call to the client API.
*
* @param httpPost
* the request method object
* @throws IOException
* in case of a network error
* @return the response object
*/
private Response executeApiCall(HttpRequestBase httpPost) throws IOException {
try {
CloseableHttpResponse serverResponse = httpClient.execute(httpPost);
try {
return getResponse(serverResponse);
} finally {
serverResponse.close();
}
} catch(ClientProtocolException e) {
throw new IOException(e.getMessage());
}
}
/**
* A thin wrapper around the HTTP methods.
*
* @param request
* the request object
* @throws IOException
* in case of a network error
* @return the response object
*/
public Response api(Request request) throws IOException {
try {
if (request.getMethod() == null) {
throw new IOException("We only support GET, PUT, PATCH, POST and DELETE.");
}
switch (request.getMethod()) {
case GET:
return get(request);
case POST:
return post(request);
case PUT:
return put(request);
case PATCH:
return patch(request);
case DELETE:
return delete(request);
default:
throw new IOException("We only support GET, PUT, PATCH, POST and DELETE.");
}
} catch (IOException ex) {
throw ex;
} catch (URISyntaxException ex) {
StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
throw new IOException(errors.toString());
}
}
/**
* Closes the http client.
*
* @throws IOException
* in case of a network error
*/
@Override
public void close() throws IOException {
this.httpClient.close();
}
/**
* Closes and finalizes the http client.
*
* @throws Throwable
* in case of an error
*/
@Override
public void finalize() throws Throwable {
try {
close();
} catch(IOException e) {
throw new Throwable(e.getMessage());
} finally {
super.finalize();
}
}
}