groovyx.net.http.AsyncHTTPBuilder Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of http-builder Show documentation
Show all versions of http-builder Show documentation
A builder-style HTTP client API, including authentication, and extensible
handling of common content-types such as JSON and XML. It is built on top of
Apache's HttpClient.
The newest version!
/*
* Copyright 2008-2011 Thomas Nichols. http://blog.thomnichols.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* You are receiving this code free of charge, which represents many hours of
* effort from other individuals and corporations. As a responsible member
* of the community, you are encouraged (but not required) to donate any
* enhancements or improvements back to the community under a similar open
* source license. Thank you. -TMN
*/
package groovyx.net.http;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.apache.http.HttpVersion;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnManagerParams;
import org.apache.http.conn.params.ConnPerRouteBean;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
/**
* This implementation makes all requests asynchronous by submitting jobs to a
* {@link ThreadPoolExecutor}. All request methods (including get
* and post
) return a {@link Future} instance, whose
* {@link Future#get() get} method will provide access to whatever value was
* returned from the response handler closure.
*
* @author Tom Nichols
*/
public class AsyncHTTPBuilder extends HTTPBuilder {
/**
* Default pool size is one is not supplied in the constructor.
*/
public static final int DEFAULT_POOL_SIZE = 4;
protected ExecutorService threadPool;
// = (ThreadPoolExecutor)Executors.newCachedThreadPool();
/**
* Accepts the following named parameters:
*
* - threadPool
- Custom {@link ExecutorService} instance for
* running submitted requests. If this is an instance of {@link ThreadPoolExecutor},
* the poolSize will be determined by {@link ThreadPoolExecutor#getMaximumPoolSize()}.
* The default threadPool uses an unbounded queue to accept an unlimited
* number of requests.
* - poolSize
- Max number of concurrent requests
* - uri
- Default request URI
* - contentType
- Default content type for requests and responses
* - timeout
- Timeout in milliseconds to wait for a connection to
* be established and request to complete.
*
*/
public AsyncHTTPBuilder( Map args ) throws URISyntaxException {
int poolSize = DEFAULT_POOL_SIZE;
ExecutorService threadPool = null;
if ( args != null ) {
threadPool = (ExecutorService)args.remove( "threadPool" );
if ( threadPool instanceof ThreadPoolExecutor )
poolSize = ((ThreadPoolExecutor)threadPool).getMaximumPoolSize();
Object poolSzArg = args.remove("poolSize");
if ( poolSzArg != null ) poolSize = Integer.parseInt( poolSzArg.toString() );
if ( args.containsKey( "url" ) ) throw new IllegalArgumentException(
"The 'url' parameter is deprecated; use 'uri' instead" );
Object defaultURI = args.remove("uri");
if ( defaultURI != null ) super.setUri(defaultURI);
Object defaultContentType = args.remove("contentType");
if ( defaultContentType != null )
super.setContentType(defaultContentType);
Object timeout = args.remove( "timeout" );
if ( timeout != null ) setTimeout( (Integer) timeout );
if ( args.size() > 0 ) {
String invalidArgs = "";
for ( String k : args.keySet() ) invalidArgs += k + ",";
throw new IllegalArgumentException("Unexpected keyword args: " + invalidArgs);
}
}
this.initThreadPools( poolSize, threadPool );
}
/**
* Submits a {@link Callable} instance to the job pool, which in turn will
* call {@link HTTPBuilder#doRequest(RequestConfigDelegate)} in an asynchronous
* thread. The {@link Future} instance returned by this value (which in
* turn should be returned by any of the public request
methods
* (including get
and post
) may be used to
* retrieve whatever value may be returned from the executed response
* handler closure.
*/
@Override
protected Future> doRequest( final RequestConfigDelegate delegate ) {
return threadPool.submit( new Callable