Example usage for org.apache.commons.httpclient.params HttpConnectionManagerParams HttpConnectionManagerParams

List of usage examples for org.apache.commons.httpclient.params HttpConnectionManagerParams HttpConnectionManagerParams

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpConnectionManagerParams HttpConnectionManagerParams.

Prototype

HttpConnectionManagerParams

Source Link

Usage

From source file:org.geoserver.security.iride.service.util.factory.http.HttpClientFactory.java

/**
 * Return a new {@link HttpClient} object, using a {@link MultiThreadedHttpConnectionManager} configured as follows:
 * <ul>//w ww  .j av  a2s. c  o m
 *   <li>The timeout (in milliseconds) for waiting until a connection is established set to {@link #connectionTimeout},
 *   or {@value #DEFAULT_TIMEOUT} if {@link #connectionTimeout} is not set (i.e.: is {@code null})<br />
 *   A value of zero means that no timeout is used</li>
 *   <li>The socket timeout (<code>SO_TIMEOUT</code>)(in milliseconds) for waiting data set to {@link #socketTimeout},
 *   or {@value #DEFAULT_TIMEOUT} if {#link {@link #socketTimeout} is not set (i.e.: is {@code null})<br />
 *   A value of zero means that no timeout is used</li>
 * </ul>
 */
@Override
protected final HttpClient newInstance() {
    final HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setConnectionTimeout(this.connectionTimeout == null ? DEFAULT_TIMEOUT : this.connectionTimeout);
    params.setSoTimeout(this.socketTimeout == null ? DEFAULT_TIMEOUT : this.socketTimeout);

    final HttpConnectionManager manager = new MultiThreadedHttpConnectionManager();
    manager.setParams(params);

    final HttpClient httpClient = new HttpClient();
    httpClient.setHttpConnectionManager(manager);

    return httpClient;
}

From source file:org.geoserver.wps.Execute.java

/**
 * Executes/*from w w w  .  j a va 2 s.c o  m*/
 * 
 * @param ref
 * @return
 */
Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception {
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;
    GetMethod refMethod = null;
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    try {
        if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(connectionTimeout);
            params.setConnectionTimeout(connectionTimeout);
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(connectionTimeout);
                            conn.setReadTimeout(connectionTimeout);
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                input = method.getResponseBodyAsStream();
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(connectionTimeout);
            conn.setReadTimeout(connectionTimeout);
            input = conn.getInputStream();
        }

        // actually parse teh data
        if (input != null) {
            return ppio.decode(input);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        // make sure to close the connection and streams no matter what
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

From source file:org.geoserver.wps.executor.RemoteRequestInputProvider.java

@Override
protected Object getValueInternal(ProgressListener listener) throws Exception {
    InputReferenceType ref = input.getReference();
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;//  www  . j a v a  2  s  .c  om
    GetMethod refMethod = null;
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    listener.started();
    try {
        if ("file".equalsIgnoreCase(destination.getProtocol())) {
            File file = DataUtilities.urlToFile(destination);
            if (maxSize > 0 && maxSize < file.length()) {
                throw new WPSException("Input " + getInputId() + " size " + file.length()
                        + " exceeds maximum allowed size of " + maxSize, "NoApplicableCode", getInputId());
            }

            input = new FileInputStream(file);
        } else if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(timeout);
            params.setConnectionTimeout(timeout);
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(timeout);
                            conn.setReadTimeout(timeout);
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(
                                new InputStreamRequestEntity(refInput, complexPPIO.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(
                            new StringRequestEntity((String) body, complexPPIO.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                try {
                    Header length = method.getResponseHeader("Content-Lenght");
                    if (maxSize > 0 && length != null && Long.parseLong(length.getValue()) > maxSize) {
                        throw new WPSException(
                                "Input " + getInputId() + " size " + length.getValue()
                                        + " exceeds maximum allowed size of " + maxSize
                                        + " according to HTTP Content-Lenght response header",
                                "NoApplicableCode", getInputId());
                    }
                } catch (NumberFormatException e) {
                    LOGGER.log(Level.FINE, "Failed to parse content lenght to check input limits respect, "
                            + "moving on and checking data as it comes in", e);
                }
                input = method.getResponseBodyAsStream();
                if (maxSize > 0) {
                    input = new MaxSizeInputStream(input, getInputId(), maxSize);
                }
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(timeout);
            conn.setReadTimeout(timeout);
            input = conn.getInputStream();

            if (maxSize > 0) {
                input = new MaxSizeInputStream(input, getInputId(), maxSize);
            }
        }

        // actually parse the data
        if (input != null) {
            CancellingInputStream is = new CancellingInputStream(input, listener);
            return complexPPIO.decode(is);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        listener.progress(100);
        listener.complete();
        // make sure to close the connection and streams no matter what
        if (refInput != null) {
            refInput.close();
        }
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

From source file:org.geoserver.wps.executor.SimpleInputProvider.java

/**
 * Executes/*from  w  ww  .ja va2  s .  c  om*/
 * 
 * @param ref
 * @return
 */
Object executeRemoteRequest(InputReferenceType ref, ComplexPPIO ppio, String inputId) throws Exception {
    URL destination = new URL(ref.getHref());

    HttpMethod method = null;
    GetMethod refMethod = null;
    InputStream input = null;
    InputStream refInput = null;

    // execute the request
    try {
        if ("http".equalsIgnoreCase(destination.getProtocol())) {
            // setup the client
            HttpClient client = new HttpClient();
            // setting timeouts (30 seconds, TODO: make this configurable)
            HttpConnectionManagerParams params = new HttpConnectionManagerParams();
            params.setSoTimeout(executor.getConnectionTimeout());
            params.setConnectionTimeout(executor.getConnectionTimeout());
            // TODO: make the http client a well behaved http client, no more than x connections
            // per server (x admin configurable maybe), persistent connections and so on
            HttpConnectionManager manager = new SimpleHttpConnectionManager();
            manager.setParams(params);
            client.setHttpConnectionManager(manager);

            // prepare either a GET or a POST request
            if (ref.getMethod() == null || ref.getMethod() == MethodType.GET_LITERAL) {
                GetMethod get = new GetMethod(ref.getHref());
                get.setFollowRedirects(true);
                method = get;
            } else {
                String encoding = ref.getEncoding();
                if (encoding == null) {
                    encoding = "UTF-8";
                }

                PostMethod post = new PostMethod(ref.getHref());
                Object body = ref.getBody();
                if (body == null) {
                    if (ref.getBodyReference() != null) {
                        URL refDestination = new URL(ref.getBodyReference().getHref());
                        if ("http".equalsIgnoreCase(refDestination.getProtocol())) {
                            // open with commons http client
                            refMethod = new GetMethod(ref.getBodyReference().getHref());
                            refMethod.setFollowRedirects(true);
                            client.executeMethod(refMethod);
                            refInput = refMethod.getResponseBodyAsStream();
                        } else {
                            // open with the built-in url management
                            URLConnection conn = refDestination.openConnection();
                            conn.setConnectTimeout(executor.getConnectionTimeout());
                            conn.setReadTimeout(executor.getConnectionTimeout());
                            refInput = conn.getInputStream();
                        }
                        post.setRequestEntity(new InputStreamRequestEntity(refInput, ppio.getMimeType()));
                    } else {
                        throw new WPSException("A POST request should contain a non empty body");
                    }
                } else if (body instanceof String) {
                    post.setRequestEntity(new StringRequestEntity((String) body, ppio.getMimeType(), encoding));
                } else {
                    throw new WPSException("The request body should be contained in a CDATA section, "
                            + "otherwise it will get parsed as XML instead of being preserved as is");

                }
                method = post;
            }
            // add eventual extra headers
            if (ref.getHeader() != null) {
                for (Iterator it = ref.getHeader().iterator(); it.hasNext();) {
                    HeaderType header = (HeaderType) it.next();
                    method.setRequestHeader(header.getKey(), header.getValue());
                }
            }
            int code = client.executeMethod(method);

            if (code == 200) {
                input = method.getResponseBodyAsStream();
            } else {
                throw new WPSException("Error getting remote resources from " + ref.getHref() + ", http error "
                        + code + ": " + method.getStatusText());
            }
        } else {
            // use the normal url connection methods then...
            URLConnection conn = destination.openConnection();
            conn.setConnectTimeout(executor.getConnectionTimeout());
            conn.setReadTimeout(executor.getConnectionTimeout());
            input = conn.getInputStream();
        }

        // actually parse teh data
        if (input != null) {
            return ppio.decode(input);
        } else {
            throw new WPSException("Could not find a mean to read input " + inputId);
        }
    } finally {
        // make sure to close the connection and streams no matter what
        if (input != null) {
            input.close();
        }
        if (method != null) {
            method.releaseConnection();
        }
        if (refMethod != null) {
            refMethod.releaseConnection();
        }
    }
}

From source file:org.geotools.data.ows.MultithreadedHttpClient.java

public MultithreadedHttpClient() {
    connectionManager = new MultiThreadedHttpConnectionManager();

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setSoTimeout(30000);//  w  w w . ja v  a 2  s .  c  om
    params.setConnectionTimeout(30000);
    params.setMaxTotalConnections(6);
    params.setDefaultMaxConnectionsPerHost(6);

    connectionManager.setParams(params);

    client = new HttpClient(connectionManager);

    applySystemProxySettings();
}

From source file:org.geowebcache.util.HttpClientBuilder.java

/**
 * uses the configuration of this builder to generate a HttpClient
 * /*from w  w w  .  j  a  va 2s.  c o  m*/
 * @return the generated HttpClient
 */
public HttpClient buildClient() {
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setSoTimeout(backendTimeoutMillis);
    params.setConnectionTimeout(backendTimeoutMillis);
    if (concurrency > 0) {
        params.setMaxTotalConnections(concurrency);
        params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, concurrency);
    }

    connectionManager.setParams(params);

    HttpClient httpClient = new HttpClient(connectionManager);

    if (authscope != null && httpcredentials != null) {
        httpClient.getState().setCredentials(authscope, httpcredentials);
        httpClient.getParams().setAuthenticationPreemptive(true);
    }

    if (proxyUrl != null) {
        httpClient.getHostConfiguration().setProxy(proxyUrl.getHost(), proxyUrl.getPort());
        if (proxycredentials != null) {
            httpClient.getState().setProxyCredentials(new AuthScope(proxyUrl.getHost(), proxyUrl.getPort()),
                    proxycredentials);
        }
    }
    return httpClient;
}

From source file:org.hydracache.client.transport.HttpTransport.java

public HttpTransport() {
    // FIXME Make this more IoC and configurable.
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams connectionManagerParams = new HttpConnectionManagerParams();
    connectionManagerParams.setDefaultMaxConnectionsPerHost(10);
    connectionManagerParams.setMaxTotalConnections(100);
    connectionManager.setParams(connectionManagerParams);

    this.httpClient = new HttpClient(connectionManager);
}

From source file:org.infoscoop.request.ProxyRequest.java

private HttpClient newHttpClient() {
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    if (this.timeout > 0) {
        params.setConnectionTimeout(this.timeout);
    } else {//  w  w  w.  j  a  va  2 s  . co m
        params.setConnectionTimeout(SOCKET_CONNECTION_TIMEOUT);
    }
    HttpConnectionManager manager = new SimpleHttpConnectionManager();
    manager.setParams(params);
    HttpClient client = new HttpClient(manager);
    client.getParams().setVersion(new HttpVersion(1, 1));

    if (proxy != null && proxy.isUseProxy()) {
        if (log.isInfoEnabled())
            log.info("Proxy=" + proxy.getHost() + ":" + proxy.getPort() + ", authentication="
                    + proxy.needsProxyAuth());

        client.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());

        if (proxy.needsProxyAuth()) {
            client.getParams().setAuthenticationPreemptive(true);
            client.getState().setProxyCredentials(new AuthScope(proxy.getHost(), proxy.getPort()),
                    proxy.getProxyCredentials());
        }

    }
    client.getParams().setParameter("http.socket.timeout", new Integer(this.timeout));

    String allowCircularRedirect = this.getRequestHeader(ALLOW_CIRCULAR_REDIRECT) == null ? "false"
            : this.getRequestHeader(ALLOW_CIRCULAR_REDIRECT);

    if (Boolean.valueOf(allowCircularRedirect).booleanValue()) {
        if (log.isInfoEnabled())
            log.info("Circular redirect on");
        client.getParams().setParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE);
    }
    return client;
}

From source file:org.infoscoop.request.ProxyRequest.java

public static void main(String args[]) throws MalformedURLException {
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setConnectionTimeout(3000);//from  w w  w.  j a v a2 s .c  om
    HttpConnectionManager manager = new SimpleHttpConnectionManager();
    manager.setParams(params);
    HttpClient c = new HttpClient(manager);
    c.getParams().setParameter("http.socket.timeout", new Integer(5000));

    Credentials credentials = new NTCredentials("test", "test", "", "");//192.168.233.2INFOSCOOP
    //Credentials credentials = new UsernamePasswordCredentials("INFOSCOOP\test", "test");
    // the scope of the certification.
    URL urlObj = new URL("http://192.168.233.2/index.html");
    AuthScope scope1 = new AuthScope(urlObj.getHost(), urlObj.getPort(), null);
    // set a pair of a scope and an information of the certification.
    c.getState().setCredentials(scope1, credentials);

    //GetMethod g = new GetMethod("http://inicio/syanai/rss.do?category=3bb34-f8f19ded28-038fb3114a5cd639e1963371842f83c0&u=bQRF9JnX%2Bm7H0n4iwJJ3ZA%3D%3D");//"http://172.22.113.111");
    //GetMethod g = new GetMethod("http://172.22.113.111");
    GetMethod g = new GetMethod("http://192.168.233.2/index.html");
    g.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false));
    try {
        c.executeMethod(g);
        System.out.println(g.getStatusCode());
        System.out.println(g.getResponseBodyAsString());
    } catch (HttpException e) {
        log.error("", e);
    } catch (IOException e) {
        log.error("", e);
    }
}

From source file:org.intalio.tempo.workflow.tas.nuxeo.NuxeoStorageStrategy.java

/**
 * Everything we need to do to have an authenticated http client
 * /*from   w  ww  .  ja va 2s .  c o m*/
 * @throws URIException
 */
private void initHttpClient() throws URIException {
    httpclient = new HttpClient();
    HostConfiguration hostConfig = new HostConfiguration();
    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(getNuxeoRestUrl(), false);
    hostConfig.setHost(uri);
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    int maxHostConnections = 20;
    params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
    connectionManager.setParams(params);
    httpclient = new HttpClient(connectionManager);
    httpclient.setHostConfiguration(hostConfig);
    Credentials creds = new UsernamePasswordCredentials(userName, password);
    AuthScope authScope = new AuthScope(hostConfig.getHost(), hostConfig.getPort());
    httpclient.getState().setCredentials(authScope, creds);
    httpclient.getParams().setAuthenticationPreemptive(true);
}