1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 package groovyx.net.http;
23
24 import java.io.IOException;
25 import java.net.URISyntaxException;
26 import java.util.Map;
27 import java.util.concurrent.Callable;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ExecutorService;
30 import java.util.concurrent.Future;
31 import java.util.concurrent.LinkedBlockingQueue;
32 import java.util.concurrent.ThreadPoolExecutor;
33 import java.util.concurrent.TimeUnit;
34
35 import org.apache.http.HttpVersion;
36 import org.apache.http.conn.ClientConnectionManager;
37 import org.apache.http.conn.params.ConnManagerParams;
38 import org.apache.http.conn.params.ConnPerRouteBean;
39 import org.apache.http.conn.scheme.PlainSocketFactory;
40 import org.apache.http.conn.scheme.Scheme;
41 import org.apache.http.conn.scheme.SchemeRegistry;
42 import org.apache.http.conn.ssl.SSLSocketFactory;
43 import org.apache.http.impl.client.DefaultHttpClient;
44 import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
45 import org.apache.http.params.BasicHttpParams;
46 import org.apache.http.params.HttpConnectionParams;
47 import org.apache.http.params.HttpParams;
48 import org.apache.http.params.HttpProtocolParams;
49
50
51
52
53
54
55
56
57
58
59 public class AsyncHTTPBuilder extends HTTPBuilder {
60
61
62
63
64 public static final int DEFAULT_POOL_SIZE = 4;
65
66 protected ExecutorService threadPool;
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84 public AsyncHTTPBuilder( Map<String, ?> args ) throws URISyntaxException {
85 super();
86 int poolSize = DEFAULT_POOL_SIZE;
87 ExecutorService threadPool = null;
88 if ( args != null ) {
89 threadPool = (ExecutorService)args.remove( "threadPool" );
90
91 if ( threadPool instanceof ThreadPoolExecutor )
92 poolSize = ((ThreadPoolExecutor)threadPool).getMaximumPoolSize();
93
94 Object poolSzArg = args.remove("poolSize");
95 if ( poolSzArg != null ) poolSize = Integer.parseInt( poolSzArg.toString() );
96
97 if ( args.containsKey( "url" ) ) throw new IllegalArgumentException(
98 "The 'url' parameter is deprecated; use 'uri' instead" );
99 Object defaultURI = args.remove("uri");
100 if ( defaultURI != null ) super.setUri(defaultURI);
101
102 Object defaultContentType = args.remove("contentType");
103 if ( defaultContentType != null )
104 super.setContentType(defaultContentType);
105
106 Object timeout = args.remove( "timeout" );
107 if ( timeout != null ) setTimeout( (Integer) timeout );
108
109 if ( args.size() > 0 ) {
110 String invalidArgs = "";
111 for ( String k : args.keySet() ) invalidArgs += k + ",";
112 throw new IllegalArgumentException("Unexpected keyword args: " + invalidArgs);
113 }
114 }
115 this.initThreadPools( poolSize, threadPool );
116 }
117
118
119
120
121
122
123
124
125
126
127 @Override
128 protected Future<?> doRequest( final RequestConfigDelegate delegate ) {
129 return threadPool.submit( new Callable<Object>() {
130
131 try {
132 return doRequestSuper(delegate);
133 }
134 catch( Exception ex ) {
135 log.info( "Exception thrown from response delegate: " + delegate, ex );
136 throw ex;
137 }
138 }
139 });
140 }
141
142
143
144
145
146 private Object doRequestSuper( RequestConfigDelegate delegate ) throws IOException {
147 return super.doRequest(delegate);
148 }
149
150
151
152
153
154 protected void initThreadPools( final int poolSize, final ExecutorService threadPool ) {
155 if (poolSize < 1) throw new IllegalArgumentException("poolSize may not be < 1");
156
157 HttpParams params = client != null ? client.getParams()
158 : new BasicHttpParams();
159 ConnManagerParams.setMaxTotalConnections(params, poolSize);
160 ConnManagerParams.setMaxConnectionsPerRoute(params,
161 new ConnPerRouteBean(poolSize));
162
163 HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
164
165
166 SchemeRegistry schemeRegistry = new SchemeRegistry();
167 schemeRegistry.register( new Scheme( "http",
168 PlainSocketFactory.getSocketFactory(), 80 ) );
169 schemeRegistry.register( new Scheme( "https",
170 SSLSocketFactory.getSocketFactory(), 443));
171
172 ClientConnectionManager cm = new ThreadSafeClientConnManager(
173 params, schemeRegistry );
174 super.client = new DefaultHttpClient( cm, params );
175
176 this.threadPool = threadPool != null ? threadPool :
177 new ThreadPoolExecutor( poolSize, poolSize, 120, TimeUnit.SECONDS,
178 new LinkedBlockingQueue<Runnable>() );
179 }
180
181
182
183
184 @Override
185 protected Object defaultSuccessHandler( HttpResponseDecorator resp, Object parsedData )
186 throws ResponseParseException {
187 return super.defaultSuccessHandler( resp, parsedData );
188 }
189
190
191
192
193
194
195
196
197
198 @Override
199 protected void defaultFailureHandler( HttpResponseDecorator resp )
200 throws HttpResponseException {
201 super.defaultFailureHandler( resp );
202 }
203
204
205
206
207
208
209
210
211 public void setTimeout( int timeout ) {
212 HttpConnectionParams.setConnectionTimeout( super.getClient().getParams(), timeout );
213 HttpConnectionParams.setSoTimeout( super.getClient().getParams(), timeout );
214
215
216
217 }
218
219
220
221
222
223 public int getTimeout() {
224 return HttpConnectionParams.getConnectionTimeout( super.getClient().getParams() );
225 }
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240 public ExecutorService getThreadExecutor() {
241 return this.threadPool;
242 }
243
244
245
246
247 @Override public void shutdown() {
248 super.shutdown();
249 this.threadPool.shutdown();
250 }
251
252
253
254
255
256 @Override protected void finalize() throws Throwable {
257 this.shutdown();
258 super.finalize();
259 }
260 }