jp.gopay.sdk.utils.GoPayClient Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of gopay-java-sdk Show documentation
Show all versions of gopay-java-sdk Show documentation
Official Gyro-n Payments Java SDK
package jp.gopay.sdk.utils;
import jp.gopay.sdk.models.common.auth.AuthHeader;
import jp.gopay.sdk.models.common.auth.AuthStrategy;
import jp.gopay.sdk.models.common.auth.LoginJWTStrategy;
import jp.gopay.sdk.settings.AbstractSDKSettings;
import jp.gopay.sdk.types.AuthType;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class GoPayClient {
public static final String AUTHORIZATION_HEADER_NAME = "Authorization";
public static final String ORIGIN_HEADER_NAME = "Origin";
public static OkHttpClient.Builder getDefaultClientBuilder(final AuthStrategy authStrategy, final AbstractSDKSettings settings) {
return new OkHttpClient
.Builder()
.connectTimeout(settings.getTimeout(), TimeUnit.SECONDS)
.readTimeout(settings.getTimeout(), TimeUnit.SECONDS)
.writeTimeout(settings.getTimeout(), TimeUnit.SECONDS)
.addInterceptor(
new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder();
AuthHeader authHeader = authStrategy.getAuthHeader();
if(!authHeader.getAuthType().equals(AuthType.NO_AUTH_HEADER)){
requestBuilder.addHeader(AUTHORIZATION_HEADER_NAME, authHeader.getValue());
}
if (!settings.getOrigin().isEmpty()) {
requestBuilder.addHeader(ORIGIN_HEADER_NAME, settings.getOrigin());
}
Request request = requestBuilder.build();
Response response = chain.proceed(request);
/*
* If the client is currently using a Login JWT for authentication, replace the soon-to-expire
* token with the refresh token sent by the API in the response's Authorization header.
*/
if(LoginJWTStrategy.class.isInstance(authStrategy)){
List refreshTokenHeader = response.headers(AUTHORIZATION_HEADER_NAME);
if(!(refreshTokenHeader == null || refreshTokenHeader.isEmpty())){
String refreshToken = AuthHeader.parseValueFromJWTHeader(refreshTokenHeader.get(0));
((LoginJWTStrategy)authStrategy).refresh(refreshToken);
}
}
return response;
}
}
);
}
}