-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathApiClient.java
More file actions
464 lines (393 loc) · 14.4 KB
/
Copy pathApiClient.java
File metadata and controls
464 lines (393 loc) · 14.4 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
456
457
458
459
460
461
462
463
464
package com.bunq.sdk.http;
import com.bunq.sdk.context.ApiContext;
import com.bunq.sdk.context.ApiEnvironmentType;
import com.bunq.sdk.context.BunqContext;
import com.bunq.sdk.context.InstallationContext;
import com.bunq.sdk.exception.ApiException;
import com.bunq.sdk.exception.BunqException;
import com.bunq.sdk.exception.ExceptionFactory;
import com.bunq.sdk.exception.UncaughtExceptionError;
import com.bunq.sdk.json.BunqGsonBuilder;
import com.bunq.sdk.security.SecurityUtils;
import com.google.gson.*;
import okhttp3.*;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
/**
* API Client encapsulates the basic operations for the API, such as HTTP requests to API, setting
* default headers or signing the requests with your API key.
*/
public class ApiClient {
/**
* Error constants.
*/
private static final String ERROR_COULD_NOT_DETERMINE_PINNED_KEY =
"Could not determine pinned key.";
/**
* Endpoints not requiring active session for the request to succeed.
*/
private static final String DEVICE_SERVER_URL = "device-server";
private static final String INSTALLATION_URL = "installation";
private static final String SESSION_SERVER_URL = "session-server";
private static final String PAYMENT_SERVICE_PROVIDER_CREDENTIAL_URL = "payment-service-provider-credential";
private static final List<String> URIS_NOT_REQUIRING_ACTIVE_SESSION = Arrays.asList(
DEVICE_SERVER_URL,
INSTALLATION_URL,
SESSION_SERVER_URL,
PAYMENT_SERVICE_PROVIDER_CREDENTIAL_URL
);
/**
* Field constants.
*/
private static final String FIELD_ERROR = "Error";
private static final String FIELD_ERROR_DESCRIPTION = "error_description";
private static final String SCHEME_HTTPS = "https";
/**
* Time out constants.
*/
private static final int TIMEOUT_SECONDS = 30;
private static final String OK_STATUS_CODE_RANGE = "2[0-9]{2}";
/**
* Response code to use in case the response code is null due to unforeseen circumstances.
*/
private static final int DUMMY_RESPONSE_CODE = 0;
/**
* Private variables.
*/
private final OkHttpClient httpClient;
private final ApiContext apiContext;
/**
* @param apiContext API context to make the calls in.
*/
public ApiClient(ApiContext apiContext) {
this.apiContext = apiContext;
this.httpClient = buildOkHttpClient();
}
/**
*
*/
private OkHttpClient buildOkHttpClient() {
OkHttpClient.Builder clientBuilder;
clientBuilder = new OkHttpClient().newBuilder()
.connectTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.readTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
.writeTimeout(TIMEOUT_SECONDS, TimeUnit.SECONDS);
if (shouldEnableCertificatePinning()) {
clientBuilder.certificatePinner(
determineCertificateToPin(this.apiContext.getEnvironmentType())
);
}
setProxyIfNeeded(clientBuilder);
return clientBuilder.build();
}
/**
*
*/
private void setProxyIfNeeded(OkHttpClient.Builder httpClientBuilder) {
String proxyString = apiContext.getProxy();
if (proxyString != null) {
URL url = Objects.requireNonNull(HttpUrl.parse(proxyString)).url();
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(url.getHost(), url.getPort()));
httpClientBuilder.proxy(proxy);
}
}
/**
*
*/
private boolean shouldEnableCertificatePinning() {
return this.apiContext.getEnvironmentType().getPinnedKey() != null;
}
private static CertificatePinner determineCertificateToPin(ApiEnvironmentType environmentType) {
if (environmentType != null && environmentType.getPinnedKey() != null) {
return new CertificatePinner.Builder()
.add(
environmentType.getBaseUri(),
environmentType.getPinnedKey()
)
.build();
} else {
throw new BunqException(ERROR_COULD_NOT_DETERMINE_PINNED_KEY);
}
}
/**
* Execute a POST request.
*
* @return The raw response of the POST request.
*/
public BunqResponseRaw post(
String uri,
byte[] requestBodyBytes,
Map<String, String> customHeaders
) {
if (customHeaders == null) {
customHeaders = new HashMap<>();
}
BunqRequestBody bunqRequestBody = BunqRequestBody.create(
ContentType.JSON.getMediaType(),
requestBodyBytes
);
if (customHeaders.containsKey(BunqHeader.CONTENT_TYPE.getHeaderName())) {
bunqRequestBody = BunqRequestBody.create(
MediaType.parse(customHeaders.get(BunqHeader.CONTENT_TYPE.getHeaderName())),
requestBodyBytes
);
}
try {
BunqRequestBuilder requestBuilder = new BunqRequestBuilder()
.url(determineFullUri(uri))
.post(bunqRequestBody);
Response response = executeRequest(requestBuilder, customHeaders, uri);
return createBunqResponseRaw(response);
} catch (IOException exception) {
throw new UncaughtExceptionError(exception);
}
}
/**
*
*/
private HttpUrl determineFullUri(String uri) {
return determineFullUri(uri, new HashMap<String, String>());
}
/**
*
*/
private HttpUrl determineFullUri(String uri, Map<String, String> params) {
HttpUrl.Builder urlBuilder = new HttpUrl.Builder()
.scheme(SCHEME_HTTPS)
.host(apiContext.getBaseUri())
.addPathSegment(apiContext.getApiVersion())
.addPathSegments(uri);
SortedMap<String, String> paramsSorted = new TreeMap<>(params);
for (Map.Entry<String, String> param : paramsSorted.entrySet()) {
urlBuilder.addQueryParameter(param.getKey(), param.getValue());
}
return urlBuilder.build();
}
/**
*
*/
private Response executeRequest(
BunqRequestBuilder request,
Map<String, String> customHeaders,
String uri
) throws IOException {
if (!URIS_NOT_REQUIRING_ACTIVE_SESSION.contains(uri) && apiContext.ensureSessionActive()) {
BunqContext.updateApiContext(apiContext);
}
setHeaders(request, customHeaders);
return httpClient.newCall(request.build()).execute();
}
/**
*
*/
private void setHeaders(BunqRequestBuilder requestBuilder, Map<String, String> customHeaders) {
setDefaultHeaders(requestBuilder);
setCustomHeaders(requestBuilder, customHeaders);
setSessionHeaders(requestBuilder);
}
/**
*
*/
private void setDefaultHeaders(BunqRequestBuilder httpEntity) {
BunqHeader.CACHE_CONTROL.addTo(httpEntity);
BunqHeader.USER_AGENT.addTo(httpEntity);
BunqHeader.LANGUAGE.addTo(httpEntity);
BunqHeader.REGION.addTo(httpEntity);
BunqHeader.CLIENT_REQUEST_ID.addTo(httpEntity, UUID.randomUUID().toString());
BunqHeader.GEOLOCATION.addTo(httpEntity);
}
/**
*
*/
private void setCustomHeaders(Request.Builder requestBuilder, Map<String, String> customHeaders) {
for (Map.Entry<String, String> entry : customHeaders.entrySet()) {
requestBuilder.header(entry.getKey(), entry.getValue());
}
}
/**
*
*/
private void setSessionHeaders(BunqRequestBuilder requestBuilder) {
String sessionToken = apiContext.getSessionToken();
if (sessionToken != null) {
BunqHeader.CLIENT_AUTHENTICATION.addTo(requestBuilder, sessionToken);
BunqHeader.CLIENT_SIGNATURE.addTo(requestBuilder, generateSignature(requestBuilder));
}
}
/**
*
*/
private String generateSignature(BunqRequestBuilder requestBuilder) {
return SecurityUtils.generateSignature(requestBuilder,
apiContext.getInstallationContext().getKeyPairClient());
}
/**
*
*/
private BunqResponseRaw createBunqResponseRaw(Response response)
throws IOException {
int responseCode = response.code();
byte[] responseBodyBytes = Objects.requireNonNull(response.body()).bytes();
assertResponseSuccess(responseCode, responseBodyBytes, getResponseId(response));
validateResponseSignature(responseCode, responseBodyBytes, response);
return new BunqResponseRaw(responseBodyBytes, getHeadersMap(response));
}
/**
*
*/
private static String getResponseId(Response response) {
Map<String, String> headerMap = getHeadersMap(response);
return BunqHeader.CLIENT_RESPONSE_ID.getHeaderValueOrDefault(headerMap);
}
/**
*
*/
private static void assertResponseSuccess(Integer responseCode, byte[] responseBodyBytes, String responseId) {
if (responseCode == null) {
responseCode = DUMMY_RESPONSE_CODE;
}
if (!Pattern.matches(OK_STATUS_CODE_RANGE, responseCode.toString())) {
throw createApiExceptionRequestUnsuccessful(responseCode, new String(responseBodyBytes), responseId);
}
}
/**
*
*/
private static ApiException createApiExceptionRequestUnsuccessful(
Integer responseCode,
String responseBody,
String responseId
) {
List<String> allErrorDescription = new ArrayList<>();
try {
allErrorDescription.addAll(fetchAllErrorDescription(responseBody));
} catch (JsonSyntaxException exception) {
allErrorDescription.add(responseBody);
}
return ExceptionFactory.createExceptionForResponse(responseCode, allErrorDescription, responseId);
}
/**
*
*/
private static List<String> fetchAllErrorDescription(String responseBody)
throws JsonSyntaxException {
List<String> errorDescriptions = new ArrayList<>();
GsonBuilder gsonBuilder = BunqGsonBuilder.buildDefault();
JsonObject responseBodyJson = gsonBuilder.create().fromJson(responseBody, JsonObject.class);
if (responseBodyJson.getAsJsonObject().has(FIELD_ERROR)) {
errorDescriptions.addAll(fetchAllErrorDescription(responseBodyJson));
} else {
errorDescriptions.add(responseBody);
}
return errorDescriptions;
}
/**
*
*/
private static List<String> fetchAllErrorDescription(JsonObject responseBodyJson) {
List<String> errorDescriptions = new ArrayList<>();
JsonArray exceptionBodies = responseBodyJson.getAsJsonObject().getAsJsonArray(FIELD_ERROR);
for (JsonElement exceptionBody : exceptionBodies) {
JsonObject exceptionBodyJson = exceptionBody.getAsJsonObject();
errorDescriptions.add(exceptionBodyJson.get(FIELD_ERROR_DESCRIPTION).getAsString());
}
return errorDescriptions;
}
/**
*
*/
private void validateResponseSignature(
int responseCode,
byte[] responseBodyBytes,
Response response
) {
InstallationContext installationContext = apiContext.getInstallationContext();
if (installationContext != null) {
SecurityUtils.validateResponseSignature(responseCode, responseBodyBytes, response,
installationContext.getPublicKeyServer());
}
}
/**
*
*/
protected static Map<String, String> getHeadersMap(Response response) {
HashMap<String, String> headersMap = new HashMap<>();
for (String headerName : response.headers().names()) {
headersMap.put(headerName, response.headers().get(headerName));
}
return headersMap;
}
/**
* Execute a GET request.
*
* @return The raw response of the GET request.
*/
public BunqResponseRaw get(
String uri,
Map<String, String> params,
Map<String, String> customHeaders
) {
if (params == null) {
params = new HashMap<>();
}
if (customHeaders == null) {
customHeaders = new HashMap<>();
}
try {
BunqRequestBuilder requestBuilder = new BunqRequestBuilder()
.get()
.url(determineFullUri(uri, params));
Response response = executeRequest(requestBuilder, customHeaders, uri);
return createBunqResponseRaw(response);
} catch (IOException exception) {
throw new UncaughtExceptionError(exception);
}
}
/**
* Execute a PUT request.
*
* @return The raw response of the PUT request.
*/
public BunqResponseRaw put(
String uri,
byte[] requestBodyBytes,
Map<String, String> customHeaders
) {
if (customHeaders == null) {
customHeaders = new HashMap<>();
}
try {
BunqRequestBuilder requestBuilder = new BunqRequestBuilder()
.put(BunqRequestBody.create(ContentType.JSON.getMediaType(), requestBodyBytes))
.url(determineFullUri(uri));
Response response = executeRequest(requestBuilder, customHeaders, uri);
return createBunqResponseRaw(response);
} catch (IOException exception) {
throw new UncaughtExceptionError(exception);
}
}
/**
* Execute a DELETE request.
*
* @return The response of the DELETE request.
*/
public BunqResponseRaw delete(String uri, Map<String, String> customHeaders) {
if (customHeaders == null) {
customHeaders = new HashMap<>();
}
try {
BunqRequestBuilder requestBuilder = new BunqRequestBuilder()
.delete()
.url(determineFullUri(uri));
Response response = executeRequest(requestBuilder, customHeaders, uri);
return createBunqResponseRaw(response);
} catch (IOException exception) {
throw new UncaughtExceptionError(exception);
}
}
}