Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
jerry-http - Common Java Functionality Copyright (c) 2012-2014, Sandeep Gupta http://sangupta.com/projects/jerry-http 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.
 
 
 package com.sangupta.jerry.http;
 
 
 
 
Global static HTTP executor that configures and maintains the Apache HTTP client connection managers and all to work with HTTP requests.

Author(s):
sangupta
Since:
0.3
 
 public class HttpExecutor {

    
Create an HttpClient with the PoolingClientConnectionManager. This connection manager must be used if more than one thread will be using the HttpClient.
 
The singleton instance of HttpClient
 
 	public static final HttpClient HTTP_CLIENT;

Build up the default instance
 
 	static {
         SchemeRegistry schemeRegistry = new SchemeRegistry();
         SchemeSocketFactory plain = PlainSocketFactory.getSocketFactory();
         schemeRegistry.register(new Scheme("http", 80, plain));
         SchemeSocketFactory ssl = null;
         
         try {
             ssl = SSLSocketFactory.getSystemSocketFactory();
         } catch (SSLInitializationException ex) {
             SSLContext sslcontext;
            try {
                sslcontext = SSLContext.getInstance(.);
                sslcontext.init(nullnew TrustManager[] {
                		
                		// make sure that we accept all SSL certificates
                		new X509TrustManager() {
								return null;
							}
							public void checkServerTrusted(X509Certificate[] arg0String arg1throws CertificateException {
							}
							public void checkClientTrusted(X509Certificate[] arg0String arg1throws CertificateException {
							}
						}
                		
                }, null);
                ssl = new SSLSocketFactory(sslcontext);
            } catch (SecurityException ignore) {
            	// do nothing
            } catch (KeyManagementException ignore) {
            	// do nothing
            } catch (NoSuchAlgorithmException ignore) {
            	// do nothing
            }
        }
        
        if (ssl != null) {
            schemeRegistry.register(new Scheme("https", 443, ssl));
        }
        
        CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager().build();
         = new HttpRateLimitingClient(closeableHttpClient);
        
	}

Default HttpExecutor instance that can be used across application
	public static final HttpExecutor DEFAULT = new HttpExecutor();

Return the underlying org.apache.http.client.HttpClient instance that can be used to make web requests. All requests shot using this client honor rate-limiting.

Returns:
the enclosed org.apache.http.client.HttpClient instance
	public static final HttpClient getHttpClient() {
		return ;
	}

Get a new HttpExecutor instance based on the underlying org.apache.http.client.HttpClient.

Returns:
a new HttpExecutor instance
	public static final HttpExecutor newInstance() {
	}

Get a new HttpExecutor instance based on given org.apache.http.client.HttpClient instance

Parameters:
client the org.apache.http.client.HttpClient to use
Returns:
a new HttpExecutor instance
Throws:
java.lang.IllegalArgumentException if the given org.apache.http.client.HttpClient is null
	public static final HttpExecutor newInstance(HttpClient client) {
		if(client == null) {
			throw new IllegalArgumentException("HttpClient instance cannot be null");
		}
		return new HttpExecutor(client);
	}

Set overall maximum connections that can be handled by the underlying connection manager.

Parameters:
numConnections the number of connections to set
Throws:
java.lang.IllegalArgumentException if the number of connections is less than 1
	public static void setMaxConnections(int numConnections) {
		if(numConnections < 1) {
			throw new IllegalArgumentException("Number of connections cannot be less than 1");
		}
	}

Set overall maximum connections per route (over all hosts) that can be handled by the underlying connection manager.

Parameters:
numConnections the number of connections to set
Throws:
java.lang.IllegalArgumentException if the number of connections is less than 1
	public static void setMaxConnectionsPerRoute(int numConnections) {
		if(numConnections < 1) {
			throw new IllegalArgumentException("Number of connections cannot be less than 1");
		}
	}

Set maximum connections that will be operated over the given route, that will be handled by the underlying connection manager.

Parameters:
route the org.apache.http.conn.routing.HttpRoute on which to set maximum connections
numConnections the number of connections to set
Throws:
java.lang.IllegalArgumentException if the number of connections is less than ZERO
	public static void setMaxConnectionsOnHost(HttpRoute routeint numConnections) {
		if(numConnections < 0) {
			throw new IllegalArgumentException("Number of connections cannot be less than 1");
		}
		.setMaxPerRoute(routenumConnections);
	}

Set maximum connections that will be operated over the given host on port 80, that will be handled by the underlying connection manager.

Parameters:
hostName the host name for which the limit needs to be set
numConnections the number of connections to set
Throws:
java.lang.IllegalArgumentException if the number of connections is less than ZERO
java.lang.IllegalArgumentException if the host name is null or empty.
	public static void setMaxConnectionsOnHost(String hostNameint numConnections) {
		if(AssertUtils.isEmpty(hostName)) {
			throw new IllegalArgumentException("Hostname cannot be null/empty");
		}
		HttpRoute route = new HttpRoute(new HttpHost(hostName));
		setMaxConnectionsOnHost(routenumConnections);
	}

Set maximum connections that will be operated over the given host on given port, that will be handled by the underlying connection manager.

Parameters:
hostName the host name for which the limit needs to be set
port the port on which the limit needs to be set
numConnections the number of connections to set
Throws:
java.lang.IllegalArgumentException if the number of connections is less than ZERO
java.lang.IllegalArgumentException if the host name is null or empty.
	public static void setMaxConnectionsOnHost(String hostNameint portint numConnections) {
		if(AssertUtils.isEmpty(hostName)) {
			throw new IllegalArgumentException("Hostname cannot be null/empty");
		}
		HttpRoute route = new HttpRoute(new HttpHost(hostNameport));
		setMaxConnectionsOnHost(routenumConnections);
	}
	// Instance class starts from here
The underlying org.apache.http.client.HttpClient that will be used by the executor
	private final HttpClient client;

The authentication caching instance that will be used by the executor
	private final AuthCache authCache;

Not declared final - for an instance may not be required throught the application life-cycle
Not declared final - for an instance may not be required throught the application life-cycle
	private HttpExecutor(final HttpClient client) {
		if(client == null) {
			throw new IllegalArgumentException("Cannot create executor over null client instance");
		}
		this. = client;
		this. = new BasicAuthCache();
	}

Execute the given web request and return the obtained raw web response.

Parameters:
webRequest the WebRequest to be executed
Returns:
the WebRawResponse obtained after execution
Throws:
java.io.IOException if something fails
org.apache.http.client.ClientProtocolException if something fails
		// sharing the context may lead to circular redirects in case
		// of redirections from two request objects towards a single
		// URI - like hitting http://google.com twice leads to circular
		// redirects in the second request
		HttpContext localHttpContext = new BasicHttpContext();
        localHttpContext.setAttribute(.this.);
        localHttpContext.setAttribute(.this.);
        localHttpContext.setAttribute(.this.);
        
        // localHttpContext.removeAttribute(DefaultRedirectStrategy.REDIRECT_LOCATIONS);
        
        HttpRequestBase httpRequest = webRequest.getHttpRequest();
        httpRequest.reset();
        return new WebRawResponse(this..execute(httpRequestlocalHttpContext), localHttpContext);
	}
    
	// Methods related to rate limiting
Add new rate limiting for the given host.

Parameters:
hostName
limit
timeUnit
	public HttpExecutor addRateLimiting(String hostNameint limitTimeUnit timeUnit) {
		if(this. instanceof HttpRateLimitingClient) {
			((HttpRateLimitingClientthis.).addRateLimiting(hostNamelimittimeUnit);
			return this;
		}
		throw new IllegalStateException("Current client does not support rate-limiting");
	}

Remove any previous rate limiting that has been set for the host.

Parameters:
hostName the host name for which we need to remove rate limiting
	public HttpExecutor removeRateLimiting(String hostName) {
		if(this. instanceof HttpRateLimitingClient) {
			return this;
		}
		throw new IllegalStateException("Current client does not support rate-limiting");
	}

Remove all previously set rate limiting.

Returns:
this very HttpExecutor
		if(this. instanceof HttpRateLimitingClient) {
			return this;
		}
		throw new IllegalStateException("Current client does not support rate-limiting");
	}
	// Methods related to authentication
Add provided authentication

Parameters:
authScope the org.apache.http.auth.AuthScope that needs to be set
credentials the org.apache.http.auth.Credentials that need to be set
Returns:
this very HttpExecutor
	public HttpExecutor addAuthentication(AuthScope authScopeCredentials credentials) {
		if (this. == null) {
            this. = new BasicCredentialsProvider();
        }
        this..setCredentials(authScopecredentials);
        return this;
	}

Clear all authentication that may have been set.

Returns:
this very HttpExecutor
        if (this. != null) {
            this..clear();
        }
        
        return this;
    }

Add authentication for a given host

Parameters:
host the host name for which authentication needs to be set
userName the username that needs to be set
password the password that needs to be set
Returns:
this very HttpExecutor
	public HttpExecutor addAuthentication(String hostString userNameString password) {
		AuthScope authScope = new AuthScope(host, 80);
		Credentials credentials = new UsernamePasswordCredentials(userNamepassword);
		return this.addAuthentication(authScopecredentials);
	}

Add authentication for given host and port.

Parameters:
host the host name for which authentication needs to be set
port the port for which authentication needs to be set
userName the username that needs to be set
password the password that needs to be set
Returns:
this very HttpExecutor
	public HttpExecutor addAuthentication(String hostint portString userNameString password) {
		AuthScope authScope = new AuthScope(hostport);
		Credentials credentials = new UsernamePasswordCredentials(userNamepassword);
		return this.addAuthentication(authScopecredentials);
	}

Remove authentication for given host.

Parameters:
host the hostname for which authentication needs to be removed
Returns:
this very HttpExecutor
		AuthScope authScope = new AuthScope(host, 80);
		return this.addAuthentication(authScopenull);
	}

Remove authentication for given host and port.

Parameters:
host the hostname
port the port number
Returns:
this very HttpExecutor
	public HttpExecutor removeAuthentication(String hostint port) {
		AuthScope authScope = new AuthScope(hostport);
		return this.addAuthentication(authScopenull);
	}
	// Methods related to cookie store
Replace or set the given cookie store as the cookie store instance to be used.

Parameters:
cookieStore the cookie store that needs to be set
Returns:
this very HttpExecutor
    public HttpExecutor setCookieStore(final CookieStore cookieStore) {
        this. = cookieStore;
        return this;
    }

    
Clear all cookies in the cookie store if any present.

Returns:
this very HttpExecutor
    public HttpExecutor clearCookies() {
        if (this. != null) {
            this..clear();
        }
        return this;
    }
    // Utility methods start here
    
Set overall maximum connections that can be handled by the underlying connection manager.

Parameters:
numConnections
	public HttpExecutor maxConnections(int numConnections) {
		setMaxConnections(numConnections);
		return this;
	}

Set overall maximum connections per route (over all hosts) that can be handled by the underlying connection manager.

Parameters:
numConnections
	public HttpExecutor maxConnectionsPerRoute(int numConnections) {
		return this;
	}

Set maximum connections that will be operated over the given route, that will be handled by the underlying connection manager.

Parameters:
route
numConnections
	public HttpExecutor maxConnectionsOnHost(HttpRoute routeint numConnections) {
		setMaxConnectionsOnHost(routenumConnections);
		return this;
	}

Set maximum connections that will be operated over the given host on port 80, that will be handled by the underlying connection manager.

Parameters:
hostName
numConnections
	public HttpExecutor maxConnectionsOnHost(String hostNameint numConnections) {
		HttpRoute route = new HttpRoute(new HttpHost(hostName));
		setMaxConnectionsOnHost(routenumConnections);
		return this;
	}

Set maximum connections that will be operated over the given host on given port, that will be handled by the underlying connection manager.

Parameters:
hostName
port
numConnections
	public HttpExecutor maxConnectionsOnHost(String hostNameint portint numConnections) {
		HttpRoute route = new HttpRoute(new HttpHost(hostNameport));
		setMaxConnectionsOnHost(routenumConnections);
		return this;
	}
	// Finalization methods
	/* (non-Javadoc)
	 * @see java.lang.Object#finalize()
	 */
	protected void finalize() throws Throwable {
		super.finalize();
		try {
catch(Throwable t) {
			// eat up
		}
		try {
catch(Throwable t) {
			// eat up
		}
	}
New to GrepCode? Check out our FAQ X