-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathRestClient.java
More file actions
522 lines (438 loc) · 16.8 KB
/
RestClient.java
File metadata and controls
522 lines (438 loc) · 16.8 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
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
package com.telesign;
import com.google.gson.JsonObject;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import okhttp3.Authenticator;
import okhttp3.Credentials;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.Route;
import okio.Buffer;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.Proxy;
import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.TimeZone;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
/**
* The TeleSign RestClient is a generic HTTP REST client that can be extended to
* make requests against any of TeleSign's REST API endpoints.
* <p>
* See https://developer.telesign.com for detailed API documentation.
*/
public class RestClient {
private static final String sdkVersion = RestClient.class.getPackage().getImplementationVersion();
public static final String URL_FORM_ENCODED_CONTENT_TYPE = "application/x-www-form-urlencoded";
public static final String JSON_CONTENT_TYPE = "application/json";
public static final String AUTH_BASIC = "Basic";
protected String customerId;
protected String apiKey;
private String restEndpoint;
private OkHttpClient client;
private String userAgent;
public RestClient(String customerId, String apiKey) {
this(customerId, apiKey, null, null, null, null, null, null, null, null, null, null);
}
public RestClient(String customerId, String apiKey, String restEndpoint) {
this(customerId, apiKey, restEndpoint, null, null, null, null, null, null, null, null, null);
}
public RestClient(String customerId, String apiKey, String restEndpoint, String source, String sdkVersionOrigin, String sdkVersionDependency) {
this(customerId, apiKey, restEndpoint, null, null, null, null, null, null, source, sdkVersionOrigin, sdkVersionDependency);
}
/**
* TeleSign RestClient useful for making generic RESTful requests against our
* API.
*
* @param customerId
* Your customer_id string associated with your account.
* @param apiKey
* Your api_key string associated with your account.
* @param restEndpoint
* (optional) Override the default restEndpoint to target another
* endpoint.
* @param connectTimeout
* (optional) connectTimeout passed into OkHttp.
* @param readTimeout
* (optional) readTimeout passed into OkHttp.
* @param writeTimeout
* (optional) writeTimeout passed into OkHttp.
* @param proxy
* (optional) proxy passed into OkHttp.
* @param proxyUsername
* (optional) proxyUserName used to create an Authenticator passed
* into OkHttp.
* @param proxyPassword
* (optional) proxyPassword used to create an Authenticator passed
* into OkHttp.
*/
public RestClient(String customerId, String apiKey, String restEndpoint, Integer connectTimeout,
Integer readTimeout, Integer writeTimeout, Proxy proxy, final String proxyUsername,
final String proxyPassword, final String source, final String sdkVersionOrigin, final String sdkVersionDependency) {
this.customerId = customerId;
this.apiKey = apiKey;
this.userAgent = String.format("TeleSignSDK/java Java/%s OkHttp/%s OriginatingSDK/%s SDKVersion/%s",
System.getProperty("java.version"), OkHttp.VERSION, (source == null ? "java_telesign" : source), (sdkVersionOrigin == null ? sdkVersion : sdkVersionOrigin));
if (!Objects.equals(source, "java_telesign") && sdkVersionDependency != null)
this.userAgent += String.format(" DependencySDKVersion/%s", sdkVersionDependency);
if (restEndpoint == null) {
this.restEndpoint = "https://rest-api.telesign.com";
} else {
this.restEndpoint = restEndpoint;
}
if (connectTimeout == null) {
connectTimeout = 10;
}
if (readTimeout == null) {
readTimeout = 10;
}
if (writeTimeout == null) {
writeTimeout = 10;
}
OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder()
.connectTimeout(connectTimeout, TimeUnit.SECONDS).readTimeout(readTimeout, TimeUnit.SECONDS)
.writeTimeout(writeTimeout, TimeUnit.SECONDS);
if (proxy != null) {
okHttpClientBuilder.proxy(proxy);
if (proxyUsername != null && proxyPassword != null) {
Authenticator proxyAuthenticator = new Authenticator() {
public Request authenticate(Route route, Response response) throws IOException {
String credential = Credentials.basic(proxyUsername, proxyPassword);
return response.request().newBuilder().header("Proxy-Authorization", credential).build();
}
};
okHttpClientBuilder.proxyAuthenticator(proxyAuthenticator);
}
}
this.client = okHttpClientBuilder.build();
}
static byte[] parseBase64(String encoded) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encoded.length(); i++) {
char ch = encoded.charAt(i);
if (
(ch >= 'A' && ch <= 'Z') ||
(ch >= 'a' && ch <= 'z') ||
(ch >= '0' && ch <= '9') ||
(ch == '+') ||
(ch == '/')
) {
sb.append(ch);
}
}
return Base64.getDecoder().decode(sb.toString());
}
static String encodeBase64(byte[] data) {
return Base64.getEncoder().encodeToString(data);
}
/**
* A simple HTTP Response object to abstract the underlying OkHttp library
* response.
*/
public static class TelesignResponse {
public int statusCode;
public Map<String, List<String>> headers;
public String body;
public boolean ok;
public JsonObject json;
public TelesignResponse(Response okHttpResponse) {
this.statusCode = okHttpResponse.code();
this.headers = okHttpResponse.headers().toMultimap();
this.ok = okHttpResponse.isSuccessful();
try {
this.body = okHttpResponse.body().string();
try {
this.json = new JsonParser().parse(body).getAsJsonObject();
} catch (JsonParseException | IllegalStateException e) {
this.json = new JsonObject();
}
} catch (IOException e) {
this.body = "";
this.json = new JsonObject();
}
}
}
/**
* Generates the TeleSign REST API headers used to authenticate requests.
* <p>
* Creates the canonicalized stringToSign and generates the HMAC signature. This
* is used to authenticate requests against the TeleSign REST API.
* <p>
* See https://developer.telesign.com/docs/authentication for detailed API
* documentation.
*
* @param customerId
* Your account customer_id.
* @param apiKey
* Your account api_key.
* @param methodName
* The HTTP method name of the request as a upper case string, should
* be one of 'POST', 'GET', 'PUT' or 'DELETE'.
* @param resource
* The partial resource URI to perform the request against.
* @param requestParams
* URL encoded HTTP body to perform the HTTP request with.
* @param dateRfc2616
* (optional) The date and time of the request formatted in rfc 2616.
* @param nonce
* (optional) A unique cryptographic nonce for the request.
* @param userAgent
* (optional) User Agent associated with the request.
*
* @param contentType
* (optional) will be sent only if post or put method is requested
* @return Map of HTTP headers to be applied to the request.
*/
public static Map<String, String> generateTelesignHeaders(String customerId, String apiKey,
String methodName, String resource, String requestParams,
String dateRfc2616, String nonce, String userAgent, String contentType, String authMethod) throws NoSuchAlgorithmException, InvalidKeyException {
if (dateRfc2616 == null) {
SimpleDateFormat rfc2616 = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
rfc2616.setTimeZone(TimeZone.getTimeZone("GMT"));
dateRfc2616 = rfc2616.format(new Date());
}
if (nonce == null) {
nonce = UUID.randomUUID().toString();
}
if ((!methodName.equals("POST") & !methodName.equals("PUT")) || contentType == null) {
contentType = "";
}
String authorization = "";
Map<String, String> headers = new HashMap<>();
if (Objects.equals(authMethod, "Basic")) {
String credentials = customerId + ":" + apiKey;
String encodedCredentials = Base64.getEncoder().encodeToString(credentials.getBytes());
authorization = authMethod + " " + encodedCredentials;
} else {
StringBuilder stringToSignBuilder = new StringBuilder();
stringToSignBuilder.append(String.format("%s", methodName));
stringToSignBuilder.append(String.format("\n%s", contentType));
stringToSignBuilder.append(String.format("\n%s", dateRfc2616));
stringToSignBuilder.append(String.format("\nx-ts-auth-method:%s", "HMAC-SHA256"));
stringToSignBuilder.append(String.format("\nx-ts-nonce:%s", nonce));
if (!contentType.isEmpty() && !requestParams.isEmpty()) {
stringToSignBuilder.append(String.format("\n%s", requestParams));
}
stringToSignBuilder.append(String.format("\n%s", resource));
String stringToSign = stringToSignBuilder.toString();
String signature;
Mac sha256HMAC = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(parseBase64(apiKey), "HmacSHA256");
sha256HMAC.init(secretKeySpec);
signature = encodeBase64(sha256HMAC.doFinal(stringToSign.getBytes()));
authorization = String.format("TSA %s:%s", customerId, signature);
headers.put("Date", dateRfc2616);
headers.put("Content-Type", contentType);
headers.put("x-ts-auth-method", authMethod);
headers.put("x-ts-nonce", nonce);
}
headers.put("Authorization", authorization);
if (userAgent != null) {
headers.put("User-Agent", userAgent);
}
return headers;
}
/**
* Generic TeleSign REST API POST handler.
*
* @param resource
* The partial resource URI to perform the request against.
* @param params
* Params to perform the POST request with.
* @return The TelesignResponse for the request.
*/
public TelesignResponse post(String resource, Map<String, ? extends Object> params)
throws IOException, GeneralSecurityException {
return this.execute("POST", resource, params, URL_FORM_ENCODED_CONTENT_TYPE, null);
}
/**
* Generic TeleSign REST API POST handler.
*
* @param resource
* The partial resource URI to perform the request against.
* @param params
* Params to perform the POST request with.
* @return The TelesignResponse for the request.
*/
public TelesignResponse post(String resource, Map<String, ? extends Object> params, String contentType)
throws IOException, GeneralSecurityException {
return this.execute("POST", resource, params, contentType, null);
}
/**
* Generic TeleSign REST API POST handler.
*
* @param resource
* The partial resource URI to perform the request against.
* @param params
* Params to perform the POST request with.
* @param contentType
* Appication/json, www-url ....
* @param authMethod
* Basic, Diggest ...
* @return The TelesignResponse for the request.
*/
public TelesignResponse post(String resource, Map<String, ? extends Object> params, String contentType, String authMethod)
throws IOException, GeneralSecurityException {
return this.execute("POST", resource, params, contentType, authMethod);
}
/**
* Generic TeleSign REST API GET handler.
*
* @param resource
* The partial resource URI to perform the request against.
* @param params
* Params to perform the GET request with.
* @return The TelesignResponse for the request.
*/
public TelesignResponse get(String resource, Map<String, String> params)
throws IOException, GeneralSecurityException {
return this.execute("GET", resource, params);
}
/**
* Generic TeleSign REST API PUT handler.
*
* @param resource
* The partial resource URI to perform the request against.
* @param params
* Params to perform the PUT request with.
* @return The TelesignResponse for the request.
*/
public TelesignResponse put(String resource, Map<String, String> params)
throws IOException, GeneralSecurityException {
return this.execute("PUT", resource, params, URL_FORM_ENCODED_CONTENT_TYPE, null);
}
/**
* Generic TeleSign REST API PATCH handler.
*
* @param resource
* The partial resource URI to perform the request against.
* @param params
* Params to perform the PATCH request with.
* @param contentType
* Appication/json, www-url ....
* @param authMethod
* Basic, Digest ...
* @return The TelesignResponse for the request.
*/
public TelesignResponse patch(String resource, Map<String, String> params, String contentType, String authMethod)
throws IOException, GeneralSecurityException {
return this.execute("PATCH", resource, params, contentType, authMethod);
}
/**
* Generic TeleSign REST API DELETE handler.
*
* @param resource
* The partial resource URI to perform the request against.
* @param params
* Params to perform the DELETE request with.
* @return The TelesignResponse for the request.
*/
public TelesignResponse delete(String resource, Map<String, String> params)
throws IOException, GeneralSecurityException {
return this.execute("DELETE", resource, params);
}
/**
* Generic TeleSign REST API request handler.
*
* @param params
* Params to perform the request with.
* @return The RequestBody for the request.
* @throws IOException
*/
public RequestBody createRequestBody(Map<String, ? extends Object> params, String contentType) throws IOException {
if (Objects.equals(contentType, "application/json")) {
Gson gson = new Gson();
String json = gson.toJson(params);
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, json.getBytes());
return body;
} else {
FormBody.Builder formBodyBuilder = new FormBody.Builder();
for (Map.Entry<String, ? extends Object> entry : params.entrySet()) {
formBodyBuilder.add(entry.getKey(), (String) entry.getValue());
}
FormBody formBody = formBodyBuilder.build();
return formBody;
}
}
/**
* Generic TeleSign method for request execution,
*
* @param methodName
* @param resource
* @param params
* @return The TelesignResponse for the request
* @throws IOException
* @throws GeneralSecurityException
*/
private TelesignResponse execute(String methodName, String resource, Map<String, ? extends Object> params)
throws IOException, GeneralSecurityException {
return execute(methodName, resource, params, "", null);
}
/**
* Generic TeleSign method for request execution,
*
* @param methodName
* @param resource
* @param params
* @return The TelesignResponse for the request
* @throws IOException
* @throws GeneralSecurityException
*/
private TelesignResponse execute(String methodName, String resource, Map<String, ? extends Object> params, String contentType, String authMethod)
throws IOException, GeneralSecurityException {
if (authMethod == null) {
authMethod = "HMAC-SHA256";
}
if (params == null) {
params = new HashMap<>();
}
HttpUrl httpUrl = HttpUrl.parse(String.format("%s%s", this.restEndpoint, resource));
RequestBody requestBody = null;
String requestParams = "";
if (methodName.equals("POST") || methodName.equals("PUT") || methodName.equals("PATCH")) {
requestBody = this.createRequestBody(params, contentType);
if (requestBody != null) {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
requestParams = buffer.readUtf8();
}
} else {
HttpUrl.Builder httpUrlBuilder = httpUrl.newBuilder();
for (Map.Entry<String, ? extends Object> entry : params.entrySet()) {
httpUrlBuilder.addQueryParameter(entry.getKey(), (String) entry.getValue());
}
httpUrl = httpUrlBuilder.build();
}
Map<String, String> headers = RestClient.generateTelesignHeaders(this.customerId, this.apiKey,
methodName, resource, requestParams, null, null, this.userAgent, contentType, authMethod);
Request.Builder requestBuilder = new Request.Builder().url(httpUrl).method(methodName, requestBody);
for (Map.Entry<String, String> entry : headers.entrySet()) {
requestBuilder.addHeader(entry.getKey(), entry.getValue());
}
Request request = requestBuilder.build();
TelesignResponse telesignResponse;
try (Response okhttpResponse = this.client.newCall(request).execute()) {
telesignResponse = new TelesignResponse(okhttpResponse);
}
return telesignResponse;
}
}