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