-
Notifications
You must be signed in to change notification settings - Fork 151
Expand file tree
/
Copy pathAdyenHttpClient.java
More file actions
328 lines (288 loc) · 12.5 KB
/
AdyenHttpClient.java
File metadata and controls
328 lines (288 loc) · 12.5 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
/*
* ######
* ######
* ############ ####( ###### #####. ###### ############ ############
* ############# #####( ###### #####. ###### ############# #############
* ###### #####( ###### #####. ###### ##### ###### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ##### ######
* ###### ###### #####( ###### #####. ###### ##### ##### ######
* ############# ############# ############# ############# ##### ######
* ############ ############ ############# ############ ##### ######
* ######
* #############
* ############
*
* Adyen Java API Library
*
* Copyright (c) 2021 Adyen B.V.
* This file is open source and available under the MIT license.
* See the LICENSE file for more info.
*/
package com.adyen.httpclient;
import static com.adyen.constants.ApiConstants.HttpMethod.POST;
import static com.adyen.constants.ApiConstants.RequestProperty.ACCEPT_CHARSET;
import static com.adyen.constants.ApiConstants.RequestProperty.ADYEN_LIBRARY_NAME;
import static com.adyen.constants.ApiConstants.RequestProperty.ADYEN_LIBRARY_VERSION;
import static com.adyen.constants.ApiConstants.RequestProperty.API_KEY;
import static com.adyen.constants.ApiConstants.RequestProperty.APPLICATION_JSON_TYPE;
import static com.adyen.constants.ApiConstants.RequestProperty.CONTENT_TYPE;
import static com.adyen.constants.ApiConstants.RequestProperty.IDEMPOTENCY_KEY;
import static com.adyen.constants.ApiConstants.RequestProperty.REQUESTED_VERIFICATION_CODE_HEADER;
import static com.adyen.constants.ApiConstants.RequestProperty.USER_AGENT;
import static com.adyen.constants.ApiConstants.RequestProperty.WWW_AUTHENTICATE_HEADER;
import com.adyen.Client;
import com.adyen.Config;
import com.adyen.constants.ApiConstants;
import com.adyen.model.RequestOptions;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import org.apache.commons.codec.binary.Base64;
import org.apache.hc.client5.http.classic.methods.HttpDelete;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPatch;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.classic.methods.HttpUriRequest;
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.net.URIBuilder;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.Timeout;
/** HTTP client implementation to invoke the Adyen APIs. Built on top of org.apache.hc.client5 */
public class AdyenHttpClient implements ClientInterface {
private static final String CHARSET = "UTF-8";
private Proxy proxy;
public Proxy getProxy() {
return proxy;
}
public void setProxy(Proxy proxy) {
this.proxy = proxy;
}
@Override
public String request(String endpoint, String requestBody, Config config)
throws IOException, HTTPClientException {
return request(endpoint, requestBody, config, false);
}
@Override
public String request(
String endpoint, String requestBody, Config config, boolean isApiKeyRequired)
throws IOException, HTTPClientException {
return request(endpoint, requestBody, config, isApiKeyRequired, null);
}
@Override
public String request(
String endpoint,
String requestBody,
Config config,
boolean isApiKeyRequired,
RequestOptions requestOptions)
throws IOException, HTTPClientException {
return request(endpoint, requestBody, config, isApiKeyRequired, requestOptions, POST);
}
@Override
public String request(
String endpoint,
String requestBody,
Config config,
boolean isApiKeyRequired,
RequestOptions requestOptions,
ApiConstants.HttpMethod httpMethod)
throws IOException, HTTPClientException {
return request(
endpoint, requestBody, config, isApiKeyRequired, requestOptions, httpMethod, null);
}
@Override
public String request(
String endpoint,
String requestBody,
Config config,
boolean isApiKeyRequired,
RequestOptions requestOptions,
ApiConstants.HttpMethod httpMethod,
Map<String, String> params)
throws IOException, HTTPClientException {
try (CloseableHttpClient httpclient = createCloseableHttpClient(config)) {
HttpUriRequestBase httpRequest =
createRequest(
endpoint, requestBody, config, isApiKeyRequired, requestOptions, httpMethod, params);
// Execute request with a custom response handler
AdyenResponse response = httpclient.execute(httpRequest, new AdyenResponseHandler());
if (response.getStatus() < 200 || response.getStatus() >= 300) {
throw new HTTPClientException(
response.getStatus(), "HTTP Exception", response.getHeaders(), response.getBody());
}
return response.getBody();
}
}
HttpUriRequestBase createRequest(
String endpoint,
String requestBody,
Config config,
boolean isApiKeyRequired,
RequestOptions requestOptions,
ApiConstants.HttpMethod httpMethod,
Map<String, String> params)
throws HTTPClientException {
HttpUriRequestBase httpRequest =
createHttpRequestBase(createUri(endpoint, params), requestBody, httpMethod);
RequestConfig.Builder builder = RequestConfig.custom();
builder.setResponseTimeout(config.getReadTimeoutMillis(), TimeUnit.MILLISECONDS);
builder.setDefaultKeepAlive(config.getDefaultKeepAliveMillis(), TimeUnit.MILLISECONDS);
builder.setConnectionRequestTimeout(
config.getConnectionRequestTimeoutMillis(), TimeUnit.MILLISECONDS);
if (config.getProtocolUpgradeEnabled() != null) {
builder.setProtocolUpgradeEnabled(config.getProtocolUpgradeEnabled());
}
httpRequest.setConfig(builder.build());
setAuthentication(httpRequest, isApiKeyRequired, config);
setHeaders(config, requestOptions, httpRequest);
return httpRequest;
}
private void setHeaders(
Config config, RequestOptions requestOptions, HttpUriRequestBase httpUriRequest) {
setContentType(httpUriRequest, APPLICATION_JSON_TYPE);
httpUriRequest.addHeader(ACCEPT_CHARSET, CHARSET);
String applicationName = config.getApplicationName();
String userAgent =
(applicationName != null && !applicationName.isBlank())
? String.format("%s %s/%s", applicationName, Client.LIB_NAME, Client.LIB_VERSION)
: String.format("%s/%s", Client.LIB_NAME, Client.LIB_VERSION);
httpUriRequest.addHeader(USER_AGENT, userAgent);
httpUriRequest.addHeader(ADYEN_LIBRARY_NAME, Client.LIB_NAME);
httpUriRequest.addHeader(ADYEN_LIBRARY_VERSION, Client.LIB_VERSION);
if (requestOptions != null) {
if (requestOptions.getIdempotencyKey() != null) {
httpUriRequest.addHeader(IDEMPOTENCY_KEY, requestOptions.getIdempotencyKey());
}
if (requestOptions.getRequestedVerificationCodeHeader() != null) {
httpUriRequest.addHeader(
REQUESTED_VERIFICATION_CODE_HEADER,
requestOptions.getRequestedVerificationCodeHeader());
}
if (requestOptions.getWwwAuthenticateHeader() != null) {
httpUriRequest.addHeader(
WWW_AUTHENTICATE_HEADER, requestOptions.getWwwAuthenticateHeader());
}
if (requestOptions.getAdditionalServiceHeaders() != null) {
requestOptions.getAdditionalServiceHeaders().forEach(httpUriRequest::addHeader);
}
}
}
private HttpUriRequestBase createHttpRequestBase(
URI endpoint, String requestBody, ApiConstants.HttpMethod httpMethod) {
StringEntity requestEntity = null;
if (requestBody != null && !requestBody.isEmpty()) {
requestEntity = new StringEntity(requestBody, Charset.forName(CHARSET));
}
switch (httpMethod) {
case GET:
return new HttpGet(endpoint);
case PATCH:
HttpPatch httpPatch = new HttpPatch(endpoint);
httpPatch.setEntity(requestEntity);
return httpPatch;
case DELETE:
return new HttpDelete(endpoint);
default:
// Default to POST if httpMethod is not provided
HttpPost httpPost = new HttpPost(endpoint);
httpPost.setEntity(requestEntity);
return httpPost;
}
}
private URI createUri(String endpoint, Map<String, String> params) throws HTTPClientException {
try {
URIBuilder uriBuilder = new URIBuilder(endpoint);
if (params != null && !params.isEmpty()) {
for (String key : params.keySet()) {
uriBuilder.addParameter(key, params.get(key));
}
}
return uriBuilder.build();
} catch (URISyntaxException e) {
throw new HTTPClientException("Invalid URI", e);
}
}
private CloseableHttpClient createCloseableHttpClient(Config config) {
SSLContext sslContext = config.getSSLContext();
if (sslContext == null) {
sslContext = SSLContexts.createDefault();
}
HostnameVerifier hostnameVerifier = config.getHostnameVerifier();
// Create ConnectionConfig with connect timeout
ConnectionConfig connectionConfig =
ConnectionConfig.custom()
.setConnectTimeout(Timeout.ofMilliseconds(config.getConnectionTimeoutMillis()))
.build();
// Create TlsSocketStrategy with SSL context and hostname verifier
DefaultClientTlsStrategy tlsStrategy =
new DefaultClientTlsStrategy(sslContext, hostnameVerifier);
// Create connection manager with TLS strategy and connection config
var connectionManager =
PoolingHttpClientConnectionManagerBuilder.create()
.setTlsSocketStrategy(tlsStrategy)
.setDefaultConnectionConfig(connectionConfig)
.build();
// Build HTTP client with connection manager and redirect strategy
var httpClientBuilder =
HttpClients.custom()
.setConnectionManager(connectionManager)
.setRedirectStrategy(new AdyenCustomRedirectStrategy());
// Set proxy if configured
if (proxy != null && proxy.address() instanceof InetSocketAddress) {
InetSocketAddress inetSocketAddress = (InetSocketAddress) proxy.address();
String scheme =
proxy.type() == Proxy.Type.SOCKS ? "socks" : "http"; // Map proxy type to scheme
HttpHost proxyHost =
new HttpHost(scheme, inetSocketAddress.getHostName(), inetSocketAddress.getPort());
DefaultProxyRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxyHost);
httpClientBuilder.setRoutePlanner(routePlanner);
}
return httpClientBuilder.build();
}
/** Sets content type */
private void setAuthentication(
HttpUriRequest httpUriRequest, boolean isApiKeyRequired, Config config) {
String apiKey = config.getApiKey();
// Use Api key if required or if provided
if (isApiKeyRequired || (apiKey != null && !apiKey.isEmpty())) {
setApiKey(httpUriRequest, apiKey);
} else {
setBasicAuthentication(httpUriRequest, config.getUsername(), config.getPassword());
}
}
/** Sets content type */
private void setContentType(HttpUriRequest httpUriRequest, String contentType) {
httpUriRequest.addHeader(CONTENT_TYPE, contentType);
}
/** Sets api key */
private void setApiKey(HttpUriRequest httpUriRequest, String apiKey) {
if (apiKey != null && !apiKey.isEmpty()) {
httpUriRequest.addHeader(API_KEY, apiKey);
}
}
/** Adds Basic Authentication headers */
private void setBasicAuthentication(
HttpUriRequest httpUriRequest, String username, String password) {
// set basic authentication
String authString = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
httpUriRequest.addHeader("Authorization", "Basic " + authStringEnc);
}
}