diff --git a/src/main/java/io/ljunggren/ups/api/service/BaseService.java b/src/main/java/io/ljunggren/ups/api/service/BaseService.java index b8676c9..b2031a8 100644 --- a/src/main/java/io/ljunggren/ups/api/service/BaseService.java +++ b/src/main/java/io/ljunggren/ups/api/service/BaseService.java @@ -29,8 +29,11 @@ public class BaseService { + protected static final int CONNECT_TIMEOUT_MS = 5000; + protected static final int SOCKET_TIMEOUT_MS = 15000; + protected String domain; - + protected BaseService(String domain) { this.domain = domain; } @@ -38,7 +41,11 @@ protected CloseableHttpClient getHttpClient() { return HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom() - .setCookieSpec(CookieSpecs.STANDARD).build()) + .setCookieSpec(CookieSpecs.STANDARD) + .setConnectTimeout(CONNECT_TIMEOUT_MS) + .setConnectionRequestTimeout(CONNECT_TIMEOUT_MS) + .setSocketTimeout(SOCKET_TIMEOUT_MS) + .build()) .build(); } diff --git a/src/main/java/io/ljunggren/ups/api/service/OauthService.java b/src/main/java/io/ljunggren/ups/api/service/OauthService.java index 28394d1..338969a 100644 --- a/src/main/java/io/ljunggren/ups/api/service/OauthService.java +++ b/src/main/java/io/ljunggren/ups/api/service/OauthService.java @@ -1,5 +1,6 @@ package io.ljunggren.ups.api.service; +import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.Base64; @@ -20,6 +21,9 @@ public class OauthService extends BaseService { + private static final int MAX_ATTEMPTS = 3; + private static final long RETRY_BACKOFF_MS = 1000; + public OauthService(String domain) { super(domain); } @@ -28,16 +32,31 @@ public AuthToken getAuthToken(String clientId, String clientSecret, String accountNumber) throws Exception { return getAuthToken(clientId, clientSecret, accountNumber, getHttpClient()); } - + public AuthToken getAuthToken(String clientId, String clientSecret, String accountNumber, CloseableHttpClient httpClient) throws Exception { HttpPost post = new HttpPost(URI); Header[] headers = generateHeaders(clientId, clientSecret, accountNumber); post.setHeaders(headers); post.setEntity(generateAuthEntity()); - try (httpClient; CloseableHttpResponse response = httpClient.execute(post)) { - String json = getResult(response); - return JsonUtils.jsonToObject(json, AuthToken.class); + IOException lastFailure = null; + try (httpClient) { + for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try (CloseableHttpResponse response = httpClient.execute(post)) { + String json = getResult(response); + return JsonUtils.jsonToObject(json, AuthToken.class); + } catch (IOException e) { + lastFailure = e; + if (attempt < MAX_ATTEMPTS) { + sleep(attempt); + } + } + } } + throw lastFailure; + } + + private void sleep(int attempt) throws InterruptedException { + Thread.sleep(RETRY_BACKOFF_MS * attempt); } public Debug debug(String clientId, String clientSecret, String accountNumber) throws Exception {