Example usage for org.apache.commons.httpclient MultiThreadedHttpConnectionManager MultiThreadedHttpConnectionManager

List of usage examples for org.apache.commons.httpclient MultiThreadedHttpConnectionManager MultiThreadedHttpConnectionManager

Introduction

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

Prototype

public MultiThreadedHttpConnectionManager() 

Source Link

Usage

From source file:org.redpill.alfresco.pdfapilot.client.PdfaPilotClientImpl.java

private HttpClient createHttpClient(int retries, int connectionTimeoutInMillis) {
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();

    HttpClient client = new HttpClient(connectionManager);

    client.getHttpConnectionManager().getParams().setTcpNoDelay(true);

    client.getHttpConnectionManager().getParams().setConnectionTimeout(connectionTimeoutInMillis);

    client.getHttpConnectionManager().getParams().setSoTimeout(_transformationTimeout * 1000);

    client.getHttpConnectionManager().getParams().setMaxTotalConnections(_maxTotalConnections);
    client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(_maxConcurrentConnections);
    URI uri;/* w ww  . j a va2s.  co  m*/

    try {
        uri = new URI(_serverUrl);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(uri.getHost(), uri.getPort(), uri.getScheme());
    client.getHttpConnectionManager().getParams().setMaxConnectionsPerHost(hostConfiguration,
            _maxConcurrentConnections);

    client.getState().setCredentials(new AuthScope(null, -1, null),
            new UsernamePasswordCredentials(_username, _password));

    client.getParams().setAuthenticationPreemptive(true);

    DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(retries, true);
    client.getParams().setParameter("http.method.retry-handler", retryhandler);

    return client;
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Generates a reusable http client wrapper which can be given to {@link #fireRequest(HttpClientWrapper, String, Method, Map, Object, boolean)}
 * as an efficiency mechanism/*from w w w  . j  a v  a  2s .  c  o m*/
 * 
 * @param multiThreaded true if you want to allow the client to run in multiple threads
 * @param idleConnectionTimeout if this is 0 then it will use the defaults, otherwise connections will be timed out after this long (ms)
 * @param cookies to send along with every request from this client
 * @return the reusable http client wrapper
 */
public static HttpClientWrapper makeReusableHttpClient(boolean multiThreaded, int idleConnectionTimeout,
        Cookie[] cookies) {
    HttpClientWrapper wrapper;
    HttpClient client;
    MultiThreadedHttpConnectionManager connectionManager = null;
    if (multiThreaded) {
        connectionManager = new MultiThreadedHttpConnectionManager();
        client = new HttpClient(connectionManager);
    } else {
        client = new HttpClient();
    }
    if (idleConnectionTimeout <= 0) {
        idleConnectionTimeout = 5000;
    }
    client.getHttpConnectionManager().closeIdleConnections(idleConnectionTimeout);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(idleConnectionTimeout);
    // create the initial state
    HttpState initialState = new HttpState();
    if (cookies != null && cookies.length > 0) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie c = cookies[i];
            org.apache.commons.httpclient.Cookie mycookie = new org.apache.commons.httpclient.Cookie(
                    c.getDomain(), c.getName(), c.getValue(), c.getPath(), c.getMaxAge(), c.getSecure());
            initialState.addCookie(mycookie);
        }
        client.setState(initialState);
    }
    // set some defaults
    client.getParams().setParameter(HttpMethodParams.USER_AGENT,
            "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 Firefox/3.0.1");
    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    client.getParams().setBooleanParameter(HttpMethodParams.SINGLE_COOKIE_HEADER, true);
    wrapper = new HttpClientWrapper(client, connectionManager, initialState);
    return wrapper;
}

From source file:org.sakaiproject.kernel.proxy.ProxyClientServiceImpl.java

/**
 * Create resources used by this component.
 * //from  w w w.jav  a2  s .co m
 * @param ctx
 * @throws Exception
 */
public void activate(ComponentContext ctx) throws Exception {
    velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new VelocityLogger(this.getClass()));

    velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, JCR_RESOURCE_LOADER);
    velocityEngine.setProperty(JCR_RESOURCE_LOADER_CLASS, JcrResourceLoader.class.getName());
    ExtendedProperties configuration = new ExtendedProperties();
    configuration.addProperty(JCR_RESOURCE_LOADER_PATH + ProxyNodeSource.JCR_RESOURCE_LOADER_RESOURCE_SOURCE,
            this);
    velocityEngine.setExtendedProperties(configuration);
    velocityEngine.init();

    httpClientConnectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    // could set a whole load of connection properties
    httpClientConnectionManager.setParams(params);

    httpClient = new HttpClient(httpClientConnectionManager);
}

From source file:org.sakaiproject.nakamura.proxy.ProxyClientServiceImpl.java

/**
 * Create resources used by this component.
 *
 * @param ctx/*from  ww  w .  ja va2  s .c  o  m*/
 * @throws Exception
 */
@SuppressWarnings("unchecked")
protected void activate(ComponentContext ctx) throws Exception {
    if (ctx != null) {
        Dictionary<String, Object> props = ctx.getProperties();
        configProperties = new HashMap<String, Object>();
        for (Enumeration<String> e = props.keys(); e.hasMoreElements();) {
            String k = e.nextElement();
            configProperties.put(k, props.get(k));
        }
        String[] safePostProcessorNames = (String[]) configProperties.get(SAFE_POSTPROCESSORS);
        if (safePostProcessorNames == null) {
            safeOpenProcessors.add("rss");
            safeOpenProcessors.add("trustedLoginTokenProxyPostProcessor");
        } else {
            for (String pp : safePostProcessorNames) {
                safeOpenProcessors.add(pp);
            }
        }
    } else {
        configProperties = new HashMap<String, Object>();
    }
    velocityEngine = new VelocityEngine();
    velocityEngine.setProperty(VelocityEngine.RUNTIME_LOG_LOGSYSTEM, new VelocityLogger(this.getClass()));

    velocityEngine.setProperty(VelocityEngine.RESOURCE_LOADER, JCR_RESOURCE_LOADER);
    velocityEngine.setProperty(JCR_RESOURCE_LOADER_CLASS, JcrResourceLoader.class.getName());
    ExtendedProperties configuration = new ExtendedProperties();
    configuration.addProperty(JCR_RESOURCE_LOADER_PATH + ProxyNodeSource.JCR_RESOURCE_LOADER_RESOURCE_SOURCE,
            this);
    velocityEngine.setExtendedProperties(configuration);
    velocityEngine.init();

    httpClientConnectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    // could set a whole load of connection properties
    httpClientConnectionManager.setParams(params);

    httpClient = new HttpClient(httpClientConnectionManager);

    // allow communications via a proxy server if command line
    // java parameters http.proxyHost,http.proxyPort,http.proxyUser,
    // http.proxyPassword have been provided.
    externalAuthenticatingProxy = false;
    String proxyHost = System.getProperty("http.proxyHost", "");
    int proxyPort = Integer.parseInt(System.getProperty("http.proxyPort", "80"));
    if (!proxyHost.equals("")) {
        // allow communications via a non-authenticating proxy
        httpClient.getHostConfiguration().setProxy(proxyHost, proxyPort);

        String proxyUser = System.getProperty("http.proxyUser", "");
        String proxyPassword = System.getProperty("http.proxyPassword", "");
        if (!proxyUser.equals("")) {
            // allow communications via an authenticating proxy
            Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
            AuthScope authScope = new AuthScope(proxyHost, proxyPort);
            httpClient.getState().setProxyCredentials(authScope, credentials);
            externalAuthenticatingProxy = true;
        }
    }
}

From source file:org.scohen.juploadr.upload.HttpClientFactory.java

public static HttpClient getHttpClient(CommunityAccount account) {
    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    Protocol http;//  ww  w.  ja  v a  2 s. co m
    if (account.isBandwidthLimited()) {
        http = new Protocol(HTTP, new BandwidthLimitingProtocolSocketFactory(account.getBandwidth()), 80);
    } else {
        http = new Protocol(HTTP, new DefaultProtocolSocketFactory(), 80);
    }

    Protocol.registerProtocol(HTTP, http);
    NetActivator activator = NetActivator.getDefault();
    IProxyService proxyService = activator.getProxyService();
    String home = ((IConfigurationElement) account.getConfiguration().getParent()).getAttribute("home"); //$NON-NLS-1$
    home = Core.furnishWebUrl(home);
    IProxyData proxyData = null;
    try {
        IProxyData[] select = proxyService.select(new URI(home));
        if (select.length > 0)
            proxyData = select[0];
    } catch (URISyntaxException e) {
        activator.logError(Messages.HttpClientFactory_bad_uri_for_proxy, e);
    } finally {
        activator.ungetProxyService(proxyService);
    }
    if (proxyData != null && proxyData.getHost() != null) {
        String proxyHost = proxyData.getHost();
        String proxyPassword = proxyData.getPassword();
        String proxyUsername = proxyData.getUserId();
        int proxyPort = proxyData.getPort();
        HostConfiguration hc = client.getHostConfiguration();
        if (proxyPort < 0)
            hc.setHost(proxyHost);
        else
            hc.setProxy(proxyHost, proxyPort);
        if (proxyData.isRequiresAuthentication() && proxyUsername.length() > 0) {
            Credentials creds = new UsernamePasswordCredentials(proxyUsername, proxyPassword);
            client.getParams().setAuthenticationPreemptive(true);
            AuthScope scope = new AuthScope(proxyHost, proxyPort);
            client.getState().setProxyCredentials(scope, creds);
        }
    }
    client.getHttpConnectionManager().getParams().setConnectionTimeout(60000);
    client.getHttpConnectionManager().getParams().setSoTimeout(60000);
    client.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(0, false));
    return client;
}

From source file:org.soasecurity.is.oauth.validation.OAuth2TokenValidationServiceClient.java

public OAuth2TokenValidationServiceClient(String serverUrl, String serverUserName, String serverPassword,
        ConfigurationContext configurationContext) {

    if (serverUrl != null) {
        serverUrl = serverUrl.trim();/*from w w w.j a v a2 s  .c  om*/
        if (!serverUrl.endsWith("/")) {
            serverUrl += "/";
        }
    }
    this.serverUrl = serverUrl;
    this.serverUserName = serverUserName;
    this.serverPassword = serverPassword;
    this.configurationContext = configurationContext;

    MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
    httpConnectionManager.getParams().setDefaultMaxConnectionsPerHost(200);
    httpConnectionManager.getParams().setMaxTotalConnections(500);
    httpClient = new HttpClient(httpConnectionManager);
}

From source file:org.sonar.wsclient.connectors.HttpClient3Connector.java

private void createClient() {
    final HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setConnectionTimeout(AbstractQuery.DEFAULT_TIMEOUT_MILLISECONDS);
    params.setSoTimeout(AbstractQuery.DEFAULT_TIMEOUT_MILLISECONDS);
    params.setDefaultMaxConnectionsPerHost(MAX_HOST_CONNECTIONS);
    params.setMaxTotalConnections(MAX_TOTAL_CONNECTIONS);
    final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.setParams(params);
    this.httpClient = new HttpClient(connectionManager);
    configureCredentials();/*from   w w  w . ja  va 2 s  .c  om*/
}

From source file:org.sonar.wsclient.WSClientFactory.java

/**
 * @see org.sonar.wsclient.connectors.HttpClient3Connector#createClient()
 *///from w w w .  j a  va 2 s. c o  m
private static HttpClient createHttpClient() {
    final HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setConnectionTimeout(TIMEOUT_MS);
    params.setSoTimeout(TIMEOUT_MS);
    params.setDefaultMaxConnectionsPerHost(MAX_HOST_CONNECTIONS);
    params.setMaxTotalConnections(MAX_TOTAL_CONNECTIONS);
    final MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.setParams(params);
    return new HttpClient(connectionManager);
}

From source file:org.springbyexample.httpclient.AbstractHttpClientTemplate.java

/**
 * Implementation of <code>InitializingBean</code> 
 * that initializes the <code>HttpClient</code> if it is <code>null</code> 
 * and also sets the connection manager to <code>MultiThreadedHttpConnectionManager</code> 
 * if it is <code>null</code> while initializing the <code>HttpClient</code>.
 *///  w w w  . ja v a2s .c  o m
public void afterPropertiesSet() throws Exception {
    // make sure credentials are properly set
    for (Credentials credentials : lCredentials) {
        Assert.notNull(credentials.getAuthScopeHost());
        Assert.isTrue(credentials.getAuthScopePort() > 0);
        Assert.notNull(credentials.getUserName());
        Assert.notNull(credentials.getPassword());

        if (credentials instanceof NTCredentials) {
            Assert.notNull(((NTCredentials) credentials).getHost());
            Assert.notNull(((NTCredentials) credentials).getDomain());
        }
    }

    if (client == null) {
        if (connectionManager == null) {
            connectionManager = new MultiThreadedHttpConnectionManager();
        }

        client = new HttpClient(connectionManager);
    }

    client.getParams().setAuthenticationPreemptive(authenticationPreemptive);

    for (Credentials credentials : lCredentials) {
        AuthScope authScope = new AuthScope(credentials.getAuthScopeHost(), credentials.getAuthScopePort(),
                AuthScope.ANY_REALM);

        org.apache.commons.httpclient.Credentials httpCredentials = null;

        if (credentials instanceof NTCredentials) {
            httpCredentials = new org.apache.commons.httpclient.NTCredentials(credentials.getUserName(),
                    credentials.getPassword(), ((NTCredentials) credentials).getHost(),
                    ((NTCredentials) credentials).getDomain());
        } else {
            httpCredentials = new UsernamePasswordCredentials(credentials.getUserName(),
                    credentials.getPassword());
        }

        client.getState().setCredentials(authScope, httpCredentials);
    }
}

From source file:org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactoryTests.java

@Test
@Ignore//from   www . j  a v  a 2s  .co  m
public void restartWithKeepAlive() throws Exception {
    ConfigurableEmbeddedServletContainerFactory factory = getFactory();
    this.container = factory.getEmbeddedServletContainer(exampleServletRegistration());
    this.container.start();
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpClient client = new HttpClient(connectionManager);
    GetMethod get1 = new GetMethod("http://localhost:8080/hello");
    assertThat(client.executeMethod(get1), equalTo(200));
    get1.releaseConnection();

    this.container.stop();
    this.container = factory.getEmbeddedServletContainer(exampleServletRegistration());

    GetMethod get2 = new GetMethod("http://localhost:8080/hello");
    assertThat(client.executeMethod(get2), equalTo(200));
    get2.releaseConnection();
}