diff --git a/src/main/java/io/ljunggren/fedex/api/service/BaseService.java b/src/main/java/io/ljunggren/fedex/api/service/BaseService.java index ffb10d4..784735d 100644 --- a/src/main/java/io/ljunggren/fedex/api/service/BaseService.java +++ b/src/main/java/io/ljunggren/fedex/api/service/BaseService.java @@ -29,6 +29,9 @@ 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) { @@ -41,7 +44,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/fedex/api/service/OauthService.java b/src/main/java/io/ljunggren/fedex/api/service/OauthService.java index 83d1806..083cedf 100644 --- a/src/main/java/io/ljunggren/fedex/api/service/OauthService.java +++ b/src/main/java/io/ljunggren/fedex/api/service/OauthService.java @@ -1,5 +1,6 @@ package io.ljunggren.fedex.api.service; +import java.io.IOException; import java.util.Arrays; import java.util.List; @@ -14,29 +15,41 @@ import io.ljunggren.fedex.api.model.Debug; 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); } private final String URI = domain + "/oauth/token"; - + public AuthToken authorize(String clientId, String clientSecret) throws Exception { return authorize(clientId, clientSecret, getHttpClient()); } - + public AuthToken authorize(String clientId, String clientSecret, CloseableHttpClient httpClient) throws Exception { HttpPost post = new HttpPost(URI); List parameters = generateParameters(clientId, clientSecret); + post.setEntity(new UrlEncodedFormEntity(parameters)); + IOException lastFailure = null; try { - post.setEntity(new UrlEncodedFormEntity(parameters)); - try (CloseableHttpResponse response = httpClient.execute(post)) { - String json = getResult(response); - return parse(json, AuthToken.class); + for (int attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try (CloseableHttpResponse response = httpClient.execute(post)) { + String json = getResult(response); + return parse(json, AuthToken.class); + } catch (IOException e) { + lastFailure = e; + if (attempt < MAX_ATTEMPTS) { + Thread.sleep(RETRY_BACKOFF_MS * attempt); + } + } } } finally { httpClient.close(); } + throw lastFailure; } public Debug debug(String clientId, String clientSecret) throws Exception {