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 public void run() {
78 try {
79 final Response response = this.executor.execute(this.request);
80 final T result = response.handleResponse(this.handler);
81 this.future.completed(result);
82 } catch (final Exception ex) {
83 this.future.failed(ex);
84 }
85 }
86
87 }
88
89 public <T> Future<T> execute(
90 final Request request, final ResponseHandler<T> handler, final FutureCallback<T> callback) {
91 final BasicFuture<T> future = new BasicFuture<T>(callback);
92 final ExecRunnable<T> runnable = new ExecRunnable<T>(
93 future,
94 request,
95 this.executor != null ? this.executor : Executor.newInstance(),
96 handler);
97 if (this.concurrentExec != null) {
98 this.concurrentExec.execute(runnable);
99 } else {
100 final Thread t = new Thread(runnable);
101 t.setDaemon(true);
102 t.start();
103 }
104 return future;
105 }
106
107 public <T> Future<T> execute(final Request request, final ResponseHandler<T> handler) {
108 return execute(request, handler, null);
109 }
110
111 public Future<Content> execute(final Request request, final FutureCallback<Content> callback) {
112 return execute(request, new ContentResponseHandler(), callback);
113 }
114
115 public Future<Content> execute(final Request request) {
116 return execute(request, new ContentResponseHandler(), null);
117 }
118
119 }