Skip to content

Commit 630ed0f

Browse files
authored
Merge pull request #39 from CyberSource/clean-proxy
Adding code to enable proxy settings in SDK
2 parents 7929858 + 49e192d commit 630ed0f

File tree

7 files changed

+104
-68
lines changed

7 files changed

+104
-68
lines changed

generator/cybersource-java-template/libraries/okhttp-gson/ApiClient.mustache

Lines changed: 86 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -12,72 +12,58 @@
1212

1313
package Invokers;
1414

15-
import java.io.File;
16-
import java.io.IOException;
1715
import java.io.InputStream;
1816
import java.io.UnsupportedEncodingException;
1917
import java.lang.reflect.Type;
18+
import java.net.HttpRetryException;
19+
import java.net.InetSocketAddress;
20+
import java.net.Proxy;
2021
import java.net.URLConnection;
2122
import java.net.URLEncoder;
2223
import java.security.GeneralSecurityException;
2324
import java.security.KeyStore;
24-
import java.security.NoSuchAlgorithmException;
2525
import java.security.SecureRandom;
2626
import java.security.cert.Certificate;
2727
import java.security.cert.CertificateException;
28-
import java.security.cert.CertificateFactory;
29-
import java.security.cert.X509Certificate;
30-
import java.text.DateFormat;
31-
import java.text.ParseException;
32-
import java.text.SimpleDateFormat;
33-
import java.util.ArrayList;
34-
import java.util.Collection;
35-
import java.util.Collections;
36-
import java.util.Date;
37-
import java.util.HashMap;
38-
import java.util.List;
39-
import java.util.Map;
40-
import java.util.Map.Entry;
41-
import java.util.TimeZone;
4228
import java.util.concurrent.TimeUnit;
4329
import java.util.regex.Matcher;
4430
import java.util.regex.Pattern;
45-
4631
import javax.net.ssl.HostnameVerifier;
4732
import javax.net.ssl.KeyManager;
4833
import javax.net.ssl.SSLContext;
4934
import javax.net.ssl.SSLSession;
5035
import javax.net.ssl.TrustManager;
5136
import javax.net.ssl.TrustManagerFactory;
5237
import javax.net.ssl.X509TrustManager;
53-
5438
import org.apache.logging.log4j.Logger;
55-
5639
import com.cybersource.authsdk.core.Authorization;
5740
import com.cybersource.authsdk.core.ConfigException;
5841
import com.cybersource.authsdk.core.MerchantConfig;
5942
import com.cybersource.authsdk.log.Log4j;
6043
import com.cybersource.authsdk.payloaddigest.PayloadDigest;
6144
import com.cybersource.authsdk.util.GlobalLabelParameters;
6245
import com.cybersource.authsdk.util.PropertiesUtil;
63-
import com.squareup.okhttp.Call;
64-
import com.squareup.okhttp.Callback;
65-
import com.squareup.okhttp.FormEncodingBuilder;
66-
import com.squareup.okhttp.Headers;
67-
import com.squareup.okhttp.MediaType;
68-
import com.squareup.okhttp.MultipartBuilder;
69-
import com.squareup.okhttp.OkHttpClient;
70-
import com.squareup.okhttp.Request;
71-
import com.squareup.okhttp.RequestBody;
72-
import com.squareup.okhttp.Response;
73-
import com.squareup.okhttp.internal.http.HttpMethod;
74-
import com.squareup.okhttp.logging.HttpLoggingInterceptor;
75-
import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level;
76-
7746
import Invokers.auth.ApiKeyAuth;
7847
import Invokers.auth.Authentication;
7948
import Invokers.auth.HttpBasicAuth;
8049
import Invokers.auth.OAuth;
50+
import okhttp3.Authenticator;
51+
import okhttp3.Call;
52+
import okhttp3.Callback;
53+
import okhttp3.Credentials;
54+
import okhttp3.FormBody;
55+
import okhttp3.FormBody.Builder;
56+
import okhttp3.Headers;
57+
import okhttp3.MediaType;
58+
import okhttp3.MultipartBody;
59+
import okhttp3.OkHttpClient;
60+
import okhttp3.Request;
61+
import okhttp3.RequestBody;
62+
import okhttp3.Response;
63+
import okhttp3.Route;
64+
import okhttp3.internal.http.HttpMethod;
65+
import okhttp3.logging.HttpLoggingInterceptor;
66+
import okhttp3.logging.HttpLoggingInterceptor.Level;
8167
import okio.BufferedSink;
8268
import okio.Okio;
8369

@@ -149,6 +135,12 @@ public class ApiClient {
149135
*/
150136
public ApiClient() {
151137
httpClient = new OkHttpClient();
138+
139+
httpClient = new OkHttpClient.Builder()
140+
.connectTimeout(1, TimeUnit.SECONDS)
141+
.writeTimeout(60, TimeUnit.SECONDS)
142+
.readTimeout(60, TimeUnit.SECONDS)
143+
.build();
152144
153145
verifyingSsl = true;
154146
@@ -180,6 +172,54 @@ public class ApiClient {
180172

181173
public ApiClient(MerchantConfig merchantConfig) {
182174
this();
175+
final boolean useProxy = merchantConfig.isUseProxyEnabled();
176+
final String username = merchantConfig.getProxyUser();
177+
final String password = merchantConfig.getProxyPassword();
178+
int proxyPort = merchantConfig.getProxyPort();
179+
String proxyHost = merchantConfig.getProxyAddress();
180+
181+
Authenticator proxyAuthenticator;
182+
183+
if (useProxy && (proxyHost != null && !proxyHost.isEmpty())) {
184+
if ((username != null && !username.isEmpty()) &&
185+
(password != null && !password.isEmpty())) {
186+
proxyAuthenticator = new Authenticator() {
187+
private int proxyCounter = 0;
188+
189+
@Override
190+
public Request authenticate(Route route, Response response) throws IOException {
191+
if (proxyCounter++ > 0) {
192+
if (response.code() == 407) {
193+
throw new HttpRetryException("Proxy Authentication Missing or Incorrect.", 407);
194+
} else {
195+
throw new IOException(response.message());
196+
}
197+
}
198+
199+
String credential = Credentials.basic(username, password);
200+
return response.request().newBuilder().header("Proxy-Authorization", credential).build();
201+
}
202+
};
203+
} else {
204+
proxyAuthenticator = new Authenticator() {
205+
@Override
206+
public Request authenticate(Route route, Response response) throws IOException {
207+
return response.request().newBuilder().build();
208+
}
209+
};
210+
}
211+
212+
httpClient = new OkHttpClient.Builder()
213+
.connectTimeout(1, TimeUnit.SECONDS)
214+
.writeTimeout(60, TimeUnit.SECONDS)
215+
.readTimeout(60, TimeUnit.SECONDS)
216+
.proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
217+
.proxyAuthenticator(proxyAuthenticator)
218+
.build();
219+
220+
this.setHttpClient(httpClient);
221+
}
222+
183223
this.merchantConfig = merchantConfig;
184224

185225
}
@@ -664,7 +704,7 @@ public class ApiClient {
664704
* @return Timeout in milliseconds
665705
*/
666706
public int getConnectTimeout() {
667-
return httpClient.getConnectTimeout();
707+
return httpClient.connectTimeoutMillis();
668708
}
669709

670710
/**
@@ -676,7 +716,7 @@ public class ApiClient {
676716
* @return Api client
677717
*/
678718
public ApiClient setConnectTimeout(int connectionTimeout) {
679-
httpClient.setConnectTimeout(connectionTimeout, TimeUnit.MILLISECONDS);
719+
this.httpClient = this.httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build();
680720
return this;
681721
}
682722

@@ -1096,12 +1136,12 @@ public class ApiClient {
10961136
public <T> void executeAsync(Call call, final Type returnType, final ApiCallback<T> callback) {
10971137
call.enqueue(new Callback() {
10981138
@Override
1099-
public void onFailure(Request request, IOException e) {
1139+
public void onFailure(Call call0, IOException e) {
11001140
callback.onFailure(new ApiException(e), 0, null);
11011141
}
11021142

11031143
@Override
1104-
public void onResponse(Response response) throws IOException {
1144+
public void onResponse(Call call0) throws IOException {
11051145
T result;
11061146
try {
11071147
result = (T) handleResponse(response, returnType);
@@ -1133,11 +1173,7 @@ public class ApiClient {
11331173
if (response.isSuccessful()) {
11341174
if (response.code() == 204) {
11351175
if (response.body() != null) {
1136-
try {
1137-
response.body().close();
1138-
} catch (IOException e) {
1139-
throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
1140-
}
1176+
response.body().close();
11411177
}
11421178
return null;
11431179
} else {
@@ -1387,6 +1423,8 @@ public class ApiClient {
13871423
reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
13881424
}
13891425
}
1426+
1427+
reqBuilder.header("Connection", "close");
13901428
}
13911429

13921430
/**
@@ -1416,7 +1454,7 @@ public class ApiClient {
14161454
* @return RequestBody
14171455
*/
14181456
public RequestBody buildRequestBodyFormEncoding(Map<String, Object> formParams) {
1419-
FormEncodingBuilder formBuilder = new FormEncodingBuilder();
1457+
FormBody.Builder formBuilder = new FormBody.Builder();
14201458
for (Entry<String, Object> param : formParams.entrySet()) {
14211459
formBuilder.add(param.getKey(), parameterToString(param.getValue()));
14221460
}
@@ -1432,7 +1470,7 @@ public class ApiClient {
14321470
* @return RequestBody
14331471
*/
14341472
public RequestBody buildRequestBodyMultipart(Map<String, Object> formParams) {
1435-
MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
1473+
MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
14361474
for (Entry<String, Object> param : formParams.entrySet()) {
14371475
if (param.getValue() instanceof File) {
14381476
File file = (File) param.getValue();
@@ -1549,11 +1587,11 @@ public class ApiClient {
15491587
if (keyManagers != null || trustManagers != null) {
15501588
SSLContext sslContext = SSLContext.getInstance("TLS");
15511589
sslContext.init(keyManagers, trustManagers, new SecureRandom());
1552-
httpClient.setSslSocketFactory(sslContext.getSocketFactory());
1590+
httpClient = httpClient.newBuilder().sslSocketFactory(sslContext.getSocketFactory()).build();
15531591
} else {
1554-
httpClient.setSslSocketFactory(null);
1592+
httpClient = httpClient.newBuilder().sslSocketFactory(null).build();
15551593
}
1556-
httpClient.setHostnameVerifier(hostnameVerifier);
1594+
httpClient = httpClient.newBuilder().hostnameVerifier(hostnameVerifier).build();
15571595
} catch (GeneralSecurityException e) {
15581596
throw new RuntimeException(e);
15591597
}

generator/cybersource-java-template/libraries/okhttp-gson/GzipRequestInterceptor.mustache

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
package {{invokerPackage}};
44

5-
import com.squareup.okhttp.*;
5+
import okhttp3.*;
66
import okio.Buffer;
77
import okio.BufferedSink;
88
import okio.GzipSink;

generator/cybersource-java-template/libraries/okhttp-gson/ProgressRequestBody.mustache

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
package {{invokerPackage}};
44

5-
import com.squareup.okhttp.MediaType;
6-
import com.squareup.okhttp.RequestBody;
5+
import okhttp3.MediaType;
6+
import okhttp3.RequestBody;
77

88
import java.io.IOException;
99

generator/cybersource-java-template/libraries/okhttp-gson/ProgressResponseBody.mustache

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,8 @@
22

33
package {{invokerPackage}};
44

5-
import com.squareup.okhttp.MediaType;
6-
import com.squareup.okhttp.ResponseBody;
5+
import okhttp3.MediaType;
6+
import okhttp3.ResponseBody;
77

88
import java.io.IOException;
99

@@ -34,12 +34,12 @@ public class ProgressResponseBody extends ResponseBody {
3434
}
3535

3636
@Override
37-
public long contentLength() throws IOException {
37+
public long contentLength() {
3838
return responseBody.contentLength();
3939
}
4040

4141
@Override
42-
public BufferedSource source() throws IOException {
42+
public BufferedSource source() {
4343
if (bufferedSource == null) {
4444
bufferedSource = Okio.buffer(source(responseBody.source()));
4545
}

generator/cybersource-java-template/libraries/okhttp-gson/api.mustache

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ public class {{classname}} {
7272
* @return Call to execute
7373
* @throws ApiException If fail to serialize the request body object
7474
*/
75-
public com.squareup.okhttp.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
75+
public okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
7676
Object {{localVariablePrefix}}localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}};
7777

7878
// create path and map variables
@@ -104,10 +104,10 @@ public class {{classname}} {
104104
{{localVariablePrefix}}localVarHeaderParams.put("Content-Type", {{localVariablePrefix}}localVarContentType);
105105

106106
if(progressListener != null) {
107-
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
107+
apiClient.getHttpClient().networkInterceptors().add(new okhttp3.Interceptor() {
108108
@Override
109-
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
110-
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
109+
public okhttp3.Response intercept(okhttp3.Interceptor.Chain chain) throws IOException {
110+
okhttp3.Response originalResponse = chain.proceed(chain.request());
111111
return originalResponse.newBuilder()
112112
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
113113
.build();
@@ -120,7 +120,7 @@ public class {{classname}} {
120120
}
121121

122122
@SuppressWarnings("rawtypes")
123-
private com.squareup.okhttp.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
123+
private okhttp3.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
124124
{{^performBeanValidation}}
125125
{{#allParams}}{{#required}}
126126
// verify the required parameter '{{paramName}}' is set
@@ -129,7 +129,7 @@ public class {{classname}} {
129129
}
130130
{{/required}}{{/allParams}}
131131

132-
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
132+
okhttp3.Call {{localVariablePrefix}}call = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
133133
return {{localVariablePrefix}}call;
134134

135135
{{/performBeanValidation}}
@@ -185,7 +185,7 @@ public class {{classname}} {
185185
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
186186
*/
187187
public ApiResponse<{{#vendorExtensions.x-streaming}}InputStream{{/vendorExtensions.x-streaming}}{{^vendorExtensions.x-streaming}}{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}{{/vendorExtensions.x-streaming}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException {
188-
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null);
188+
okhttp3.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null, null);
189189
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
190190
return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType);{{/returnType}}{{^returnType}}return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}}
191191
}
@@ -198,7 +198,7 @@ public class {{classname}} {
198198
* @return The request call
199199
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
200200
*/
201-
public com.squareup.okhttp.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
201+
public okhttp3.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException {
202202
203203
ProgressResponseBody.ProgressListener progressListener = null;
204204
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
@@ -219,7 +219,7 @@ public class {{classname}} {
219219
};
220220
}
221221

222-
com.squareup.okhttp.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
222+
okhttp3.Call {{localVariablePrefix}}call = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}progressListener, progressRequestListener);
223223
{{#returnType}}Type {{localVariablePrefix}}localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType();
224224
{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}localVarReturnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}}
225225
return {{localVariablePrefix}}call;

generator/cybersource-java-template/libraries/okhttp-gson/auth/HttpBasicAuth.mustache

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,11 @@ package {{invokerPackage}}.auth;
44

55
import {{invokerPackage}}.Pair;
66

7-
import com.squareup.okhttp.Credentials;
7+
import okhttp3.Credentials;
88

99
import java.util.Map;
1010
import java.util.List;
1111

12-
import java.io.UnsupportedEncodingException;
13-
1412
public class HttpBasicAuth implements Authentication {
1513
private String username;
1614
private String password;

src/main/java/Api/SecureFileShareApi.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,4 +326,4 @@ public void onRequestProgress(long bytesWritten, long contentLength, boolean don
326326
return call;
327327
}
328328
}
329-
329+

0 commit comments

Comments
 (0)