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.client.fluent;
28
29 import java.util.concurrent.Future;
30
31 import org.apache.http.client.ResponseHandler;
32 import org.apache.http.concurrent.BasicFuture;
33 import org.apache.http.concurrent.FutureCallback;
34
35 public class Async {
36
37 private Executor executor;
38 private java.util.concurrent.Executor concurrentExec;
39
40 public static Async newInstance() {
41 return new Async();
42 }
43
44 Async() {
45 super();
46 }
47
48 public Async use(final Executor executor) {
49 this.executor = executor;
50 return this;
51 }
52
53 public Async use(final java.util.concurrent.Executor concurrentExec) {
54 this.concurrentExec = concurrentExec;
55 return this;
56 }
57
58 static class ExecRunnable<T> implements Runnable {
59
60 private final BasicFuture<T> future;
61 private final Request request;
62 private final Executor executor;
63 private final ResponseHandler<T> handler;
64
65 ExecRunnable(
66 final BasicFuture<T> future,
67 final Request request,
68 final Executor executor,
69 final ResponseHandler<T> handler) {
70 super();
71 this.future = future;
72 this.request = request;
73 this.executor = executor;
74 this.handler = handler;
75 }
76
77 @Override
78 public void run() {
79 try {
80 final Response response = this.executor.execute(this.request);
81 final T result = response.handleResponse(this.handler);
82 this.future.completed(result);
83 } catch (final Exception ex) {
84 this.future.failed(ex);
85 }
86 }
87
88 }
89
90 public <T> Future<T> execute(
91 final Request request, final ResponseHandler<T> handler, final FutureCallback<T> callback) {
92 final BasicFuture<T> future = new BasicFuture<T>(callback);
93 final ExecRunnable<T> runnable = new ExecRunnable<T>(
94 future,
95 request,
96 this.executor != null ? this.executor : Executor.newInstance(),
97 handler);
98 if (this.concurrentExec != null) {
99 this.concurrentExec.execute(runnable);
100 } else {
101 final Thread t = new Thread(runnable);
102 t.setDaemon(true);
103 t.start();
104 }
105 return future;
106 }
107
108 public <T> Future<T> execute(final Request request, final ResponseHandler<T> handler) {
109 return execute(request, handler, null);
110 }
111
112 public Future<Content> execute(final Request request, final FutureCallback<Content> callback) {
113 return execute(request, new ContentResponseHandler(), callback);
114 }
115
116 public Future<Content> execute(final Request request) {
117 return execute(request, new ContentResponseHandler(), null);
118 }
119
120 }