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 package org.apache.http.impl.client;
28
29 import java.util.concurrent.Callable;
30 import java.util.concurrent.atomic.AtomicBoolean;
31
32 import org.apache.http.client.HttpClient;
33 import org.apache.http.client.ResponseHandler;
34 import org.apache.http.client.methods.HttpUriRequest;
35 import org.apache.http.concurrent.FutureCallback;
36 import org.apache.http.protocol.HttpContext;
37
38 class HttpRequestTaskCallable<V> implements Callable<V> {
39
40 private final HttpUriRequest request;
41 private final HttpClient httpclient;
42 private final AtomicBoolean cancelled = new AtomicBoolean(false);
43
44 private final long scheduled = System.currentTimeMillis();
45 private long started = -1;
46 private long ended = -1;
47
48 private final HttpContext context;
49 private final ResponseHandler<V> responseHandler;
50 private final FutureCallback<V> callback;
51
52 private final FutureRequestExecutionMetrics metrics;
53
54 HttpRequestTaskCallable(
55 final HttpClient httpClient,
56 final HttpUriRequest request,
57 final HttpContext context,
58 final ResponseHandler<V> responseHandler,
59 final FutureCallback<V> callback,
60 final FutureRequestExecutionMetrics metrics) {
61 this.httpclient = httpClient;
62 this.responseHandler = responseHandler;
63 this.request = request;
64 this.context = context;
65 this.callback = callback;
66 this.metrics = metrics;
67 }
68
69 public long getScheduled() {
70 return scheduled;
71 }
72
73 public long getStarted() {
74 return started;
75 }
76
77 public long getEnded() {
78 return ended;
79 }
80
81 @Override
82 public V call() throws Exception {
83 if (!cancelled.get()) {
84 try {
85 metrics.getActiveConnections().incrementAndGet();
86 started = System.currentTimeMillis();
87 try {
88 metrics.getScheduledConnections().decrementAndGet();
89 final V result = httpclient.execute(request, responseHandler, context);
90 ended = System.currentTimeMillis();
91 metrics.getSuccessfulConnections().increment(started);
92 if (callback != null) {
93 callback.completed(result);
94 }
95 return result;
96 } catch (final Exception e) {
97 metrics.getFailedConnections().increment(started);
98 ended = System.currentTimeMillis();
99 if (callback != null) {
100 callback.failed(e);
101 }
102 throw e;
103 }
104 } finally {
105 metrics.getRequests().increment(started);
106 metrics.getTasks().increment(started);
107 metrics.getActiveConnections().decrementAndGet();
108 }
109 }
110 throw new IllegalStateException("call has been cancelled for request " + request.getURI());
111 }
112
113 public void cancel() {
114 cancelled.set(true);
115 if (callback != null) {
116 callback.cancelled();
117 }
118 }
119 }