-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathWebServiceClient.java
More file actions
584 lines (533 loc) · 23.3 KB
/
Copy pathWebServiceClient.java
File metadata and controls
584 lines (533 loc) · 23.3 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
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
package com.maxmind.minfraud;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.InjectableValues;
import com.fasterxml.jackson.databind.InjectableValues.Std;
import com.maxmind.minfraud.exception.AuthenticationException;
import com.maxmind.minfraud.exception.HttpException;
import com.maxmind.minfraud.exception.InsufficientFundsException;
import com.maxmind.minfraud.exception.InvalidRequestException;
import com.maxmind.minfraud.exception.MinFraudException;
import com.maxmind.minfraud.exception.PermissionRequiredException;
import com.maxmind.minfraud.request.Transaction;
import com.maxmind.minfraud.request.TransactionReport;
import com.maxmind.minfraud.response.FactorsResponse;
import com.maxmind.minfraud.response.InsightsResponse;
import com.maxmind.minfraud.response.ScoreResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.ProxySelector;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpTimeoutException;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
/**
* Client for MaxMind minFraud Score, Insights, and Factors
*/
public final class WebServiceClient {
private static final String pathBase = "/minfraud/v2.0/";
private static final String userAgent = "minFraud-API/"
+ WebServiceClient.class.getPackage().getImplementationVersion()
+ " Java/" + System.getProperty("java.version");
private final String authHeader;
private final String host;
private final int port;
private final boolean useHttps;
private final List<String> locales;
private final Duration requestTimeout;
private final int maxRetries;
private final HttpClient httpClient;
private WebServiceClient(WebServiceClient.Builder builder) {
host = builder.host;
port = builder.port;
useHttps = builder.useHttps;
locales = builder.locales;
// HttpClient supports basic auth, but it will only send it after the
// server responds with an unauthorized. As such, we just make the
// Authorization header ourselves.
authHeader = "Basic "
+ Base64.getEncoder()
.encodeToString((builder.accountId + ":" + builder.licenseKey)
.getBytes(StandardCharsets.UTF_8));
requestTimeout = builder.requestTimeout;
maxRetries = builder.maxRetries;
if (builder.httpClient != null) {
httpClient = builder.httpClient;
} else {
HttpClient.Builder httpClientBuilder = HttpClient.newBuilder()
.proxy(builder.proxy);
if (builder.connectTimeout != null) {
httpClientBuilder.connectTimeout(builder.connectTimeout);
}
httpClient = httpClientBuilder.build();
}
}
/**
* <p>
* {@code Builder} creates instances of {@code WebServiceClient} from values set by the
* methods.
* </p>
* <p>
* This example shows how to create a {@code WebServiceClient} object with the {@code Builder}:
* </p>
* <p>
* WebServiceClient client = new WebServiceClient.Builder(12,"licensekey").host
* ("geoip.maxmind.com").build();
* </p>
* <p>
* Only the values set in the {@code Builder} constructor are required.
* </p>
*/
public static final class Builder {
final int accountId;
final String licenseKey;
String host = "minfraud.maxmind.com";
int port = 443;
boolean useHttps = true;
Duration connectTimeout;
Duration requestTimeout;
List<String> locales = List.of("en");
private ProxySelector proxy;
private HttpClient httpClient;
private int maxRetries = 1;
/**
* @param accountId Your MaxMind account ID.
* @param licenseKey Your MaxMind license key.
*/
public Builder(int accountId, String licenseKey) {
this.accountId = accountId;
this.licenseKey = licenseKey;
}
/**
* @param val Timeout duration to establish a connection to the web service. There is no
* timeout by default.
* @return Builder object
* @apiNote See {@link #maxRetries(int)} for how this timeout interacts with retries.
*/
public WebServiceClient.Builder connectTimeout(Duration val) {
connectTimeout = val;
return this;
}
/**
* Disables HTTPS to connect to a test server or proxy. The minFraud ScoreResponse and
* InsightsResponse web services require HTTPS.
*
* @return Builder object
*/
public WebServiceClient.Builder disableHttps() {
useHttps = false;
return this;
}
/**
* @param val The host to use. By default, the client connects to the production host.
* However, during testing and development, you can set this option to
* 'sandbox.maxmind.com' to use the Sandbox environment's host. The sandbox
* allows you to experiment with the API without affecting your production data.
* @return Builder object
*/
public WebServiceClient.Builder host(String val) {
host = val;
return this;
}
/**
* @param val The port to use.
* @return Builder object
*/
public WebServiceClient.Builder port(int val) {
port = val;
return this;
}
/**
* @param val List of locale codes to use in name property from most preferred to least
* preferred.
* @return Builder object
*/
public WebServiceClient.Builder locales(List<String> val) {
if (locales == null) {
throw new IllegalArgumentException("locales must not be null");
}
locales = List.copyOf(val);
return this;
}
/**
* @param val Request timeout duration. There is no timeout by default.
* @return Builder object
* @apiNote See {@link #maxRetries(int)} for how this timeout interacts with retries.
*/
public Builder requestTimeout(Duration val) {
requestTimeout = val;
return this;
}
/**
* @param val the proxy to use when making this request.
* @return Builder object
*/
public Builder proxy(ProxySelector val) {
proxy = val;
return this;
}
/**
* @param val the HttpClient to use when making requests. When provided,
* connectTimeout and proxy settings will be ignored as the
* custom client should handle these configurations.
* <p>
* The SDK applies its own transport-failure retry on top of any supplied
* client; customers can disable it via {@link #maxRetries(int)} with
* {@code .maxRetries(0)}.
* @return Builder object
*/
public Builder httpClient(HttpClient val) {
httpClient = val;
return this;
}
/**
* @param val Maximum number of retries on transport-level failures
* (connection reset, broken pipe, EOF, ...).
* Applies uniformly to all endpoints. Defaults to 1.
* Set to 0 to disable.
* @return Builder.
* @throws IllegalArgumentException if {@code val} is negative.
* @apiNote Retries fire only on transient transport failures.
* Timeouts and other non-transient errors are not retried — see
* the README for the complete list. When all attempts fail,
* the prior {@code IOException}s are attached via
* {@link Throwable#getSuppressed()} for debugging.
*/
public Builder maxRetries(int val) {
if (val < 0) {
throw new IllegalArgumentException("maxRetries must not be negative");
}
maxRetries = val;
return this;
}
/**
* @return an instance of {@code WebServiceClient} created from the fields set on this
* builder.
*/
public WebServiceClient build() {
if (httpClient != null) {
if (connectTimeout != null) {
throw new IllegalArgumentException(
"Cannot set both httpClient and connectTimeout. "
+ "Configure timeouts on the provided HttpClient instead.");
}
if (proxy != null) {
throw new IllegalArgumentException(
"Cannot set both httpClient and proxy. "
+ "Configure proxy on the provided HttpClient instead.");
}
} else {
if (proxy == null) {
proxy = ProxySelector.getDefault();
}
}
return new WebServiceClient(this);
}
}
/**
* Make a minFraud Factors request to the web service using the transaction request object
* passed to the method.
*
* @param transaction A transaction request object.
* @return An Factors model object
* @throws InsufficientFundsException when there are insufficient funds on the account.
* @throws AuthenticationException when there is a problem authenticating.
* @throws InvalidRequestException when the request is invalid for some other reason.
* @throws PermissionRequiredException when permission is required to use the service.
* @throws MinFraudException when the web service returns unexpected content.
* @throws HttpException when the web service returns an unexpected response.
* @throws IOException when some other IO error occurs.
*/
public FactorsResponse factors(Transaction transaction) throws IOException,
MinFraudException, InsufficientFundsException, InvalidRequestException,
AuthenticationException, PermissionRequiredException, HttpException {
return responseFor("factors", transaction, FactorsResponse.class);
}
/**
* Make a minFraud Insights request to the web service using the transaction request object
* passed to the method.
*
* @param transaction A transaction request object.
* @return An Insights model object
* @throws InsufficientFundsException when there are insufficient funds on the account.
* @throws AuthenticationException when there is a problem authenticating.
* @throws InvalidRequestException when the request is invalid for some other reason.
* @throws PermissionRequiredException when permission is required to use the service.
* @throws MinFraudException when the web service returns unexpected content.
* @throws HttpException when the web service returns an unexpected response.
* @throws IOException when some other IO error occurs.
*/
public InsightsResponse insights(Transaction transaction) throws IOException,
MinFraudException, InsufficientFundsException, InvalidRequestException,
AuthenticationException, PermissionRequiredException, HttpException {
return responseFor("insights", transaction, InsightsResponse.class);
}
/**
* Make a minFraud Score request to the web service using the transaction request object passed
* to the method.
*
* @param transaction A transaction request object.
* @return An Score model object
* @throws InsufficientFundsException when there are insufficient funds on the account.
* @throws AuthenticationException when there is a problem authenticating.
* @throws InvalidRequestException when the request is invalid for some other reason.
* @throws PermissionRequiredException when permission is required to use the service.
* @throws MinFraudException when the web service returns unexpected content.
* @throws HttpException when the web service returns an unexpected response.
* @throws IOException when some other IO error occurs.
*/
public ScoreResponse score(Transaction transaction) throws IOException,
MinFraudException, InsufficientFundsException, InvalidRequestException,
AuthenticationException, PermissionRequiredException, HttpException {
return responseFor("score", transaction, ScoreResponse.class);
}
/**
* Make a Report Transaction request to the web service using the TransactionReport request
* object passed to the method.
*
* @param transaction A TransactionReport request object.
* @throws InsufficientFundsException when there are insufficient funds on the account.
* @throws AuthenticationException when there is a problem authenticating.
* @throws InvalidRequestException when the request is invalid for some other reason.
* @throws PermissionRequiredException when permission is required to use the service.
* @throws MinFraudException when the web service returns unexpected content.
* @throws HttpException when the web service returns an unexpected response.
* @throws IOException when some other IO error occurs.
*/
public void reportTransaction(TransactionReport transaction) throws IOException,
MinFraudException, InsufficientFundsException, InvalidRequestException,
AuthenticationException, PermissionRequiredException, HttpException {
if (transaction == null) {
throw new IllegalArgumentException("transaction report must not be null");
}
var uri = createUri(WebServiceClient.pathBase + "transactions/report");
var request = requestFor(transaction, uri);
HttpResponse<InputStream> response = null;
try {
response = sendWithRetry(request);
maybeThrowException(response, uri);
exhaustBody(response);
} catch (InterruptedException e) {
throw new MinFraudException("Interrupted sending request", e);
} finally {
if (response != null) {
response.body().close();
}
}
}
private <T> T responseFor(String service, AbstractModel transaction, Class<T> cls)
throws IOException, MinFraudException {
if (transaction == null) {
throw new IllegalArgumentException("transaction must not be null");
}
var uri = createUri(WebServiceClient.pathBase + service);
var request = requestFor(transaction, uri);
HttpResponse<InputStream> response = null;
try {
response = sendWithRetry(request);
return handleResponse(response, uri, cls);
} catch (InterruptedException e) {
throw new MinFraudException("Interrupted sending request", e);
} finally {
if (response != null) {
response.body().close();
}
}
}
private HttpResponse<InputStream> sendWithRetry(HttpRequest request)
throws IOException, InterruptedException {
int attempts = 0;
IOException prior = null;
while (true) {
try {
return httpClient.send(request, HttpResponse.BodyHandlers.ofInputStream());
} catch (IOException e) {
// Attach the immediate predecessor so the suppressed chain
// carries the full retry history (each link is the previous
// attempt's failure; walk via Throwable#getSuppressed).
if (prior != null) {
e.addSuppressed(prior);
}
if (!isRetriableTransportFailure(e) || attempts >= maxRetries) {
throw e;
}
prior = e;
attempts++;
}
}
}
private static boolean isRetriableTransportFailure(IOException e) {
if (Thread.currentThread().isInterrupted()) {
return false;
}
// Both connect-phase and request-phase timeouts are customer-set
// budgets that retrying would silently extend.
// HttpConnectTimeoutException extends HttpTimeoutException, so this
// single check covers both.
if (e instanceof HttpTimeoutException) {
return false;
}
// The thread was interrupted during I/O; honor the cancellation.
if (e instanceof InterruptedIOException) {
return false;
}
// The four exclusions below are *occasionally* transient (DNS hiccup,
// TCP RST race during cert rotation, brief LB outage), but treating
// them as deterministic is a deliberate product decision: retrying
// would mask config bugs behind 2x latency, and the customer-visible
// cost of one extra failed call on a true transient is small.
if (e instanceof UnknownHostException) {
return false;
}
if (e instanceof ConnectException) {
return false;
}
if (e instanceof SSLHandshakeException) {
return false;
}
if (e instanceof SSLPeerUnverifiedException) {
return false;
}
// Everything else from httpClient.send() is a transport failure
// (connection reset, broken pipe, EOF, closed channel, ...).
// HTTP 4xx and 5xx responses do not reach this predicate -- they come
// back as HttpResponse objects rather than IOExceptions.
return true;
}
private HttpRequest requestFor(AbstractModel transaction, URI uri)
throws MinFraudException, IOException {
var builder = HttpRequest.newBuilder()
.uri(uri)
.header("Accept", "application/json")
.header("Authorization", authHeader)
.header("Content-Type", "application/json; charset=UTF-8")
.header("User-Agent", userAgent)
// XXX - creating this JSON string is somewhat wasteful. We
// could use an input stream instead.
// BodyPublishers.ofString() is replayable; safe for retry attempts
.POST(HttpRequest.BodyPublishers.ofString(transaction.toJson()));
if (requestTimeout != null) {
builder.timeout(requestTimeout);
}
return builder.build();
}
private void maybeThrowException(HttpResponse<InputStream> response, URI uri)
throws IOException, MinFraudException {
var status = response.statusCode();
if (status >= 400 && status < 500) {
this.handle4xxStatus(response, uri);
} else if (status >= 500 && status < 600) {
exhaustBody(response);
throw new HttpException("Received a server error (" + status
+ ") for " + uri, status, uri);
} else if (status != 200 && status != 204) {
exhaustBody(response);
throw new HttpException("Received an unexpected HTTP status ("
+ status + ") for " + uri, status, uri);
}
}
private <T> T handleResponse(HttpResponse<InputStream> response, URI uri, Class<T> cls)
throws MinFraudException, IOException {
maybeThrowException(response, uri);
var inject = new Std().addValue(
"locales", locales);
try (InputStream stream = response.body()) {
return Mapper.get().readerFor(cls).with(inject).readValue(stream);
} catch (IOException e) {
throw new MinFraudException(
"Received a 200 response but could not decode it as JSON", e);
}
}
private void handle4xxStatus(HttpResponse<InputStream> response, URI uri)
throws IOException, InsufficientFundsException,
InvalidRequestException, AuthenticationException,
PermissionRequiredException {
var status = response.statusCode();
String body;
try (InputStream stream = response.body()) {
body = new String(stream.readAllBytes(), StandardCharsets.UTF_8);
}
Map<String, String> content;
try {
content = Mapper.get().readValue(body,
new TypeReference<HashMap<String, String>>() {
});
this.handleErrorWithJsonBody(content, body, status, uri);
} catch (HttpException e) {
throw e;
} catch (IOException e) {
throw new HttpException("Received a " + status + " error for "
+ uri + " but it did not include the expected JSON body: "
+ body, status, uri, e);
}
}
private void handleErrorWithJsonBody(Map<String, String> content,
String body, int status, URI uri)
throws HttpException, InsufficientFundsException,
InvalidRequestException, AuthenticationException,
PermissionRequiredException {
var error = content.get("error");
var code = content.get("code");
if (error == null || code == null) {
throw new HttpException(
"Error response contains JSON but it does not specify code or error keys: "
+ body, status, uri);
}
switch (code) {
case "ACCOUNT_ID_REQUIRED", "AUTHORIZATION_INVALID", "LICENSE_KEY_REQUIRED",
"USER_ID_REQUIRED" -> throw new AuthenticationException(error);
case "INSUFFICIENT_FUNDS" -> throw new InsufficientFundsException(error);
case "PERMISSION_REQUIRED" -> throw new PermissionRequiredException(error);
default -> throw new InvalidRequestException(error, code, status, uri, null);
}
}
private URI createUri(String path) throws MinFraudException {
try {
return new URI(
useHttps ? "https" : "http",
null,
host,
port,
path,
null,
null
);
} catch (URISyntaxException e) {
throw new MinFraudException("Error creating service URL", e);
}
}
private void exhaustBody(HttpResponse<InputStream> response) throws HttpException {
try (InputStream body = response.body()) {
// Make sure we read the stream until the end so that
// the connection can be reused.
while (body.read() != -1) {
}
} catch (IOException e) {
throw new HttpException("Error reading response body", response.statusCode(),
response.uri(), e);
}
}
@Override
public String toString() {
return "WebServiceClient{"
+ "host='" + host + '\''
+ ", port=" + port
+ ", useHttps=" + useHttps
+ ", locales=" + locales
+ ", httpClient=" + httpClient
+ '}';
}
}