-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
DefaultAsyncHttpClient.java
308 lines (265 loc) · 10 KB
/
DefaultAsyncHttpClient.java
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*
* Copyright 2010 Ning, Inc.
*
* This program is licensed to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
*/
package org.asynchttpclient;
import io.netty.channel.EventLoopGroup;
import io.netty.handler.codec.http.cookie.Cookie;
import io.netty.util.HashedWheelTimer;
import io.netty.util.Timer;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.asynchttpclient.channel.ChannelPool;
import org.asynchttpclient.cookie.CookieEvictionTask;
import org.asynchttpclient.filter.FilterContext;
import org.asynchttpclient.filter.FilterException;
import org.asynchttpclient.filter.RequestFilter;
import org.asynchttpclient.handler.resumable.ResumableAsyncHandler;
import org.asynchttpclient.netty.channel.ChannelManager;
import org.asynchttpclient.netty.request.NettyRequestSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Predicate;
import static org.asynchttpclient.util.Assertions.assertNotNull;
/**
* Default and threadsafe implementation of {@link AsyncHttpClient}.
*/
public class DefaultAsyncHttpClient implements AsyncHttpClient {
private final static Logger LOGGER = LoggerFactory.getLogger(DefaultAsyncHttpClient.class);
private final AsyncHttpClientConfig config;
private final boolean noRequestFilters;
private final AtomicBoolean closed = new AtomicBoolean(false);
private final ChannelManager channelManager;
private final NettyRequestSender requestSender;
private final boolean allowStopNettyTimer;
private final Timer nettyTimer;
/**
* Default signature calculator to use for all requests constructed by this
* client instance.
*/
private SignatureCalculator signatureCalculator;
/**
* Create a new HTTP Asynchronous Client using the default
* {@link DefaultAsyncHttpClientConfig} configuration. The default
* {@link AsyncHttpClient} that will be used will be based on the classpath
* configuration.
* <p>
* If none of those providers are found, then the engine will throw an
* IllegalStateException.
*/
public DefaultAsyncHttpClient() {
this(new DefaultAsyncHttpClientConfig.Builder().build());
}
/**
* Create a new HTTP Asynchronous Client using the specified
* {@link DefaultAsyncHttpClientConfig} configuration. This configuration
* will be passed to the default {@link AsyncHttpClient} that will be
* selected based on the classpath configuration.
*
* @param config a {@link DefaultAsyncHttpClientConfig}
*/
public DefaultAsyncHttpClient(AsyncHttpClientConfig config) {
this.config = config;
this.noRequestFilters = config.getRequestFilters().isEmpty();
allowStopNettyTimer = config.getNettyTimer() == null;
nettyTimer = allowStopNettyTimer ? newNettyTimer(config) : config.getNettyTimer();
channelManager = new ChannelManager(config, nettyTimer);
requestSender = new NettyRequestSender(config, channelManager, nettyTimer, new AsyncHttpClientState(closed));
channelManager.configureBootstraps(requestSender);
nettyTimer.newTimeout(new CookieEvictionTask(config.expiredCookieEvictionDelay(), config.getCookieStore()),
config.expiredCookieEvictionDelay(), TimeUnit.MILLISECONDS);
}
private Timer newNettyTimer(AsyncHttpClientConfig config) {
ThreadFactory threadFactory = config.getThreadFactory() != null ? config.getThreadFactory() : new DefaultThreadFactory(config.getThreadPoolName() + "-timer");
HashedWheelTimer timer = new HashedWheelTimer(threadFactory, config.getHashedWheelTimerTickDuration(), TimeUnit.MILLISECONDS, config.getHashedWheelTimerSize());
timer.start();
return timer;
}
@Override
public void close() {
if (closed.compareAndSet(false, true)) {
try {
channelManager.close();
} catch (Throwable t) {
LOGGER.warn("Unexpected error on ChannelManager close", t);
}
if (allowStopNettyTimer) {
try {
nettyTimer.stop();
} catch (Throwable t) {
LOGGER.warn("Unexpected error on HashedWheelTimer close", t);
}
}
}
}
@Override
public boolean isClosed() {
return closed.get();
}
@Override
public DefaultAsyncHttpClient setSignatureCalculator(SignatureCalculator signatureCalculator) {
this.signatureCalculator = signatureCalculator;
return this;
}
@Override
public BoundRequestBuilder prepare(String method, String url) {
return requestBuilder(method, url);
}
@Override
public BoundRequestBuilder prepareGet(String url) {
return requestBuilder("GET", url);
}
@Override
public BoundRequestBuilder prepareConnect(String url) {
return requestBuilder("CONNECT", url);
}
@Override
public BoundRequestBuilder prepareOptions(String url) {
return requestBuilder("OPTIONS", url);
}
@Override
public BoundRequestBuilder prepareHead(String url) {
return requestBuilder("HEAD", url);
}
@Override
public BoundRequestBuilder preparePost(String url) {
return requestBuilder("POST", url);
}
@Override
public BoundRequestBuilder preparePut(String url) {
return requestBuilder("PUT", url);
}
@Override
public BoundRequestBuilder prepareDelete(String url) {
return requestBuilder("DELETE", url);
}
@Override
public BoundRequestBuilder preparePatch(String url) {
return requestBuilder("PATCH", url);
}
@Override
public BoundRequestBuilder prepareTrace(String url) {
return requestBuilder("TRACE", url);
}
@Override
public BoundRequestBuilder prepareRequest(Request request) {
return requestBuilder(request);
}
@Override
public BoundRequestBuilder prepareRequest(RequestBuilder requestBuilder) {
return prepareRequest(requestBuilder.build());
}
@Override
public <T> ListenableFuture<T> executeRequest(Request request, AsyncHandler<T> handler) {
if (config.getCookieStore() != null) {
try {
List<Cookie> cookies = config.getCookieStore().get(request.getUri());
if (!cookies.isEmpty()) {
RequestBuilder requestBuilder = request.toBuilder();
for (Cookie cookie : cookies) {
requestBuilder.addOrReplaceCookie(cookie);
}
request = requestBuilder.build();
}
} catch (Exception e) {
handler.onThrowable(e);
return new ListenableFuture.CompletedFailure<>("Failed to set cookies of request", e);
}
}
if (noRequestFilters) {
return execute(request, handler);
} else {
FilterContext<T> fc = new FilterContext.FilterContextBuilder<T>().asyncHandler(handler).request(request).build();
try {
fc = preProcessRequest(fc);
} catch (Exception e) {
handler.onThrowable(e);
return new ListenableFuture.CompletedFailure<>("preProcessRequest failed", e);
}
return execute(fc.getRequest(), fc.getAsyncHandler());
}
}
@Override
public <T> ListenableFuture<T> executeRequest(RequestBuilder requestBuilder, AsyncHandler<T> handler) {
return executeRequest(requestBuilder.build(), handler);
}
@Override
public ListenableFuture<Response> executeRequest(Request request) {
return executeRequest(request, new AsyncCompletionHandlerBase());
}
@Override
public ListenableFuture<Response> executeRequest(RequestBuilder requestBuilder) {
return executeRequest(requestBuilder.build());
}
private <T> ListenableFuture<T> execute(Request request, final AsyncHandler<T> asyncHandler) {
try {
return requestSender.sendRequest(request, asyncHandler, null);
} catch (Exception e) {
asyncHandler.onThrowable(e);
return new ListenableFuture.CompletedFailure<>(e);
}
}
/**
* Configure and execute the associated {@link RequestFilter}. This class
* may decorate the {@link Request} and {@link AsyncHandler}
*
* @param fc {@link FilterContext}
* @return {@link FilterContext}
*/
private <T> FilterContext<T> preProcessRequest(FilterContext<T> fc) throws FilterException {
for (RequestFilter asyncFilter : config.getRequestFilters()) {
fc = asyncFilter.filter(fc);
assertNotNull(fc, "filterContext");
}
Request request = fc.getRequest();
if (fc.getAsyncHandler() instanceof ResumableAsyncHandler) {
request = ResumableAsyncHandler.class.cast(fc.getAsyncHandler()).adjustRequestRange(request);
}
if (request.getRangeOffset() != 0) {
RequestBuilder builder = request.toBuilder();
builder.setHeader("Range", "bytes=" + request.getRangeOffset() + "-");
request = builder.build();
}
fc = new FilterContext.FilterContextBuilder<>(fc).request(request).build();
return fc;
}
public ChannelPool getChannelPool() {
return channelManager.getChannelPool();
}
public EventLoopGroup getEventLoopGroup() {
return channelManager.getEventLoopGroup();
}
@Override
public ClientStats getClientStats() {
return channelManager.getClientStats();
}
@Override
public void flushChannelPoolPartitions(Predicate<Object> predicate) {
getChannelPool().flushPartitions(predicate);
}
protected BoundRequestBuilder requestBuilder(String method, String url) {
return new BoundRequestBuilder(this, method, config.isDisableUrlEncodingForBoundRequests()).setUrl(url).setSignatureCalculator(signatureCalculator);
}
protected BoundRequestBuilder requestBuilder(Request prototype) {
return new BoundRequestBuilder(this, prototype).setSignatureCalculator(signatureCalculator);
}
@Override
public AsyncHttpClientConfig getConfig() {
return this.config;
}
}