• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

Adyen / adyen-java-api-library / #2752

23 Oct 2023 03:04PM CUT coverage: 12.821%. First build
#2752

push

web-flow
Merge 1479c10ab into b96088175

12345 of 96286 relevant lines covered (12.82%)

0.13 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/main/java/com/adyen/httpclient/AdyenHttpClient.java
1
/*
2
 *                       ######
3
 *                       ######
4
 * ############    ####( ######  #####. ######  ############   ############
5
 * #############  #####( ######  #####. ######  #############  #############
6
 *        ######  #####( ######  #####. ######  #####  ######  #####  ######
7
 * ###### ######  #####( ######  #####. ######  #####  #####   #####  ######
8
 * ###### ######  #####( ######  #####. ######  #####          #####  ######
9
 * #############  #############  #############  #############  #####  ######
10
 *  ############   ############  #############   ############  #####  ######
11
 *                                      ######
12
 *                               #############
13
 *                               ############
14
 *
15
 * Adyen Java API Library
16
 *
17
 * Copyright (c) 2021 Adyen B.V.
18
 * This file is open source and available under the MIT license.
19
 * See the LICENSE file for more info.
20
 */
21
package com.adyen.httpclient;
22

23
import com.adyen.Client;
24
import com.adyen.Config;
25
import com.adyen.constants.ApiConstants;
26
import com.adyen.model.RequestOptions;
27
import org.apache.commons.codec.binary.Base64;
28
import org.apache.hc.client5.http.classic.methods.HttpDelete;
29
import org.apache.hc.client5.http.classic.methods.HttpGet;
30
import org.apache.hc.client5.http.classic.methods.HttpPatch;
31
import org.apache.hc.client5.http.classic.methods.HttpPost;
32
import org.apache.hc.client5.http.classic.methods.HttpUriRequest;
33
import org.apache.hc.client5.http.classic.methods.HttpUriRequestBase;
34
import org.apache.hc.client5.http.config.RequestConfig;
35
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
36
import org.apache.hc.client5.http.impl.classic.HttpClients;
37
import org.apache.hc.client5.http.impl.io.PoolingHttpClientConnectionManagerBuilder;
38
import org.apache.hc.client5.http.ssl.SSLConnectionSocketFactory;
39
import org.apache.hc.core5.http.HttpHost;
40
import org.apache.hc.core5.http.io.entity.StringEntity;
41
import org.apache.hc.core5.net.URIBuilder;
42
import org.apache.hc.core5.ssl.SSLContexts;
43

44
import javax.net.ssl.HostnameVerifier;
45
import javax.net.ssl.SSLContext;
46
import java.io.IOException;
47
import java.net.InetSocketAddress;
48
import java.net.Proxy;
49
import java.net.URI;
50
import java.net.URISyntaxException;
51
import java.nio.charset.Charset;
52
import java.util.Map;
53
import java.util.concurrent.TimeUnit;
54

55
import static com.adyen.constants.ApiConstants.HttpMethod.POST;
56
import static com.adyen.constants.ApiConstants.RequestProperty.ACCEPT_CHARSET;
57
import static com.adyen.constants.ApiConstants.RequestProperty.ADYEN_LIBRARY_NAME;
58
import static com.adyen.constants.ApiConstants.RequestProperty.ADYEN_LIBRARY_VERSION;
59
import static com.adyen.constants.ApiConstants.RequestProperty.API_KEY;
60
import static com.adyen.constants.ApiConstants.RequestProperty.APPLICATION_JSON_TYPE;
61
import static com.adyen.constants.ApiConstants.RequestProperty.CONTENT_TYPE;
62
import static com.adyen.constants.ApiConstants.RequestProperty.IDEMPOTENCY_KEY;
63
import static com.adyen.constants.ApiConstants.RequestProperty.REQUESTED_VERIFICATION_CODE_HEADER;
64
import static com.adyen.constants.ApiConstants.RequestProperty.USER_AGENT;
65

66
public class AdyenHttpClient implements ClientInterface {
×
67

68
    private static final String CHARSET = "UTF-8";
69
    private Proxy proxy;
70

71
    public Proxy getProxy() {
72
        return proxy;
×
73
    }
74

75
    public void setProxy(Proxy proxy) {
76
        this.proxy = proxy;
×
77
    }
×
78

79
    @Override
80
    public String request(String endpoint, String requestBody, Config config) throws IOException, HTTPClientException {
81
        return request(endpoint, requestBody, config, false);
×
82
    }
83

84
    @Override
85
    public String request(String endpoint, String requestBody, Config config, boolean isApiKeyRequired) throws IOException, HTTPClientException {
86
        return request(endpoint, requestBody, config, isApiKeyRequired, null);
×
87
    }
88

89
    @Override
90
    public String request(String endpoint, String requestBody, Config config, boolean isApiKeyRequired, RequestOptions requestOptions) throws IOException, HTTPClientException {
91
        return request(endpoint, requestBody, config, isApiKeyRequired, requestOptions, POST);
×
92
    }
93

94
    @Override
95
    public String request(String endpoint, String requestBody, Config config, boolean isApiKeyRequired, RequestOptions requestOptions, ApiConstants.HttpMethod httpMethod) throws IOException, HTTPClientException {
96
        return request(endpoint, requestBody, config, isApiKeyRequired, requestOptions, httpMethod, null);
×
97
    }
98

99
    @Override
100
    public String request(String endpoint, String requestBody, Config config, boolean isApiKeyRequired, RequestOptions requestOptions, ApiConstants.HttpMethod httpMethod, Map<String, String> params) throws IOException, HTTPClientException {
101
        try (CloseableHttpClient httpclient = createCloseableHttpClient(config)) {
×
102
            HttpUriRequestBase httpRequest = createRequest(endpoint, requestBody, config, isApiKeyRequired, requestOptions, httpMethod, params);
×
103

104
            // Execute request with a custom response handler
105
            AdyenResponse response = httpclient.execute(httpRequest, new AdyenResponseHandler());
×
106

107
            if (response.getStatus() < 200 || response.getStatus() >= 300) {
×
108
                throw new HTTPClientException(response.getStatus(), "HTTP Exception", response.getHeaders(), response.getBody());
×
109
            }
110
            return response.getBody();
×
111
        }
112
    }
113

114
    private HttpUriRequestBase createRequest(String endpoint, String requestBody, Config config, boolean isApiKeyRequired, RequestOptions requestOptions, ApiConstants.HttpMethod httpMethod, Map<String, String> params) throws HTTPClientException {
115
        HttpUriRequestBase httpRequest = createHttpRequestBase(createUri(endpoint, params), requestBody, httpMethod);
×
116

117
        RequestConfig.Builder builder = RequestConfig.custom();
×
118
        if (config.getReadTimeoutMillis() > 0) {
×
119
            builder.setResponseTimeout(config.getReadTimeoutMillis(), TimeUnit.MILLISECONDS);
×
120
        }
121
        if (config.getConnectionTimeoutMillis() > 0) {
×
122
            builder.setConnectTimeout(config.getConnectionTimeoutMillis(), TimeUnit.MILLISECONDS);
×
123
        }
124
        if (proxy != null && proxy.address() instanceof InetSocketAddress) {
×
125
            InetSocketAddress inetSocketAddress = (InetSocketAddress) proxy.address();
×
126
            builder.setProxy(new HttpHost(inetSocketAddress.getHostName(), inetSocketAddress.getPort()));
×
127
        }
128
        httpRequest.setConfig(builder.build());
×
129

130
        setAuthentication(httpRequest, isApiKeyRequired, config);
×
131
        setHeaders(config, requestOptions, httpRequest);
×
132

133
        return httpRequest;
×
134
    }
135

136
    private void setHeaders(Config config, RequestOptions requestOptions, HttpUriRequestBase httpUriRequest) {
137

138
        setContentType(httpUriRequest, APPLICATION_JSON_TYPE);
×
139
        httpUriRequest.addHeader(ACCEPT_CHARSET, CHARSET);
×
140
        httpUriRequest.addHeader(USER_AGENT, String.format("%s %s/%s", config.getApplicationName(), Client.LIB_NAME, Client.LIB_VERSION));
×
141
        httpUriRequest.addHeader(ADYEN_LIBRARY_NAME, Client.LIB_NAME);
×
142
        httpUriRequest.addHeader(ADYEN_LIBRARY_VERSION, Client.LIB_VERSION);
×
143

144
        if (requestOptions != null) {
×
145
            if (requestOptions.getIdempotencyKey() != null) {
×
146
                httpUriRequest.addHeader(IDEMPOTENCY_KEY, requestOptions.getIdempotencyKey());
×
147
            }
148
            if (requestOptions.getRequestedVerificationCodeHeader() != null) {
×
149
                httpUriRequest.addHeader(REQUESTED_VERIFICATION_CODE_HEADER, requestOptions.getRequestedVerificationCodeHeader());
×
150
            }
151

152
            if (requestOptions.getAdditionalServiceHeaders() != null) {
×
153
                requestOptions.getAdditionalServiceHeaders().forEach(httpUriRequest::addHeader);
×
154
            }
155
        }
156
    }
×
157

158
    private HttpUriRequestBase createHttpRequestBase(URI endpoint, String requestBody, ApiConstants.HttpMethod httpMethod) {
159
        StringEntity requestEntity = null;
×
160
        if (requestBody != null && !requestBody.isEmpty()) {
×
161
            requestEntity = new StringEntity(requestBody, Charset.forName(CHARSET));
×
162
        }
163

164
        switch (httpMethod) {
×
165
            case GET:
166
                return new HttpGet(endpoint);
×
167
            case PATCH:
168
                HttpPatch httpPatch = new HttpPatch(endpoint);
×
169
                httpPatch.setEntity(requestEntity);
×
170
                return httpPatch;
×
171
            case DELETE:
172
                return new HttpDelete(endpoint);
×
173
            default:
174
                // Default to POST if httpMethod is not provided
175
                HttpPost httpPost = new HttpPost(endpoint);
×
176
                httpPost.setEntity(requestEntity);
×
177
                return httpPost;
×
178
        }
179
    }
180

181
    private URI createUri(String endpoint, Map<String, String> params) throws HTTPClientException {
182
        try {
183
            URIBuilder uriBuilder = new URIBuilder(endpoint);
×
184
            if (params != null && !params.isEmpty()) {
×
185
                for (String key: params.keySet()) {
×
186
                    uriBuilder.addParameter(key, params.get(key));
×
187
                }
×
188
            }
189
            return uriBuilder.build();
×
190
        } catch (URISyntaxException e) {
×
191
            throw new HTTPClientException("Invalid URI", e);
×
192
        }
193
    }
194

195
    private CloseableHttpClient createCloseableHttpClient(Config config) {
196
        SSLContext sslContext = config.getSSLContext();
×
197
        if (sslContext == null) {
×
198
            sslContext = SSLContexts.createDefault();
×
199
        }
200
        HostnameVerifier hostnameVerifier = config.getHostnameVerifier();
×
201
        return createHttpClientWithSocketFactory(new SSLConnectionSocketFactory(sslContext, hostnameVerifier));
×
202
    }
203

204
    private CloseableHttpClient createHttpClientWithSocketFactory(SSLConnectionSocketFactory socketFactory) {
205
        return HttpClients.custom()
×
206
                .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
×
207
                        .setSSLSocketFactory(socketFactory)
×
208
                        .build())
×
209
                .build();
×
210
    }
211

212
    /**
213
     * Sets content type
214
     */
215
    private void setAuthentication(HttpUriRequest httpUriRequest, boolean isApiKeyRequired, Config config) {
216
        String apiKey = config.getApiKey();
×
217
        // Use Api key if required or if provided
218
        if (isApiKeyRequired || (apiKey != null && !apiKey.isEmpty())) {
×
219
            setApiKey(httpUriRequest, apiKey);
×
220
        } else {
221
            setBasicAuthentication(httpUriRequest, config.getUsername(), config.getPassword());
×
222
        }
223
    }
×
224

225
    /**
226
     * Sets content type
227
     */
228
    private void setContentType(HttpUriRequest httpUriRequest, String contentType) {
229
        httpUriRequest.addHeader(CONTENT_TYPE, contentType);
×
230
    }
×
231

232
    /**
233
     * Sets api key
234
     */
235
    private void setApiKey(HttpUriRequest httpUriRequest, String apiKey) {
236
        if (apiKey != null && !apiKey.isEmpty()) {
×
237
            httpUriRequest.addHeader(API_KEY, apiKey);
×
238
        }
239
    }
×
240

241
    /**
242
     * Adds Basic Authentication headers
243
     */
244
    private void setBasicAuthentication(HttpUriRequest httpUriRequest, String username, String password) {
245
        // set basic authentication
246
        String authString = username + ":" + password;
×
247
        byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
×
248
        String authStringEnc = new String(authEncBytes);
×
249

250
        httpUriRequest.addHeader("Authorization", "Basic " + authStringEnc);
×
251
    }
×
252
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc