1212
1313package Invokers;
1414
15- import java.io.File;
16- import java.io.IOException;
1715import java.io.InputStream;
1816import java.io.UnsupportedEncodingException;
1917import java.lang.reflect.Type;
18+ import java.net.HttpRetryException;
19+ import java.net.InetSocketAddress;
20+ import java.net.Proxy;
2021import java.net.URLConnection;
2122import java.net.URLEncoder;
2223import java.security.GeneralSecurityException;
2324import java.security.KeyStore;
24- import java.security.NoSuchAlgorithmException;
2525import java.security.SecureRandom;
2626import java.security.cert.Certificate;
2727import java.security.cert.CertificateException;
@@ -43,42 +43,42 @@ import java.util.TimeZone;
4343import java.util.concurrent.TimeUnit;
4444import java.util.regex.Matcher;
4545import java.util.regex.Pattern;
46-
4746import javax.net.ssl.HostnameVerifier;
4847import javax.net.ssl.KeyManager;
4948import javax.net.ssl.SSLContext;
5049import javax.net.ssl.SSLSession;
5150import javax.net.ssl.TrustManager;
5251import javax.net.ssl.TrustManagerFactory;
5352import javax.net.ssl.X509TrustManager;
54-
5553import org.apache.logging.log4j.Logger;
56-
5754import com.cybersource.authsdk.core.Authorization;
5855import com.cybersource.authsdk.core.ConfigException;
5956import com.cybersource.authsdk.core.MerchantConfig;
6057import com.cybersource.authsdk.log.Log4j;
6158import com.cybersource.authsdk.payloaddigest.PayloadDigest;
6259import com.cybersource.authsdk.util.GlobalLabelParameters;
6360import com.cybersource.authsdk.util.PropertiesUtil;
64- import com.squareup.okhttp.Call;
65- import com.squareup.okhttp.Callback;
66- import com.squareup.okhttp.FormEncodingBuilder;
67- import com.squareup.okhttp.Headers;
68- import com.squareup.okhttp.MediaType;
69- import com.squareup.okhttp.MultipartBuilder;
70- import com.squareup.okhttp.OkHttpClient;
71- import com.squareup.okhttp.Request;
72- import com.squareup.okhttp.RequestBody;
73- import com.squareup.okhttp.Response;
74- import com.squareup.okhttp.internal.http.HttpMethod;
75- import com.squareup.okhttp.logging.HttpLoggingInterceptor;
76- import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level;
77-
7861import Invokers.auth.ApiKeyAuth;
7962import Invokers.auth.Authentication;
8063import Invokers.auth.HttpBasicAuth;
8164import Invokers.auth.OAuth;
65+ import okhttp3.Authenticator;
66+ import okhttp3.Call;
67+ import okhttp3.Callback;
68+ import okhttp3.Credentials;
69+ import okhttp3.FormBody;
70+ import okhttp3.FormBody.Builder;
71+ import okhttp3.Headers;
72+ import okhttp3.MediaType;
73+ import okhttp3.MultipartBody;
74+ import okhttp3.OkHttpClient;
75+ import okhttp3.Request;
76+ import okhttp3.RequestBody;
77+ import okhttp3.Response;
78+ import okhttp3.Route;
79+ import okhttp3.internal.http.HttpMethod;
80+ import okhttp3.logging.HttpLoggingInterceptor;
81+ import okhttp3.logging.HttpLoggingInterceptor.Level;
8282import okio.BufferedSink;
8383import okio.Okio;
8484
@@ -88,7 +88,7 @@ public class ApiClient {
8888 public static final int ANDROID_SDK_VERSION;
8989 public String responseCode;
9090 public String status;
91- public String responseBody;
91+ public InputStream responseBody;
9292 public String respBody;
9393 public MerchantConfig merchantConfig;
9494
@@ -154,6 +154,12 @@ public class ApiClient {
154154
155155 versionInfo = getClientID();
156156
157+ httpClient = new OkHttpClient.Builder()
158+ .connectTimeout(1, TimeUnit.SECONDS)
159+ .writeTimeout(60, TimeUnit.SECONDS)
160+ .readTimeout(60, TimeUnit.SECONDS)
161+ .build();
162+
157163 verifyingSsl = true ;
158164
159165 json = new JSON(this);
@@ -197,6 +203,54 @@ public class ApiClient {
197203
198204 public ApiClient(MerchantConfig merchantConfig) {
199205 this();
206+ final boolean useProxy = merchantConfig.isUseProxyEnabled();
207+ final String username = merchantConfig.getProxyUser();
208+ final String password = merchantConfig.getProxyPassword();
209+ int proxyPort = merchantConfig.getProxyPort();
210+ String proxyHost = merchantConfig.getProxyAddress();
211+
212+ Authenticator proxyAuthenticator;
213+
214+ if (useProxy && (proxyHost != null && ! proxyHost.isEmpty())) {
215+ if ((username != null && ! username.isEmpty()) &&
216+ (password != null && ! password.isEmpty())) {
217+ proxyAuthenticator = new Authenticator() {
218+ private int proxyCounter = 0;
219+
220+ @Override
221+ public Request authenticate(Route route, Response response) throws IOException {
222+ if (proxyCounter++ > 0) {
223+ if (response.code() == 407) {
224+ throw new HttpRetryException(" Proxy Authentication Missing or Incorrect." , 407);
225+ } else {
226+ throw new IOException(response.message());
227+ }
228+ }
229+
230+ String credential = Credentials.basic(username, password);
231+ return response.request().newBuilder().header("Proxy-Authorization", credential).build();
232+ }
233+ };
234+ } else {
235+ proxyAuthenticator = new Authenticator() {
236+ @Override
237+ public Request authenticate(Route route, Response response) throws IOException {
238+ return response.request().newBuilder().build();
239+ }
240+ };
241+ }
242+
243+ httpClient = new OkHttpClient.Builder()
244+ .connectTimeout(1, TimeUnit.SECONDS)
245+ .writeTimeout(60, TimeUnit.SECONDS)
246+ .readTimeout(60, TimeUnit.SECONDS)
247+ .proxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)))
248+ .proxyAuthenticator(proxyAuthenticator)
249+ .build();
250+
251+ this.setHttpClient(httpClient);
252+ }
253+
200254 this.merchantConfig = merchantConfig;
201255
202256 }
@@ -681,7 +735,7 @@ public class ApiClient {
681735 * @return Timeout in milliseconds
682736 */
683737 public int getConnectTimeout() {
684- return httpClient.getConnectTimeout ();
738+ return httpClient.connectTimeoutMillis ();
685739 }
686740
687741 /**
@@ -693,7 +747,7 @@ public class ApiClient {
693747 * @return Api client
694748 */
695749 public ApiClient setConnectTimeout(int connectionTimeout) {
696- httpClient.setConnectTimeout( connectionTimeout, TimeUnit.MILLISECONDS);
750+ this. httpClient = this.httpClient.newBuilder().connectTimeout( connectionTimeout, TimeUnit.MILLISECONDS).build( );
697751 return this;
698752 }
699753
@@ -891,21 +945,15 @@ public class ApiClient {
891945 */
892946 @SuppressWarnings("unchecked")
893947 public <T > T deserialize(Response response, Type returnType) throws ApiException {
894- if (response == null /* || returnType == null */ ) {
948+ if (response == null) {
895949 return null;
896950 }
897- if (returnType == null && response != null) {
951+
952+ if ((returnType == null && response != null) || ("byte[]".equals(returnType.toString()))) {
898953 try {
899- return (T) response.body().bytes();
900- } catch (IOException e) {
901- throw new ApiException(e);
902- }
903- } else
954+ T respBody = (T) response.body().byteStream();
904955
905- if ("byte[]".equals(returnType.toString())) {
906- // Handle binary response (byte array).
907- try {
908- return (T) response.body().bytes();
956+ return respBody;
909957 } catch (IOException e) {
910958 throw new ApiException(e);
911959 }
@@ -1079,25 +1127,9 @@ public class ApiClient {
10791127 responseCode = String.valueOf(response.code());
10801128 status = response.message();
10811129 String headerType = response.header(" Content-Type" );
1082- if (headerType != null)
1083- if (headerType.equals(" application/xml" ) || headerType.equals(" text/csv" )
1084- || headerType.equals(" application/pdf" )) {
1085- responseBody = response.body().string();
1086- }
1087- if (!(responseCode.equals("200"))) {
1088- if (! responseCode.equals(" 201" )) {
1089- System.out.println(response.body().string());
1090- }
1091- }
1130+
10921131 T data = handleResponse(response, returnType);
10931132
1094- response.body().close();
1095-
1096- if (headerType != null)
1097- if (!headerType.equals("application/xml") && !headerType.equals("text/csv")
1098- && !headerType.equals("application/pdf")) {
1099- responseBody = response.toString();
1100- }
11011133 return new ApiResponse< T> (response.code(), response.headers().toMultimap(), data);
11021134 } catch (IOException e) {
11031135 throw new ApiException(e);
@@ -1135,12 +1167,12 @@ public class ApiClient {
11351167 public <T > void executeAsync(Call call, final Type returnType, final ApiCallback<T > callback) {
11361168 call.enqueue(new Callback() {
11371169 @Override
1138- public void onFailure(Request request , IOException e) {
1170+ public void onFailure(Call call0 , IOException e) {
11391171 callback.onFailure(new ApiException(e), 0, null);
11401172 }
11411173
11421174 @Override
1143- public void onResponse(Response response ) throws IOException {
1175+ public void onResponse(Call call0 ) throws IOException {
11441176 T result;
11451177 try {
11461178 result = (T) handleResponse(response, returnType);
@@ -1170,16 +1202,10 @@ public class ApiClient {
11701202 */
11711203 public <T > T handleResponse(Response response, Type returnType) throws ApiException {
11721204 if (response.isSuccessful()) {
1173- if (/* returnType == null || */ response.code() == 204) {
1174- // returning null if the returnType is not defined,
1175- // or the status code is 204 (No Content)
1205+ if (response.code() == 204) {
11761206 if (response.body() != null) {
1177- try {
11781207 response.body().close();
1179- } catch (IOException e) {
1180- throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap());
11811208 }
1182- }
11831209 return null;
11841210 } else {
11851211 return deserialize(response, returnType);
@@ -1436,6 +1462,8 @@ public class ApiClient {
14361462 reqBuilder.header(header.getKey(), parameterToString(header.getValue()));
14371463 }
14381464 }
1465+
1466+ reqBuilder.header("Connection", "close");
14391467 }
14401468
14411469 /**
@@ -1465,7 +1493,7 @@ public class ApiClient {
14651493 * @return RequestBody
14661494 */
14671495 public RequestBody buildRequestBodyFormEncoding(Map<String , Object > formParams) {
1468- FormEncodingBuilder formBuilder = new FormEncodingBuilder ();
1496+ FormBody.Builder formBuilder = new FormBody.Builder ();
14691497 for (Entry< String, Object> param : formParams.entrySet()) {
14701498 formBuilder.add(param.getKey(), parameterToString(param.getValue()));
14711499 }
@@ -1481,7 +1509,7 @@ public class ApiClient {
14811509 * @return RequestBody
14821510 */
14831511 public RequestBody buildRequestBodyMultipart(Map<String , Object > formParams) {
1484- MultipartBuilder mpBuilder = new MultipartBuilder ().type(MultipartBuilder .FORM);
1512+ MultipartBody.Builder mpBuilder = new MultipartBody.Builder ().setType(MultipartBody .FORM);
14851513 for (Entry< String, Object> param : formParams.entrySet()) {
14861514 if (param.getValue() instanceof File) {
14871515 File file = (File) param.getValue();
@@ -1598,11 +1626,11 @@ public class ApiClient {
15981626 if (keyManagers != null || trustManagers != null) {
15991627 SSLContext sslContext = SSLContext.getInstance("TLS");
16001628 sslContext.init(keyManagers, trustManagers, new SecureRandom());
1601- httpClient.setSslSocketFactory( sslContext.getSocketFactory());
1629+ httpClient = httpClient.newBuilder().sslSocketFactory( sslContext.getSocketFactory()).build( );
16021630 } else {
1603- httpClient.setSslSocketFactory( null);
1631+ httpClient = httpClient.newBuilder().sslSocketFactory( null).build( );
16041632 }
1605- httpClient.setHostnameVerifier( hostnameVerifier);
1633+ httpClient = httpClient.newBuilder(). hostnameVerifier(hostnameVerifier).build( );
16061634 } catch (GeneralSecurityException e) {
16071635 throw new RuntimeException(e);
16081636 }
0 commit comments