forked from stripe/stripe-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLiveStripeResponseGetter.java
More file actions
466 lines (401 loc) · 16.2 KB
/
LiveStripeResponseGetter.java
File metadata and controls
466 lines (401 loc) · 16.2 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
package com.stripe.net;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSyntaxException;
import com.stripe.Stripe;
import com.stripe.exception.*;
import com.stripe.exception.oauth.InvalidClientException;
import com.stripe.exception.oauth.InvalidGrantException;
import com.stripe.exception.oauth.InvalidScopeException;
import com.stripe.exception.oauth.OAuthException;
import com.stripe.exception.oauth.UnsupportedGrantTypeException;
import com.stripe.exception.oauth.UnsupportedResponseTypeException;
import com.stripe.model.*;
import com.stripe.model.oauth.OAuthError;
import com.stripe.util.Stopwatch;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public class LiveStripeResponseGetter implements StripeResponseGetter {
private final HttpClient httpClient;
private final StripeResponseGetterOptions options;
private final RequestTelemetry requestTelemetry = new RequestTelemetry();
@FunctionalInterface
private interface RequestSendFunction<R> {
R apply(StripeRequest request) throws StripeException;
}
private <T extends AbstractStripeResponse<?>> T sendWithTelemetry(
StripeRequest request, List<String> usage, RequestSendFunction<T> send)
throws StripeException {
Stopwatch stopwatch = Stopwatch.startNew();
T response = send.apply(request);
stopwatch.stop();
requestTelemetry.maybeEnqueueMetrics(response, stopwatch.getElapsed(), usage);
return response;
}
/**
* Initializes a new instance of the {@link LiveStripeResponseGetter} class with default
* parameters.
*/
public LiveStripeResponseGetter() {
this(null, null);
}
/**
* Initializes a new instance of the {@link LiveStripeResponseGetter} class.
*
* @param httpClient the HTTP client to use
*/
public LiveStripeResponseGetter(HttpClient httpClient) {
this(null, httpClient);
}
/**
* Initializes a new instance of the {@link LiveStripeResponseGetter} class.
*
* @param options the client options instance to use
* @param httpClient the HTTP client to use
*/
public LiveStripeResponseGetter(StripeResponseGetterOptions options, HttpClient httpClient) {
this.options = options != null ? options : GlobalStripeResponseGetterOptions.INSTANCE;
this.httpClient = (httpClient != null) ? httpClient : buildDefaultHttpClient();
}
private StripeRequest toStripeRequest(ApiRequest apiRequest, RequestOptions mergedOptions)
throws StripeException {
String fullUrl = fullUrl(apiRequest);
Optional<String> telemetryHeaderValue = requestTelemetry.pollPayload();
StripeRequest request =
StripeRequest.create(
apiRequest.getMethod(),
fullUrl,
apiRequest.getParams(),
mergedOptions,
apiRequest.getApiMode());
if (telemetryHeaderValue.isPresent()) {
request =
request.withAdditionalHeader(RequestTelemetry.HEADER_NAME, telemetryHeaderValue.get());
}
return request;
}
private StripeRequest toRawStripeRequest(RawApiRequest apiRequest, RequestOptions mergedOptions)
throws StripeException {
String fullUrl = fullUrl(apiRequest);
Optional<String> telemetryHeaderValue = requestTelemetry.pollPayload();
StripeRequest request =
StripeRequest.createWithStringContent(
apiRequest.getMethod(),
fullUrl,
apiRequest.getRawContent(),
mergedOptions,
apiRequest.getApiMode());
if (telemetryHeaderValue.isPresent()) {
request =
request.withAdditionalHeader(RequestTelemetry.HEADER_NAME, telemetryHeaderValue.get());
}
return request;
}
@Override
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
public <T extends StripeObject> T request(ApiRequest apiRequest, Type typeToken)
throws StripeException {
RequestOptions mergedOptions = RequestOptions.merge(this.options, apiRequest.getOptions());
if (RequestOptions.unsafeGetStripeVersionOverride(mergedOptions) != null) {
apiRequest = apiRequest.addUsage("unsafe_stripe_version_override");
}
StripeRequest request = toStripeRequest(apiRequest, mergedOptions);
StripeResponse response =
sendWithTelemetry(request, apiRequest.getUsage(), r -> httpClient.requestWithRetries(r));
int responseCode = response.code();
String responseBody = response.body();
String requestId = response.requestId();
if (responseCode < 200 || responseCode >= 300) {
handleError(response, apiRequest.getApiMode());
}
T resource = null;
try {
resource = (T) ApiResource.deserializeStripeObject(responseBody, typeToken, this);
} catch (JsonSyntaxException e) {
throw makeMalformedJsonError(responseBody, responseCode, requestId, e);
}
if (resource instanceof StripeCollectionInterface<?>) {
((StripeCollectionInterface<?>) resource).setRequestOptions(apiRequest.getOptions());
((StripeCollectionInterface<?>) resource).setRequestParams(apiRequest.getParams());
}
if (resource instanceof com.stripe.model.v2.StripeCollection<?>) {
((com.stripe.model.v2.StripeCollection<?>) resource)
.setRequestOptions(apiRequest.getOptions());
}
resource.setLastResponse(response);
return resource;
}
@Override
public InputStream requestStream(ApiRequest apiRequest) throws StripeException {
RequestOptions mergedOptions = RequestOptions.merge(this.options, apiRequest.getOptions());
if (RequestOptions.unsafeGetStripeVersionOverride(mergedOptions) != null) {
apiRequest = apiRequest.addUsage("unsafe_stripe_version_override");
}
StripeRequest request = toStripeRequest(apiRequest, mergedOptions);
StripeResponseStream responseStream =
sendWithTelemetry(
request, apiRequest.getUsage(), r -> httpClient.requestStreamWithRetries(r));
int responseCode = responseStream.code();
if (responseCode < 200 || responseCode >= 300) {
StripeResponse response;
try {
response = responseStream.unstream();
} catch (IOException e) {
throw ApiConnectionException.create(Stripe.getApiBase(), e);
}
handleError(response, apiRequest.getApiMode());
}
return responseStream.body();
}
@Override
public StripeResponse rawRequest(RawApiRequest apiRequest) throws StripeException {
RequestOptions mergedOptions = RequestOptions.merge(this.options, apiRequest.getOptions());
if (RequestOptions.unsafeGetStripeVersionOverride(mergedOptions) != null) {
apiRequest = apiRequest.addUsage("unsafe_stripe_version_override");
}
StripeRequest request = toRawStripeRequest(apiRequest, mergedOptions);
Map<String, String> additionalHeaders = apiRequest.getOptions().getAdditionalHeaders();
if (additionalHeaders != null) {
for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
request = request.withAdditionalHeader(key, value);
}
}
StripeResponse response =
sendWithTelemetry(request, apiRequest.getUsage(), r -> httpClient.requestWithRetries(r));
int responseCode = response.code();
if (responseCode < 200 || responseCode >= 300) {
handleError(response, apiRequest.getApiMode());
}
return response;
}
@Override
@SuppressWarnings({"TypeParameterUnusedInFormals", "deprecation"})
public <T extends StripeObject> T request(
BaseAddress baseAddress,
ApiResource.RequestMethod method,
String path,
Map<String, Object> params,
Type typeToken,
RequestOptions options,
ApiMode apiMode)
throws StripeException {
return this.request(new ApiRequest(baseAddress, method, path, params, options), typeToken);
}
@Override
@SuppressWarnings({"TypeParameterUnusedInFormals", "deprecation"})
public InputStream requestStream(
BaseAddress baseAddress,
ApiResource.RequestMethod method,
String path,
Map<String, Object> params,
RequestOptions options,
ApiMode apiMode)
throws StripeException {
return this.requestStream(new ApiRequest(baseAddress, method, path, params, options));
}
private static HttpClient buildDefaultHttpClient() {
return new HttpURLConnectionClient();
}
private static ApiException makeMalformedJsonError(
String responseBody, int responseCode, String requestId, Throwable e) throws ApiException {
String details = e == null ? "none" : e.getMessage();
throw new ApiException(
String.format(
"Invalid response object from API: %s. (HTTP response code was %d). Additional details: %s.",
responseBody, responseCode, details),
requestId,
null,
responseCode,
e);
}
private StripeError parseStripeError(
String body, int code, String requestId, Class<? extends StripeError> klass)
throws StripeException {
StripeError ret;
try {
JsonObject jsonObject =
ApiResource.GSON.fromJson(body, JsonObject.class).getAsJsonObject("error");
ret = (StripeError) StripeObject.deserializeStripeObject(jsonObject, klass, this);
if (ret != null) return ret;
} catch (JsonSyntaxException e) {
throw makeMalformedJsonError(body, code, requestId, e);
}
throw makeMalformedJsonError(body, code, requestId, null);
}
private void handleError(StripeResponse response, ApiMode apiMode) throws StripeException {
try {
/*
OAuth errors are JSON objects where `error` is a string. In
contrast, in API errors, `error` is a hash with sub-keys. We use
this property to distinguish between OAuth and API errors.
*/
JsonObject responseBody = ApiResource.GSON.fromJson(response.body(), JsonObject.class);
if (responseBody.has("error") && responseBody.get("error").isJsonPrimitive()) {
JsonPrimitive error = responseBody.getAsJsonPrimitive("error");
if (error.isString()) {
handleOAuthError(response);
}
} else if (apiMode == ApiMode.V2) {
handleV2ApiError(response);
} else {
handleV1ApiError(response);
}
} catch (JsonSyntaxException e) {
throw makeMalformedJsonError(response.body(), response.code(), response.requestId(), e);
}
}
private void handleV1ApiError(StripeResponse response) throws StripeException {
throwStripeException(response, ApiMode.V1);
}
private void handleV2ApiError(StripeResponse response) throws StripeException {
// First try to throw an exception based on the "type" field, if it exists and we
// recognize it. Otherwise, we will fall back to throwing an exception based on status code.
JsonObject body =
ApiResource.GSON.fromJson(response.body(), JsonObject.class).getAsJsonObject("error");
JsonElement typeElement = body == null ? null : body.get("type");
String type = typeElement == null ? "<no_type>" : typeElement.getAsString();
StripeException exception =
StripeException.parseV2Exception(type, body, response.code(), response.requestId(), this);
if (exception != null) {
throw exception;
}
throwStripeException(response, ApiMode.V2);
}
private void throwStripeException(StripeResponse response, ApiMode apiMode)
throws StripeException {
StripeError error =
parseStripeError(response.body(), response.code(), response.requestId(), StripeError.class);
error.setLastResponse(response);
StripeException exception = exceptionFromStatus(response.code(), response.requestId(), error);
exception.setStripeError(error, apiMode);
throw exception;
}
private StripeException exceptionFromStatus(int statusCode, String requestId, StripeError error) {
switch (statusCode) {
case 400:
case 404:
if ("idempotency_error".equals(error.getType())) {
return new IdempotencyException(
error.getMessage(), requestId, error.getCode(), statusCode);
} else {
return new InvalidRequestException(
error.getMessage(), error.getParam(), requestId, error.getCode(), statusCode, null);
}
case 401:
return new AuthenticationException(
error.getMessage(), requestId, error.getCode(), statusCode);
case 402:
return new CardException(
error.getMessage(),
requestId,
error.getCode(),
error.getParam(),
error.getDeclineCode(),
error.getCharge(),
statusCode,
null);
case 403:
return new PermissionException(error.getMessage(), requestId, error.getCode(), statusCode);
case 429:
return new RateLimitException(
error.getMessage(), error.getParam(), requestId, error.getCode(), statusCode, null);
default:
return new ApiException(error.getMessage(), requestId, error.getCode(), statusCode, null);
}
}
private void handleOAuthError(StripeResponse response) throws StripeException {
OAuthError error = null;
StripeException exception = null;
try {
error = StripeObject.deserializeStripeObject(response.body(), OAuthError.class, this);
} catch (JsonSyntaxException e) {
throw makeMalformedJsonError(response.body(), response.code(), response.requestId(), e);
}
if (error == null) {
throw makeMalformedJsonError(response.body(), response.code(), response.requestId(), null);
}
error.setLastResponse(response);
String code = error.getError();
String description = (error.getErrorDescription() != null) ? error.getErrorDescription() : code;
switch (code) {
case "invalid_client":
exception =
new InvalidClientException(
code, description, response.requestId(), response.code(), null);
break;
case "invalid_grant":
exception =
new InvalidGrantException(
code, description, response.requestId(), response.code(), null);
break;
case "invalid_request":
exception =
new com.stripe.exception.oauth.InvalidRequestException(
code, description, response.requestId(), response.code(), null);
break;
case "invalid_scope":
exception =
new InvalidScopeException(
code, description, response.requestId(), response.code(), null);
break;
case "unsupported_grant_type":
exception =
new UnsupportedGrantTypeException(
code, description, response.requestId(), response.code(), null);
break;
case "unsupported_response_type":
exception =
new UnsupportedResponseTypeException(
code, description, response.requestId(), response.code(), null);
break;
default:
exception = new ApiException(code, response.requestId(), null, response.code(), null);
break;
}
if (exception instanceof OAuthException) {
((OAuthException) exception).setOauthError(error);
}
throw exception;
}
@Override
public void validateRequestOptions(RequestOptions options) {
if ((options == null || options.getAuthenticator() == null)
&& this.options.getAuthenticator() == null) {
throw new ApiKeyMissingException(
"API key is not set. You can set the API key globally using Stripe.ApiKey, or by passing RequestOptions");
}
}
private String fullUrl(BaseApiRequest apiRequest) {
BaseAddress baseAddress = apiRequest.getBaseAddress();
RequestOptions options = apiRequest.getOptions();
String relativeUrl = apiRequest.getPath();
String baseUrl;
switch (baseAddress) {
case API:
baseUrl = this.options.getApiBase();
break;
case CONNECT:
baseUrl = this.options.getConnectBase();
break;
case FILES:
baseUrl = this.options.getFilesBase();
break;
case METER_EVENTS:
baseUrl = this.options.getMeterEventsBase();
break;
default:
throw new IllegalArgumentException("Unknown base address " + baseAddress);
}
if (options != null && options.getBaseUrl() != null) {
baseUrl = options.getBaseUrl();
}
return String.format("%s%s", baseUrl, relativeUrl);
}
}