Example usage for org.apache.commons.httpclient HttpClient setHttpConnectionManager

List of usage examples for org.apache.commons.httpclient HttpClient setHttpConnectionManager

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpClient setHttpConnectionManager.

Prototype

public void setHttpConnectionManager(HttpConnectionManager paramHttpConnectionManager)

Source Link

Usage

From source file:jp.go.nict.langrid.management.logic.service.ProcessDeployer.java

static InputStream openStream(URL url, String userName, String password) throws IOException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    client.setHttpConnectionManager(manager);
    GetMethod m = new GetMethod(url.getFile());
    if ((userName != null) && (userName.length() > 0)) {
        client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        m.setDoAuthentication(true);// w  ww .  java  2 s  .co  m
    }
    try {
        client.executeMethod(m);
        if (m.getStatusCode() != 200) {
            throw new IOException("failed to get vaild http response: " + m.getStatusCode());
        }
        return new ByteArrayInputStream(StreamUtil.readAsBytes(m.getResponseBodyAsStream()));
    } finally {
        manager.shutdown();
    }
}

From source file:jp.go.nict.langrid.servicesupervisor.invocationprocessor.executor.ServiceInvoker.java

/**
 * /*from w  w w .  j  ava2  s. c  o m*/
 * 
 */
public static int invoke(URL url, String userName, String password, Map<String, String> headers,
        InputStream input, HttpServletResponse output, OutputStream errorOut, int connectionTimeout,
        int soTimeout) throws IOException, SocketTimeoutException {
    HttpClient client = HttpClientUtil.createHttpClientWithHostConfig(url);
    SimpleHttpConnectionManager manager = new SimpleHttpConnectionManager(true);
    manager.getParams().setConnectionTimeout(connectionTimeout);
    manager.getParams().setSoTimeout(soTimeout);
    manager.getParams().setMaxConnectionsPerHost(client.getHostConfiguration(), 2);
    client.setHttpConnectionManager(manager);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));

    PostMethod method = new PostMethod(url.getFile());
    method.setRequestEntity(new InputStreamRequestEntity(input));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        method.addRequestHeader(e.getKey(), e.getValue());
    }
    if (!headers.containsKey("Content-Type"))
        method.addRequestHeader("Content-Type", "text/xml; charset=utf-8");
    if (!headers.containsKey("Accept"))
        method.addRequestHeader("Accept", "application/soap+xml, application/dime, multipart/related, text/*");
    if (!headers.containsKey("SOAPAction"))
        method.addRequestHeader("SOAPAction", "\"\"");
    if (!headers.containsKey("User-Agent"))
        method.addRequestHeader("User-Agent", "Langrid Service Invoker/1.0");
    if (userName != null) {
        int port = url.getPort();
        if (port == -1) {
            port = url.getDefaultPort();
            if (port == -1) {
                port = 80;
            }
        }
        if (password == null) {
            password = "";
        }
        client.getState().setCredentials(new AuthScope(url.getHost(), port, null),
                new UsernamePasswordCredentials(userName, password));
        client.getParams().setAuthenticationPreemptive(true);
        method.setDoAuthentication(true);
    }

    try {
        int status;
        try {
            status = client.executeMethod(method);
        } catch (SocketTimeoutException e) {
            status = HttpServletResponse.SC_REQUEST_TIMEOUT;
        }
        output.setStatus(status);
        if (status == 200) {
            for (Header h : method.getResponseHeaders()) {
                String name = h.getName();
                if (name.startsWith("X-Langrid") || (!throughHeaders.contains(name.toLowerCase())))
                    continue;
                String value = h.getValue();
                output.addHeader(name, value);
            }
            OutputStream os = output.getOutputStream();
            StreamUtil.transfer(method.getResponseBodyAsStream(), os);
            os.flush();
        } else if (status == HttpServletResponse.SC_REQUEST_TIMEOUT) {
        } else {
            StreamUtil.transfer(method.getResponseBodyAsStream(), errorOut);
        }
        return status;
    } finally {
        manager.shutdown();
    }
}

From source file:com.foglyn.core.FoglynCorePlugin.java

private HttpClient createHttpClient(HttpConnectionManager connectionManager) {
    HttpClient httpClient = new HttpClient();
    httpClient.setHttpConnectionManager(connectionManager);
    httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

    String userAgent = USER_AGENT;
    String version = getBundleVersion();
    if (version != null) {
        userAgent = USER_AGENT + "/" + version;
    }/*  www . j a va  2s. co  m*/

    WebUtil.configureHttpClient(httpClient, userAgent);
    return httpClient;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Create and set connection pool./*  w  ww .j  a v  a  2  s. co  m*/
 *
 * @param httpClient httpClient instance
 */
public static void createMultiThreadedHttpConnectionManager(HttpClient httpClient) {
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.getParams().setDefaultMaxConnectionsPerHost(100);
    connectionManager.getParams().setConnectionTimeout(10000);
    synchronized (LOCK) {
        httpConnectionManagerThread.addConnectionManager(connectionManager);
    }
    httpClient.setHttpConnectionManager(connectionManager);
}

From source file:net.sf.webissues.core.WebIssuesClientManager.java

protected HttpClient createHttpClient(AbstractWebLocation location) {
    HttpClient httpClient = new HttpClient();
    httpClient.getParams().setAuthenticationPreemptive(true);
    HttpConnectionManager connectionManager = WebIssuesClientManager.getConnectionManager();
    httpClient.setHttpConnectionManager(connectionManager);
    connectionManager.getParams().setConnectionTimeout(8000);
    connectionManager.getParams().setSoTimeout(8000);
    httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    WebUtil.configureHttpClient(httpClient, WebIssuesClientManager.USER_AGENT);
    httpClient.setHostConfiguration(WebUtil.createHostConfiguration(httpClient, location, null));
    return httpClient;
}

From source file:com.wooki.services.parsers.XHTMLToFormattingObjects.java

public void setHttpClient(HttpClient httpClient) {
    this.httpClient = httpClient;
    HttpClientParams params = httpClient.getParams();
    // params./*from w w  w .j a  v a2s . com*/
    httpClient.setHttpConnectionManager(new MultiThreadedHttpConnectionManager());
}

From source file:com.esri.gpt.framework.http.HttpClientRequest.java

/**
 * Executes the HTTP request./*from  ww  w. j  a va 2  s .c  o m*/
 * @throws IOException if an Exception occurs
 */
public void execute() throws IOException {

    // initialize
    this.executionLog.setLength(0);
    StringBuffer log = this.executionLog;
    ResponseInfo respInfo = this.getResponseInfo();
    respInfo.reset();
    InputStream responseStream = null;
    HttpMethodBase method = null;

    try {
        log.append("HTTP Client Request\n").append(this.getUrl());

        // make the Apache HTTPClient
        HttpClient client = this.batchHttpClient;
        if (client == null) {
            client = new HttpClient();
            boolean alwaysClose = Val.chkBool(Val.chkStr(ApplicationContext.getInstance().getConfiguration()
                    .getCatalogConfiguration().getParameters().getValue("httpClient.alwaysClose")), false);
            if (alwaysClose) {
                client.setHttpConnectionManager(new SimpleHttpConnectionManager(true));
            }
        }

        // setting timeout info
        client.getHttpConnectionManager().getParams().setConnectionTimeout(getConnectionTimeOutMs());
        client.getHttpConnectionManager().getParams().setSoTimeout(getResponseTimeOutMs());

        // setting retries
        int retries = this.getRetries();

        // create the client and method, apply authentication and proxy settings
        method = this.createMethod();
        //method.setFollowRedirects(true);
        if (retries > -1) {
            // TODO: not taking effect yet?
            DefaultHttpMethodRetryHandler retryHandler = new DefaultHttpMethodRetryHandler(retries, true);
            client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
            method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryHandler);
        }

        this.applyAuthAndProxySettings(client, this.getUrl());

        // execute the method, determine basic information about the response
        respInfo.setResponseCode(client.executeMethod(method));
        this.determineResponseInfo(method);

        // collect logging info
        if (LOGGER.isLoggable(Level.FINER)) {
            log.append("\n>>").append(method.getStatusLine());
            log.append("\n--Request Header");
            for (Header hdr : method.getRequestHeaders()) {
                log.append("\n  ").append(hdr.getName() + ": " + hdr.getValue());
            }
            log.append("\n--Response Header");
            for (Header hdr : method.getResponseHeaders()) {
                log.append("\n  ").append(hdr.getName() + ": " + hdr.getValue());
            }

            //log.append(" responseCode=").append(this.getResponseInfo().getResponseCode());
            //log.append(" responseContentType=").append(this.getResponseInfo().getContentType());
            //log.append(" responseContentEncoding=").append(this.getResponseInfo().getContentEncoding());
            //log.append(" responseContentLength=").append(this.getResponseInfo().getContentLength());

            if (this.getContentProvider() != null) {
                String loggable = this.getContentProvider().getLoggableContent();
                if (loggable != null) {
                    log.append("\n--Request Content------------------------------------\n").append(loggable);
                }
            }
        }

        // throw an exception if an error is encountered
        if ((respInfo.getResponseCode() < 200) || (respInfo.getResponseCode() >= 300)) {
            String msg = "HTTP Request failed: " + method.getStatusLine();
            if (respInfo.getResponseCode() == HttpStatus.SC_UNAUTHORIZED) {
                AuthState authState = method.getHostAuthState();
                AuthScheme authScheme = authState.getAuthScheme();
                HttpClient401Exception authException = new HttpClient401Exception(msg);
                authException.setUrl(this.getUrl());
                authException.setRealm(authState.getRealm());
                authException.setScheme(authScheme.getSchemeName());
                if ((authException.getRealm() == null) || (authException.getRealm().length() == 0)) {
                    authException.setRealm(authException.generateHostBasedRealm());
                }
                throw authException;
            } else {
                throw new HttpClientException(respInfo.getResponseCode(), msg);
            }
        }

        // handle the response
        if (this.getContentHandler() != null) {
            if (getContentHandler().onBeforeReadResponse(this)) {
                responseStream = getResponseStream(method);
                if (responseStream != null) {
                    this.getContentHandler().readResponse(this, responseStream);
                }
            }

            // log thre response content
            String loggable = this.getContentHandler().getLoggableContent();
            long nBytesRead = this.getResponseInfo().getBytesRead();
            long nCharsRead = this.getResponseInfo().getCharactersRead();
            if ((nBytesRead >= 0) || (nCharsRead >= 0) || (loggable != null)) {
                log.append("\n--Response Content------------------------------------");
                if (nBytesRead >= 0)
                    log.append("\n(").append(nBytesRead).append(" bytes read)");
                if (nCharsRead >= 0)
                    log.append("\n(").append(nCharsRead).append(" characters read)");
                if (loggable != null)
                    log.append("\n").append(loggable);
            }
        }

    } finally {

        // cleanup
        try {
            if (responseStream != null)
                responseStream.close();
        } catch (Throwable t) {
            LOGGER.log(Level.SEVERE, "Unable to close HTTP response stream.", t);
        }
        try {
            if (method != null)
                method.releaseConnection();
        } catch (Throwable t) {
            LOGGER.log(Level.SEVERE, "Unable to release HttpMethod", t);
        }

        // log the request/response
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.finer(this.getExecutionLog().toString());
        }
    }
}

From source file:org.apache.camel.component.http.HttpEndpoint.java

/**
 * Factory method used by producers and consumers to create a new {@link HttpClient} instance
 *///ww  w . ja va  2 s .c  o m
public HttpClient createHttpClient() {
    ObjectHelper.notNull(clientParams, "clientParams");
    ObjectHelper.notNull(httpConnectionManager, "httpConnectionManager");

    HttpClient answer = new HttpClient(getClientParams());

    // configure http proxy from camelContext
    if (ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyHost"))
            && ObjectHelper.isNotEmpty(getCamelContext().getProperty("http.proxyPort"))) {
        String host = getCamelContext().getProperty("http.proxyHost");
        int port = Integer.parseInt(getCamelContext().getProperty("http.proxyPort"));
        LOG.debug(
                "CamelContext properties http.proxyHost and http.proxyPort detected. Using http proxy host: {} port: {}",
                host, port);
        answer.getHostConfiguration().setProxy(host, port);
    }

    if (proxyHost != null) {
        LOG.debug("Using proxy: {}:{}", proxyHost, proxyPort);
        answer.getHostConfiguration().setProxy(proxyHost, proxyPort);
    }

    if (authMethodPriority != null) {
        List<String> authPrefs = new ArrayList<String>();
        Iterator<?> it = getCamelContext().getTypeConverter().convertTo(Iterator.class, authMethodPriority);
        int i = 1;
        while (it.hasNext()) {
            Object value = it.next();
            AuthMethod auth = getCamelContext().getTypeConverter().convertTo(AuthMethod.class, value);
            if (auth == null) {
                throw new IllegalArgumentException(
                        "Unknown authMethod: " + value + " in authMethodPriority: " + authMethodPriority);
            }
            LOG.debug("Using authSchemePriority #{}: {}", i, auth);
            authPrefs.add(auth.name());
            i++;
        }
        if (!authPrefs.isEmpty()) {
            answer.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }
    }

    answer.setHttpConnectionManager(httpConnectionManager);
    HttpClientConfigurer configurer = getHttpClientConfigurer();
    if (configurer != null) {
        configurer.configureHttpClient(answer);
    }
    return answer;
}

From source file:org.eclipse.ecf.internal.provider.filetransfer.httpclient.ConnectionManagerHelper.java

private static void initParameters(HttpClient httpClient, HttpConnectionManager cm, boolean cmIsShared,
        Map options) {/*from   w w w.j av a 2  s  .c  om*/

    if (cmIsShared) {
        long closeIdlePeriod = getLongProperty(ConnectionOptions.PROP_POOL_CLOSE_IDLE_PERIOD,
                ConnectionOptions.POOL_CLOSE_IDLE_PERIOD_DEFAULT);
        if (closeIdlePeriod > 0) {
            Trace.trace(Activator.PLUGIN_ID,
                    "Closing connections which were idle at least " + closeIdlePeriod + " milliseconds."); //$NON-NLS-1$ //$NON-NLS-2$
            cm.closeIdleConnections(closeIdlePeriod);
        }
    }

    // HttpClient parameters can be traced independently
    httpClient.setHttpConnectionManager(cm);
    int readTimeout = getSocketReadTimeout(options);
    cm.getParams().setSoTimeout(readTimeout);
    int connectTimeout = getConnectTimeout(options);
    cm.getParams().setConnectionTimeout(connectTimeout);

    if (cmIsShared) {
        HttpConnectionManagerParams cmParams = cm.getParams();
        int maxHostConnections = getIntegerProperty(ConnectionOptions.PROP_MAX_CONNECTIONS_PER_HOST,
                ConnectionOptions.MAX_CONNECTIONS_PER_HOST_DEFAULT);
        int maxTotalConnections = getIntegerProperty(ConnectionOptions.PROP_MAX_TOTAL_CONNECTIONS,
                ConnectionOptions.MAX_TOTAL_CONNECTIONS_DEFAULT);

        cmParams.setDefaultMaxConnectionsPerHost(maxHostConnections);
        cmParams.setMaxTotalConnections(maxTotalConnections);
        long connectionManagerTimeout = getLongProperty(ConnectionOptions.PROP_POOL_CONNECTION_TIMEOUT,
                ConnectionOptions.POOL_CONNECTION_TIMEOUT_DEFAULT);
        httpClient.getParams().setConnectionManagerTimeout(connectionManagerTimeout);
    }
}

From source file:org.eclipse.mylyn.commons.net.http.CommonHttpClient3.java

private static HttpClient createHttpClient(String userAgent) {
    HttpClient httpClient = new HttpClient();
    httpClient.setHttpConnectionManager(WebUtil.getConnectionManager());
    httpClient.getParams().setCookiePolicy(CookiePolicy.RFC_2109);
    WebUtil.configureHttpClient(httpClient, userAgent);
    return httpClient;
}