-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathHttpClient.java
More file actions
189 lines (174 loc) · 7.67 KB
/
HttpClient.java
File metadata and controls
189 lines (174 loc) · 7.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package com.gocardless.http;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import com.github.rholder.retry.*;
import com.gocardless.GoCardlessException;
import com.gocardless.errors.GoCardlessInternalException;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import okhttp3.*;
/**
* An HTTP client that can execute {@link ApiRequest}s.
*
* Users of this library should not need to access this class directly.
*/
public class HttpClient {
/**
* The maximum number of times that a request can be retried.
*/
public static final int MAX_RETRIES = 3;
/**
* The amount of time to wait before retrying a failed request in milli seconds
*/
public static final long WAIT_BETWEEN_RETRIES_IN_MILLI_SECONDS = 500;
/**
* See http://tools.ietf.org/html/rfc7230#section-3.2.6.
*/
private static final String DISALLOWED_USER_AGENT_CHARACTERS =
"[^\\w!#$%&'\\*\\+\\-\\.\\^`\\|~]";
private static final String USER_AGENT =
String.format("gocardless-pro-java/8.2.0 java/%s %s/%s %s/%s",
cleanUserAgentToken(System.getProperty("java.vm.specification.version")),
cleanUserAgentToken(System.getProperty("java.vm.name")),
cleanUserAgentToken(System.getProperty("java.version")),
cleanUserAgentToken(System.getProperty("os.name")),
cleanUserAgentToken(System.getProperty("os.version")));
private static final RequestBody EMPTY_BODY = RequestBody.create(null, new byte[0]);
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json");
private static final Map<String, String> HEADERS;
static {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
builder.put("GoCardless-Version", "2015-07-06");
builder.put("Accept", "application/json");
builder.put("GoCardless-Client-Library", "gocardless-pro-java");
builder.put("GoCardless-Client-Version", "8.2.0");
HEADERS = builder.build();
}
private final OkHttpClient rawClient;
private final UrlFormatter urlFormatter;
private final ResponseParser responseParser;
private final RequestWriter requestWriter;
private final String credentials;
private final boolean errorOnIdempotencyConflict;
private final int maxNoOfRetries;
private final long waitBetweenRetriesInMilliSeconds;
/**
* Constructor. Users of this library should not need to access this class directly - you should
* instantiate a GoCardlessClient and its underlying HttpClient using
* GoCardlessClient.newBuilder().
*
* @param accessToken the access token.
* @param baseUrl base URI to make requests against.
* @param rawClient the OkHttpClient instance to use to make requests (which will be configured
* to log requests with LoggingInterceptor).
*/
public HttpClient(String accessToken, String baseUrl, OkHttpClient rawClient,
boolean errorOnIdempotencyConflict, int maxNoOfRetries,
long waitBetweenRetriesInMilliSeconds) {
this.rawClient = rawClient;
this.urlFormatter = new UrlFormatter(baseUrl);
Gson gson = GsonFactory.build();
this.responseParser = new ResponseParser(gson);
this.requestWriter = new RequestWriter(gson);
this.credentials = String.format("Bearer %s", accessToken);
this.errorOnIdempotencyConflict = errorOnIdempotencyConflict;
this.maxNoOfRetries = maxNoOfRetries;
this.waitBetweenRetriesInMilliSeconds = waitBetweenRetriesInMilliSeconds;
}
public boolean isErrorOnIdempotencyConflict() {
return this.errorOnIdempotencyConflict;
}
@VisibleForTesting
public int getMaxNoOfRetries() {
return this.maxNoOfRetries;
}
<T> T execute(ApiRequest<T> apiRequest) {
Request request = buildRequest(apiRequest);
Response response = execute(request);
return parseResponseBody(apiRequest, response);
}
<T> ApiResponse<T> executeWrapped(ApiRequest<T> apiRequest) {
Request request = buildRequest(apiRequest);
Response response = execute(request);
T resource = parseResponseBody(apiRequest, response);
return new ApiResponse<>(resource, response.code(), response.headers().toMultimap());
}
<T> T executeWithRetries(final ApiRequest<T> apiRequest) {
Retryer<T> retrier = RetryerBuilder.<T>newBuilder()
.retryIfExceptionOfType(GoCardlessNetworkException.class)
.retryIfExceptionOfType(GoCardlessInternalException.class)
.withWaitStrategy(WaitStrategies.fixedWait(this.waitBetweenRetriesInMilliSeconds,
MILLISECONDS))
.withStopStrategy(StopStrategies.stopAfterAttempt(this.maxNoOfRetries)).build();
Callable<T> executeOnce = new Callable<T>() {
@Override
public T call() throws Exception {
return execute(apiRequest);
}
};
try {
return retrier.call(executeOnce);
} catch (ExecutionException | RetryException e) {
Throwable cause = e.getCause();
throw Throwables.propagate(cause);
}
}
private <T> Request buildRequest(ApiRequest<T> apiRequest) {
HttpUrl url = apiRequest.getUrl(urlFormatter);
Request.Builder request =
new Request.Builder().url(url).headers(Headers.of(apiRequest.getHeaders()))
.header("Authorization", credentials).header("User-Agent", USER_AGENT)
.method(apiRequest.getMethod(), getBody(apiRequest));
for (Map.Entry<String, String> entry : HEADERS.entrySet()) {
request = request.header(entry.getKey(), entry.getValue());
}
return request.build();
}
private <T> RequestBody getBody(ApiRequest<T> request) {
if (!request.hasBody()) {
if (request.getMethod().equals("GET")) {
return null;
} else {
return EMPTY_BODY;
}
}
String json = requestWriter.write(request, request.getRequestEnvelope());
return RequestBody.create(MEDIA_TYPE, json);
}
private Response execute(Request request) {
Response response;
try {
response = rawClient.newCall(request).execute();
} catch (IOException e) {
throw new GoCardlessNetworkException("Failed to execute request", e);
}
if (!response.isSuccessful()) {
throw handleErrorResponse(response);
}
return response;
}
private <T> T parseResponseBody(ApiRequest<T> request, Response response) {
try {
String responseBody = response.body().string();
return request.parseResponse(responseBody, responseParser);
} catch (IOException e) {
throw new GoCardlessNetworkException("Failed to read response body", e);
}
}
private GoCardlessException handleErrorResponse(Response response) {
try {
String responseBody = response.body().string();
return responseParser.parseError(responseBody, response.code());
} catch (IOException e) {
throw new GoCardlessNetworkException("Failed to read response body", e);
}
}
private static String cleanUserAgentToken(String s) {
return s.replaceAll(DISALLOWED_USER_AGENT_CHARACTERS, "_");
}
}