-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathRestTool.java
783 lines (659 loc) · 32.9 KB
/
RestTool.java
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
package com.mangopay.core;
import com.google.gson.*;
import com.mangopay.MangoPayApi;
import com.mangopay.core.enumerations.RequestType;
import com.mangopay.entities.RateLimit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
/**
* Class used to build HTTP request, call the request and handle response.
*/
public class RestTool {
// root/parent instance that holds the OAuthToken and Configuration instance
private MangoPayApi root;
// enable/disable debugging
private boolean debugMode;
// variable to flag that in request authentication data are required
private boolean authRequired;
private boolean clientIdRequired;
// array with HTTP header to send with request
private Map<String, String> requestHttpHeaders;
// HTTP communication object
private HttpURLConnection connection;
// request type for current request
private String requestType;
// key-value collection pass in the request
private Map<String, String> requestData;
// code get from response
private int responseCode;
// pagination object
private Pagination pagination;
// slf4j logger facade
private Logger logger;
/**
* Instantiates new RestTool object.
*
* @param root Root/parent instance that holds the OAuthToken and Configuration instance.
* @param authRequired Defines whether request authentication is required.
*/
public RestTool(MangoPayApi root, Boolean authRequired, Boolean clientIdRequired) {
this.root = root;
this.authRequired = authRequired;
this.clientIdRequired = clientIdRequired;
this.debugMode = this.root.getConfig().isDebugMode();
logger = LoggerFactory.getLogger(RestTool.class);
}
/**
* Adds HTTP headers as name/value pairs into the request.
*
* @param httpHeader Collection of headers name/value pairs.
*/
public void addRequestHttpHeader(Map<String, String> httpHeader) {
if (this.requestHttpHeaders == null)
this.requestHttpHeaders = new HashMap<>();
this.requestHttpHeaders.putAll(httpHeader);
}
/**
* Adds HTTP header into the request.
*
* @param key Header name.
* @param value Header value.
*/
public void addRequestHttpHeader(final String key, final String value) {
addRequestHttpHeader(Collections.singletonMap(key, value));
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting single
* <code>Dto</code> instances. In order to process collections of objects,
* use <code>requestList</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term, one of the GET, PUT or POST.
* @param requestData Collection of key-value pairs of request
* parameters.
* @param pagination Pagination object.
* @param entity Instance of Dto class that is going to be
* sent in case of PUTting or POSTing.
* @return The Dto instance returned from API.
* @throws Exception
*/
public <T extends Dto, U extends Dto> T request(Class<T> classOfT, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination, U entity) throws Exception {
return this.request(classOfT, null, urlMethod, requestType, requestData, pagination, entity);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting single
* <code>Dto</code> instances. In order to process collections of objects,
* use <code>requestList</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param idempotencyKey idempotency key for this request.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term, one of the GET, PUT or POST.
* @param requestData Collection of key-value pairs of request
* parameters.
* @param pagination Pagination object.
* @param entity Instance of Dto class that is going to be
* sent in case of PUTting or POSTing.
* @return The Dto instance returned from API.
* @throws Exception
*/
public <T extends Dto, U extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination, U entity) throws Exception {
this.requestType = requestType;
this.requestData = requestData;
return this.doRequest(classOfT, idempotencyKey, urlMethod, pagination, entity);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting single
* <code>Dto</code> instances. In order to process collections of objects,
* use <code>requestList</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term, one of the GET, PUT or POST.
* @return The Dto instance returned from API.
* @throws Exception
*/
public <T extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType) throws Exception {
return request(classOfT, idempotencyKey, urlMethod, requestType, null, null, null);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting single
* <code>Dto</code> instances. In order to process collections of objects,
* use <code>requestList</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term, one of the GET, PUT or POST.
* @param requestData Collection of key-value pairs of request
* parameters.
* @return The Dto instance returned from API.
* @throws Exception
*/
public <T extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType, Map<String, String> requestData) throws Exception {
return request(classOfT, idempotencyKey, urlMethod, requestType, requestData, null, null);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting single
* <code>Dto</code> instances. In order to process collections of objects,
* use <code>requestList</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term, one of the GET, PUT or POST.
* @param requestData Collection of key-value pairs of request
* parameters.
* @param pagination Pagination object.
* @return The Dto instance returned from API.
* @throws Exception
*/
public <T extends Dto> T request(Class<T> classOfT, String idempotencyKey, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination) throws Exception {
return request(classOfT, idempotencyKey, urlMethod, requestType, requestData, pagination, null);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting collections of
* <code>Dto</code> instances. In order to process single objects,
* use <code>request</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param classOfTItem The class of single item in array.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term. For lists should be always GET.
* @param requestData Collection of key-value pairs of request
* parameters.
* @param pagination Pagination object.
* @param additionalUrlParams
* @return The collection of Dto instances returned from API.
* @throws Exception
*/
public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination, Map<String, String> additionalUrlParams) throws Exception {
this.requestType = requestType;
this.requestData = requestData;
return this.doRequestList(classOfT, classOfTItem, urlMethod, pagination, additionalUrlParams);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting collections of
* <code>Dto</code> instances. In order to process single objects,
* use <code>request</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param classOfTItem The class of single item in array.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term. For lists should be always GET.
* @return The collection of Dto instances returned from API.
* @throws Exception
*/
public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType) throws Exception {
return requestList(classOfT, classOfTItem, urlMethod, requestType, null, null, null);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting collections of
* <code>Dto</code> instances. In order to process single objects,
* use <code>request</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param classOfTItem The class of single item in array.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term. For lists should be always GET.
* @param requestData Collection of key-value pairs of request
* parameters.
* @return The collection of Dto instances returned from API.
* @throws Exception
*/
public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType, Map<String, String> requestData) throws Exception {
return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, null, null);
}
/**
* Makes a call to the MangoPay API.
* <p>
* This generic method handles calls targeting collections of
* <code>Dto</code> instances. In order to process single objects,
* use <code>request</code> method instead.
*
* @param <T> Type on behalf of which the request is being called.
* @param classOfT Type on behalf of which the request is being called.
* @param classOfTItem The class of single item in array.
* @param urlMethod Relevant method key.
* @param requestType HTTP request term. For lists should be always GET.
* @param requestData Collection of key-value pairs of request
* parameters.
* @param pagination Pagination object.
* @return The collection of Dto instances returned from API.
* @throws Exception
*/
public <T extends Dto> List<T> requestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, String requestType, Map<String, String> requestData, Pagination pagination) throws Exception {
return requestList(classOfT, classOfTItem, urlMethod, requestType, requestData, pagination, null);
}
private <T extends Dto, U extends Dto> T doRequest(Class<T> classOfT, String idempotencyKey, String urlMethod, Pagination pagination, U entity) throws Exception {
T response = null;
try {
UrlTool urlTool = new UrlTool(root);
String restUrl = urlTool.getRestUrl(urlMethod, this.clientIdRequired, pagination, null);
URL url = new URL(urlTool.getFullUrl(restUrl));
if (this.debugMode) {
logger.info("FullUrl: {}", urlTool.getFullUrl(restUrl));
}
/* FOR WEB DEBUG PURPOSES
SocketAddress addr = new InetSocketAddress("localhost", 8888);
Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
connection = (HttpURLConnection)url.openConnection(proxy);
*/
connection = (HttpURLConnection) url.openConnection();
if (connection instanceof HttpsURLConnection) {
configureSslContext((HttpsURLConnection) connection);
}
// Get connection timeout from config
connection.setConnectTimeout(this.root.getConfig().getConnectTimeout());
// Get read timeout from config
connection.setReadTimeout(this.root.getConfig().getReadTimeout());
// set request method
connection.setRequestMethod(this.requestType);
// set headers
Map<String, String> httpHeaders = this.getHttpHeaders(restUrl);
for (Entry<String, String> entry : httpHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
if (this.debugMode)
logger.info("HTTP Header: {}", entry.getKey() + ": " + entry.getValue());
}
if (idempotencyKey != null && !idempotencyKey.trim().isEmpty()) {
connection.addRequestProperty("Idempotency-Key", idempotencyKey);
}
// prepare to go
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
if (pagination != null) {
this.pagination = pagination;
}
if (this.debugMode)
logger.info("RequestType: {}", this.requestType);
if (this.requestData != null || entity != null || this.requestType.equals(RequestType.POST.toString())) {
String requestBody = "";
if (entity != null) {
requestBody = root.getGson().toJson(entity);
}
if (this.requestData != null) {
String params = "";
for (Entry<String, String> entry : this.requestData.entrySet()) {
params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8"));
}
requestBody = params.replaceFirst("&", "");
}
if (this.debugMode) {
logger.info("RequestData: {}", this.requestData);
logger.info("RequestBody: {}", requestBody);
}
try (OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream(), "UTF-8")) {
osw.write(requestBody);
osw.flush();
}
}
// get response
this.responseCode = connection.getResponseCode();
InputStream is;
if (responseCodeIsSuccessful()) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
checkApiConnection(is);
StringBuffer resp;
try (BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"))) {
String line;
resp = new StringBuffer();
while ((line = rd.readLine()) != null) {
resp.append(line);
}
}
String responseString = resp.toString();
if (this.debugMode) {
if (responseCodeIsSuccessful()) {
logger.info("Response OK: {}", responseString);
} else {
logger.info("Response ERROR: {}", responseString);
}
}
if (responseCodeIsSuccessful() && responseCode != 204) {
this.readResponseHeaders(connection);
// some endpoints return 200 with empty body
if (!responseString.isEmpty()) {
response = castResponseToEntity(classOfT, JsonParser.parseString(responseString).getAsJsonObject());
if (this.debugMode) logger.info("Response object: {}", response.toString());
}
}
this.checkResponseCode(responseString);
} catch (Exception ex) {
//ex.printStackTrace();
if (this.debugMode) logger.error("EXCEPTION: {}", Arrays.toString(ex.getStackTrace()));
throw ex;
}
return response;
}
private void configureSslContext(HttpsURLConnection connection) throws KeyManagementException, NoSuchAlgorithmException {
connection.setSSLSocketFactory(getSSLContext().getSocketFactory());
}
private SSLContext getSSLContext() throws NoSuchAlgorithmException, KeyManagementException {
SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
sslContext.init(null, null, new SecureRandom());
return sslContext;
}
private void readResponseHeaders(HttpURLConnection conn) {
List<RateLimit> updatedRateLimits = null;
for (Map.Entry<String, List<String>> k : conn.getHeaderFields().entrySet()) {
for (String v : k.getValue()) {
if (this.debugMode) logger.info("Response header: {}", k.getKey() + ":" + v);
if (k.getKey() == null) continue;
if (k.getKey().equals("X-RateLimit-Remaining") || k.getKey().equals("X-RateLimit-Remaining".toLowerCase())) {
if (updatedRateLimits == null) {
updatedRateLimits = initRateLimits();
}
List<String> callsRemaining = k.getValue();
updatedRateLimits.get(0).setCallsRemaining(Integer.valueOf(callsRemaining.get(3)));
updatedRateLimits.get(1).setCallsRemaining(Integer.valueOf(callsRemaining.get(2)));
updatedRateLimits.get(2).setCallsRemaining(Integer.valueOf(callsRemaining.get(1)));
updatedRateLimits.get(3).setCallsRemaining(Integer.valueOf(callsRemaining.get(0)));
}
if (k.getKey().equals("X-RateLimit") || k.getKey().equals("X-RateLimit".toLowerCase())) {
if (updatedRateLimits == null) {
updatedRateLimits = initRateLimits();
}
List<String> callsMade = k.getValue();
updatedRateLimits.get(0).setCallsMade(Integer.valueOf(callsMade.get(3)));
updatedRateLimits.get(1).setCallsMade(Integer.valueOf(callsMade.get(2)));
updatedRateLimits.get(2).setCallsMade(Integer.valueOf(callsMade.get(1)));
updatedRateLimits.get(3).setCallsMade(Integer.valueOf(callsMade.get(0)));
}
if (k.getKey().equals("X-RateLimit-Reset") || k.getKey().equals("X-RateLimit-Reset".toLowerCase())) {
if (updatedRateLimits == null) {
updatedRateLimits = initRateLimits();
}
List<String> resetTimes = k.getValue();
updatedRateLimits.get(0).setResetTimeSeconds(Long.valueOf(resetTimes.get(3)));
updatedRateLimits.get(1).setResetTimeSeconds(Long.valueOf(resetTimes.get(2)));
updatedRateLimits.get(2).setResetTimeSeconds(Long.valueOf(resetTimes.get(1)));
updatedRateLimits.get(3).setResetTimeSeconds(Long.valueOf(resetTimes.get(0)));
}
if (k.getKey().equals("X-Number-Of-Pages") || k.getKey().equals("X-Number-Of-Pages".toLowerCase())) {
this.pagination.setTotalPages(Integer.parseInt(v));
}
if (k.getKey().equals("X-Number-Of-Items") || k.getKey().equals("X-Number-Of-Items".toLowerCase())) {
this.pagination.setTotalItems(Integer.parseInt(v));
}
if (k.getKey().equals("Link") || k.getKey().equals("Link".toLowerCase())) {
String linkValue = v;
String[] links = linkValue.split(",");
if (links != null && links.length > 0) {
for (String link : links) {
link = link.replaceAll(Matcher.quoteReplacement("<\""), "");
link = link.replaceAll(Matcher.quoteReplacement("\">"), "");
link = link.replaceAll(Matcher.quoteReplacement(" rel=\""), "");
link = link.replaceAll(Matcher.quoteReplacement("\""), "");
String[] oneLink = link.split(";");
if (oneLink != null && oneLink.length > 1) {
if (oneLink[0] != null && oneLink[1] != null) {
this.pagination.setLinks(oneLink);
}
}
}
}
}
}
}
if (updatedRateLimits != null) {
root.setRateLimits(updatedRateLimits);
}
}
private List<RateLimit> initRateLimits() {
return Arrays.asList(
new RateLimit(15),
new RateLimit(30),
new RateLimit(60),
new RateLimit(24 * 60));
}
public <T> T castResponseToEntity(Class<T> classOfT, JsonObject response) {
return root.getGson().fromJson(response, classOfT);
}
private <T extends Dto> List<T> doRequestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, Pagination pagination) throws Exception {
return doRequestList(classOfT, classOfTItem, urlMethod, pagination, null);
}
private <T extends Dto> List<T> doRequestList(Class<T[]> classOfT, Class<T> classOfTItem, String urlMethod, Pagination pagination, Map<String, String> additionalUrlParams) throws Exception {
List<T> response = new ArrayList<>();
try {
UrlTool urlTool = new UrlTool(root);
String restUrl = urlTool.getRestUrl(urlMethod, this.clientIdRequired, pagination, additionalUrlParams);
URL url = new URL(urlTool.getFullUrl(restUrl));
if (this.debugMode)
logger.info("FullUrl: {}", urlTool.getFullUrl(restUrl));
connection = (HttpURLConnection) url.openConnection();
if (connection instanceof HttpsURLConnection) {
configureSslContext((HttpsURLConnection) connection);
}
// set request method
connection.setRequestMethod(this.requestType);
// set headers
Map<String, String> httpHeaders = this.getHttpHeaders(restUrl);
for (Entry<String, String> entry : httpHeaders.entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
if (this.debugMode)
logger.info("HTTP Header: {}", entry.getKey() + ": " + entry.getValue());
}
// prepare to go
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
if (pagination != null) {
this.pagination = pagination;
}
if (this.debugMode)
logger.info("RequestType: {}", this.requestType);
if (this.requestData != null) {
String requestBody;
String params = "";
for (Entry<String, String> entry : this.requestData.entrySet()) {
params += String.format("&%s=%s", URLEncoder.encode(entry.getKey(), "UTF-8"), URLEncoder.encode(entry.getValue(), "UTF-8"));
}
requestBody = params.replaceFirst("&", "");
writeRequestBody(connection, requestBody);
if (this.debugMode) {
logger.info("RequestData: {}", this.requestData);
logger.info("RequestBody: {}", requestBody);
}
} else if (restUrl.contains("consult")
&& (restUrl.contains("KYC/documents") || restUrl.contains("dispute-documents"))) {
writeRequestBody(connection, "");
}
//Get Response
this.responseCode = connection.getResponseCode();
InputStream is;
if (responseCodeIsSuccessful()) {
is = connection.getInputStream();
} else {
is = connection.getErrorStream();
}
checkApiConnection(is);
StringBuffer resp;
try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) {
String line;
resp = new StringBuffer();
while ((line = rd.readLine()) != null) {
resp.append(line);
resp.append('\r');
}
}
String responseString = resp.toString();
if (this.debugMode) {
if (responseCodeIsSuccessful()) {
logger.info("Response OK: {}", responseString);
} else {
logger.info("Response ERROR: {}", responseString);
}
}
if (responseCodeIsSuccessful() && responseCode != 204) {
this.readResponseHeaders(connection);
// some endpoints return 200 with empty body
if (!responseString.isEmpty()) {
JsonArray ja = JsonParser.parseString(responseString).getAsJsonArray();
for (int x = 0; x < ja.size(); x++) {
JsonObject jo = ja.get(x).getAsJsonObject();
T toAdd = castResponseToEntity(classOfTItem, jo);
response.add(toAdd);
}
if (this.debugMode) {
logger.info("Response object: {}", response.toString());
logger.info("Elements count: {}", response.size());
}
}
}
this.checkResponseCode(responseString);
} catch (Exception ex) {
if (this.debugMode) logger.error("EXCEPTION: {}", Arrays.toString(ex.getStackTrace()));
throw ex;
}
return response;
}
private void writeRequestBody(HttpURLConnection connection, String body) throws IOException {
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(body);
wr.flush();
}
}
/**
* Gets HTTP header to use in request.
*
* @param restUrl The REST API URL.
* @return Array containing HTTP headers.
*/
private Map<String, String> getHttpHeaders(String restUrl) throws Exception {
// return if already created...
if (this.requestHttpHeaders != null)
return this.requestHttpHeaders;
// ...or initialize with default headers
Map<String, String> httpHeaders = new HashMap<>();
// content type
httpHeaders.put("Content-Type", "application/json");
// AuthenticationHelper http header
if (this.authRequired) {
AuthenticationHelper authHlp = new AuthenticationHelper(root);
httpHeaders.putAll(authHlp.getHttpHeaderKey());
}
httpHeaders.put("User-Agent", String.format("MangoPay V2 SDK Java %s", root.getConfig().getVersion()));
if(this.root.getConfig().isUkHeaderFlag()) {
httpHeaders.put("x-tenant-id", "uk");
}
return httpHeaders;
}
private void checkApiConnection(InputStream is) throws ResponseException {
if (is == null) {
ResponseException responseException = new ResponseException("Connection to Mangopay API failed");
responseException.setResponseHttpCode(500);
responseException.setResponseHttpDescription("Internal Server Error");
responseException.setApiMessage("Connection to Mangopay API failed");
throw responseException;
}
}
/**
* Checks the HTTP response code and if it's not successful throws a ResponseException.
*
* @param message Text response.
* @throws ResponseException If response code is not successful
*/
private void checkResponseCode(String message) throws ResponseException {
if (!responseCodeIsSuccessful()) {
HashMap<Integer, String> responseCodes = new HashMap<Integer, String>() {{
put(400, "Bad request");
put(401, "Unauthorized");
put(403, "Prohibition to use the method");
put(404, "Not found");
put(405, "Method not allowed");
put(413, "Request entity too large");
put(422, "Unprocessable entity");
put(500, "Internal server error");
put(501, "Not implemented");
}};
ResponseException responseException = new ResponseException(message);
responseException.setResponseHttpCode(this.responseCode);
if (responseCodes.containsKey(this.responseCode)) {
responseException.setResponseHttpDescription(responseCodes.get(this.responseCode));
} else {
responseException.setResponseHttpDescription("Unknown response error");
}
if (message != null) {
try {
JsonObject error = JsonParser.parseString(message).getAsJsonObject();
for (Entry<String, JsonElement> entry : error.entrySet()) {
switch (entry.getKey().toLowerCase()) {
case "message":
responseException.setApiMessage(entry.getValue().getAsString());
break;
case "type":
responseException.setType(entry.getValue().getAsString());
break;
case "id":
responseException.setId(entry.getValue().getAsString());
break;
case "date":
responseException.setDate((int) entry.getValue().getAsDouble());
break;
case "errors":
if (entry.getValue() == null) break;
if (entry.getValue().isJsonNull()) break;
for (Entry<String, JsonElement> errorEntry : entry.getValue().getAsJsonObject().entrySet()) {
if (!responseException.getErrors().containsKey(errorEntry.getKey()))
responseException.getErrors().put(errorEntry.getKey(), errorEntry.getValue().getAsString());
else {
String description = responseException.getErrors().get(errorEntry.getKey());
description = " | " + errorEntry.getValue().getAsString();
responseException.getErrors().put(errorEntry.getKey(), description);
}
}
break;
}
}
} catch (IllegalStateException | JsonSyntaxException ex) {
responseException.setType("Resource not found");
responseException.setApiMessage("API Endpoint not found");
}
}
throw responseException;
}
}
private boolean responseCodeIsSuccessful() {
return responseCode >= 200 && responseCode < 300;
}
}