Example usage for org.apache.commons.httpclient HostConfiguration ANY_HOST_CONFIGURATION

List of usage examples for org.apache.commons.httpclient HostConfiguration ANY_HOST_CONFIGURATION

Introduction

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

Prototype

HostConfiguration ANY_HOST_CONFIGURATION

To view the source code for org.apache.commons.httpclient HostConfiguration ANY_HOST_CONFIGURATION.

Click Source Link

Usage

From source file:org.apache.airavata.client.stub.interpretor.WorkflowInterpretorStub.java

/**
 * Constructor that takes in a configContext and useseperate listner
 *///from w  ww.  jav a 2  s  .  co  m
public WorkflowInterpretorStub(org.apache.axis2.context.ConfigurationContext configurationContext,
        java.lang.String targetEndpoint, boolean useSeparateListener) throws org.apache.axis2.AxisFault {
    // To populate AxisService
    populateAxisService();
    populateFaults();
    MultiThreadedHttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager();
    httpConnectionManager.getParams().setMaxTotalConnections(10000);
    httpConnectionManager.getParams().setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 100);
    httpConnectionManager.getParams().setDefaultMaxConnectionsPerHost(200);
    HttpClient httpClient = new HttpClient(httpConnectionManager);
    _serviceClient = new org.apache.axis2.client.ServiceClient(configurationContext, _service);

    configurationContext = _serviceClient.getServiceContext().getConfigurationContext();
    configurationContext.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, true);
    configurationContext.setProperty(HTTPConstants.CACHED_HTTP_CLIENT, httpClient);
    configurationContext.setProperty(HTTPConstants.AUTO_RELEASE_CONNECTION, true);
    _serviceClient.getOptions().setTo(new org.apache.axis2.addressing.EndpointReference(targetEndpoint));
    _serviceClient.getOptions().setUseSeparateListener(useSeparateListener);
}

From source file:org.eclipse.mylyn.commons.net.WebUtil.java

private static void configureHttpClientConnectionManager(HttpClient client) {
    client.getHttpConnectionManager().getParams().setSoTimeout(WebUtil.SOCKET_TIMEOUT);
    client.getHttpConnectionManager().getParams().setConnectionTimeout(WebUtil.CONNNECT_TIMEOUT);
    // FIXME fix connection leaks
    if (CoreUtil.TEST_MODE) {
        client.getHttpConnectionManager().getParams()
                .setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 2);
    } else {//from w  w w .  j  ava 2s . c o  m
        client.getHttpConnectionManager().getParams().setMaxConnectionsPerHost(
                HostConfiguration.ANY_HOST_CONFIGURATION, NetUtil.getMaxHttpConnectionsPerHost());
        client.getHttpConnectionManager().getParams().setMaxTotalConnections(NetUtil.getMaxHttpConnections());
    }
}

From source file:org.eclipse.mylyn.commons.tests.net.WebUtilTest.java

public void testConfigureClient() throws Exception {
    WebLocation location = new WebLocation(TestUrl.DEFAULT.getHttpOk().toString());

    WebUtil.createHostConfiguration(client, location, null /*monitor*/);

    HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
    assertEquals(CoreUtil.TEST_MODE ? 2 : MAX_HTTP_HOST_CONNECTIONS_DEFAULT,
            params.getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION));
    assertEquals(CoreUtil.TEST_MODE ? 20 : MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT, params.getMaxTotalConnections());
}

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

/**
 * uses the configuration of this builder to generate a HttpClient
 * /* w  w  w.  j a v a 2 s .  co  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.jasig.portal.security.provider.SamlAssertionFilter.java

@Override
protected void initFilterBean() throws ServletException {
    this.connectionManager = new MultiThreadedHttpConnectionManager();
    final HttpConnectionManagerParams params = this.connectionManager.getParams();
    params.setMaxTotalConnections(this.maxTotalConnections);
    params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, this.maxTotalConnections);
    params.setConnectionTimeout(this.connectionTimeout);
    params.setSoTimeout(this.readTimeout);

    this.httpClient = new HttpClient(this.connectionManager);
}

From source file:org.kuali.rice.kew.config.ThinClientResourceLoader.java

protected void initializeHttpClientParams() {
    httpClientParams = new HttpClientParams();
    configureDefaultHttpClientParams(httpClientParams);
    Properties configProps = ConfigContext.getCurrentContextConfig().getProperties();
    for (Iterator iterator = configProps.keySet().iterator(); iterator.hasNext();) {
        String paramName = (String) iterator.next();
        if (paramName.startsWith("http.")) {
            HttpClientHelper.setParameter(httpClientParams, paramName, (String) configProps.get(paramName));
        }/*from w w  w  .j  a v a 2s  .c  om*/
    }

    String maxConnectionsValue = configProps.getProperty(MAX_CONNECTIONS);
    if (!StringUtils.isEmpty(maxConnectionsValue)) {
        Integer maxConnections = new Integer(maxConnectionsValue);
        Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>();
        maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, maxConnections);
        httpClientParams.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap);
        httpClientParams.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, maxConnections);
    }

    String connectionManagerTimeoutValue = configProps.getProperty(CONNECTION_MANAGER_TIMEOUT);
    if (!StringUtils.isEmpty(connectionManagerTimeoutValue)) {
        httpClientParams.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT,
                new Long(connectionManagerTimeoutValue));
    }

    String connectionTimeoutValue = configProps.getProperty(CONNECTION_TIMEOUT);
    if (!StringUtils.isEmpty(connectionTimeoutValue)) {
        httpClientParams.setIntParameter(HttpConnectionManagerParams.CONNECTION_TIMEOUT,
                new Integer(connectionTimeoutValue));
    }
}

From source file:org.kuali.rice.kew.config.ThinClientResourceLoader.java

protected void configureDefaultHttpClientParams(HttpParams params) {
    params.setParameter(HttpClientParams.CONNECTION_MANAGER_CLASS, MultiThreadedHttpConnectionManager.class);
    params.setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
    params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT,
            new Long(DEFAULT_CONNECTION_MANAGER_TIMEOUT));
    Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>();
    maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, new Integer(DEFAULT_MAX_CONNECTIONS));
    params.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap);
    params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS,
            new Integer(DEFAULT_MAX_CONNECTIONS));
    params.setIntParameter(HttpConnectionManagerParams.CONNECTION_TIMEOUT,
            new Integer(DEFAULT_CONNECTION_TIMEOUT));

    boolean retrySocketException = new Boolean(
            ConfigContext.getCurrentContextConfig().getProperty(RETRY_SOCKET_EXCEPTION_PROPERTY));
    if (retrySocketException) {
        LOG.info("Installing custom HTTP retry handler to retry requests in face of SocketExceptions");
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new CustomHttpMethodRetryHandler());
    }//from w  w  w .  j a va  2s . c o  m
}

From source file:org.kuali.rice.ksb.messaging.serviceconnectors.HttpInvokerConnector.java

protected void configureDefaultHttpClientParams(HttpParams params) {
    params.setParameter(HttpClientParams.CONNECTION_MANAGER_CLASS, MultiThreadedHttpConnectionManager.class);
    params.setParameter(HttpMethodParams.COOKIE_POLICY, CookiePolicy.RFC_2109);
    params.setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 10000);
    Map<HostConfiguration, Integer> maxHostConnectionsMap = new HashMap<HostConfiguration, Integer>();
    maxHostConnectionsMap.put(HostConfiguration.ANY_HOST_CONFIGURATION, new Integer(20));
    params.setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, maxHostConnectionsMap);
    params.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, 20);
    params.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 10000);
    params.setIntParameter(HttpConnectionParams.SO_TIMEOUT, 2 * 60 * 1000);

    boolean retrySocketException = new Boolean(
            ConfigContext.getCurrentContextConfig().getProperty(RETRY_SOCKET_EXCEPTION_PROPERTY));
    if (retrySocketException) {
        LOG.info("Installing custom HTTP retry handler to retry requests in face of SocketExceptions");
        params.setParameter(HttpMethodParams.RETRY_HANDLER, new CustomHttpMethodRetryHandler());
    }//from  w  ww  . ja  v a  2  s  .c  o m

}

From source file:org.sakaiproject.search.component.service.impl.BaseSearchServiceImpl.java

/**
 * Register a notification action to listen to events and modify the search
 * index// w  w w.ja  v a2s.com
 */
public void init() {

    try {

        // register a transient notification for resources
        notification = notificationService.addTransientNotification();

        // add all the functions that are registered to trigger search index
        // modification

        notification.setFunction(SearchService.EVENT_TRIGGER_SEARCH);
        if (triggerFunctions != null) {
            for (Iterator<String> ifn = triggerFunctions.iterator(); ifn.hasNext();) {
                String function = (String) ifn.next();
                notification.addFunction(function);
                if (log.isDebugEnabled()) {
                    log.debug("Adding Search Register " + function); //$NON-NLS-1$
                }
            }
        }

        // set the filter to any site related resource
        notification.setResourceFilter("/"); //$NON-NLS-1$

        // set the action
        notification.setAction(new SearchNotificationAction(searchIndexBuilder));

        // Configure params for the Connection Manager
        httpParams.setDefaultMaxConnectionsPerHost(20);
        httpParams.setMaxTotalConnections(30);

        // This next line may not be necessary since we specified default 2
        // lines ago, but here it is anyway
        httpParams.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, 20);

        // Set up the connection manager
        httpConnectionManager.setParams(httpParams);

        // Finally set up the static multithreaded HttpClient
        httpClient = new HttpClient(httpConnectionManager);

        if (diagnostics) {
            indexStorage.enableDiagnostics();
        } else {
            indexStorage.disableDiagnostics();
        }

        indexStorage.addReloadListener(new IndexReloadListener() {

            public void reloaded(long reloadStart, long reloadEnd) {
                if (diagnostics) {
                    log.info("Index Reloaded containing " + getNDocs() + " active documents and  "
                            + getPendingDocs() + " pending documents in " + (reloadEnd - reloadStart) + "ms");
                }
            }

        });

    } catch (Throwable t) {
        log.error("Failed to start ", t); //$NON-NLS-1$
    }

}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.HttpClientProxyUtil.java

public static void applyProxyToHttpClient(HttpClient httpClient, RemoteStorageContext ctx, Logger logger) {
    httpClient.setHttpConnectionManager(new CustomMultiThreadedHttpConnectionManager());

    // getting the timeout from RemoteStorageContext. The value we get depends on per-repo and global settings.
    // The value will "cascade" from repo level to global level, see imple of it.
    int timeout = ctx.getRemoteConnectionSettings().getConnectionTimeout();

    // getting the connection pool size, using a little trick to allow us "backdoor" to tune it using system
    // properties, but defaulting it to the same we had before (httpClient defaults)
    int connectionPoolSize = SystemPropertiesHelper.getInteger(CONNECTION_POOL_SIZE_KEY,
            MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS);

    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
    // httpClient.getHttpConnectionManager().getParams().setTcpNoDelay( true );
    httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(connectionPoolSize);
    // NOTE: connPool is _per_ repo, hence all of those will connect to same host (unless mirrors are used)
    // so, we are violating intentionally the RFC and we let the whole pool size to chase same host
    httpClient.getHttpConnectionManager().getParams()
            .setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, connectionPoolSize);

    // Setting auth if needed
    HostConfiguration httpConfiguration = httpClient.getHostConfiguration();

    // BASIC and DIGEST auth only
    RemoteAuthenticationSettings ras = ctx.getRemoteAuthenticationSettings();

    boolean isSimpleAuthUsed = false;
    boolean isNtlmUsed = false;

    if (ras != null) {
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.BASIC);

        if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
            // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras;

            // TODO - implement this
        } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
            NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

            // Using NTLM auth, adding it as first in policies
            authPrefs.add(0, AuthPolicy.NTLM);

            logger(logger).info("... authentication setup for NTLM domain '{}'", nras.getNtlmDomain());

            httpConfiguration.setHost(nras.getNtlmHost());

            httpClient.getState().setCredentials(AuthScope.ANY, new NTCredentials(nras.getUsername(),
                    nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()));

            isNtlmUsed = true;/*www. java2s .  co  m*/
        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

            // Using Username/Pwd auth, will not add NTLM
            logger(logger).info("... authentication setup for remote storage with username '{}'",
                    uras.getUsername());

            httpClient.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()));

            isSimpleAuthUsed = true;
        }

        httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    }

    RemoteProxySettings rps = ctx.getRemoteProxySettings();

    boolean isProxyUsed = false;

    if (rps.isEnabled()) {
        isProxyUsed = true;

        logger(logger).info("... proxy setup with host '{}'", rps.getHostname());

        httpConfiguration.setProxy(rps.getHostname(), rps.getPort());

        // check if we have non-proxy hosts
        if (rps.getNonProxyHosts() != null && !rps.getNonProxyHosts().isEmpty()) {
            Set<Pattern> nonProxyHostPatterns = new HashSet<Pattern>(rps.getNonProxyHosts().size());
            for (String nonProxyHostRegex : rps.getNonProxyHosts()) {
                try {
                    nonProxyHostPatterns.add(Pattern.compile(nonProxyHostRegex, Pattern.CASE_INSENSITIVE));
                } catch (PatternSyntaxException e) {
                    logger(logger).warn("Invalid non proxy host regex: {}", nonProxyHostRegex, e);
                }
            }
            httpConfiguration.getParams().setParameter(
                    CustomMultiThreadedHttpConnectionManager.NON_PROXY_HOSTS_PATTERNS_KEY,
                    nonProxyHostPatterns);
        }

        if (rps.getProxyAuthentication() != null) {
            ras = rps.getProxyAuthentication();

            List<String> authPrefs = new ArrayList<String>(2);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.BASIC);

            if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
                // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras;

                // TODO - implement this
            } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
                NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

                // Using NTLM auth, adding it as first in policies
                authPrefs.add(0, AuthPolicy.NTLM);

                if (ctx.getRemoteAuthenticationSettings() != null && (ctx
                        .getRemoteAuthenticationSettings() instanceof NtlmRemoteAuthenticationSettings)) {
                    logger(logger).warn("... Apache Commons HttpClient 3.x is unable to use NTLM auth scheme\n"
                            + " for BOTH server side and proxy side authentication!\n"
                            + " You MUST reconfigure server side auth and use BASIC/DIGEST scheme\n"
                            + " if you have to use NTLM proxy, otherwise it will not work!\n"
                            + " *** SERVER SIDE AUTH OVERRIDDEN");
                }

                logger(logger).info("... proxy authentication setup for NTLM domain '{}'",
                        nras.getNtlmDomain());

                httpConfiguration.setHost(nras.getNtlmHost());

                httpClient.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials(nras.getUsername(),
                        nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()));

                isNtlmUsed = true;
            } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
                UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

                // Using Username/Pwd auth, will not add NTLM
                logger(logger).info("... proxy authentication setup for remote storage with username '{}'",
                        uras.getUsername());

                httpClient.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()));
            }

            httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }
    }

    // set preemptive only for simplest scenario:
    // no proxy and BASIC auth is used
    if (isSimpleAuthUsed && !isProxyUsed) {
        logger(logger)
                .info("... simple scenario: simple authentication used with no proxy in between target and us,"
                        + " will use preemptive authentication");

        // we have authentication, let's do it preemptive
        httpClient.getParams().setAuthenticationPreemptive(true);
    }

    // mark the fact that NTLM is in use
    // but ONLY IF IT CHANGED!
    // Otherwise, doing it always, actually marks the ctx itself as "changed", causing an avalanche of other
    // consequences, like resetting all the HTTP clients of all remote storages (coz they think there is a change
    // in proxy or remote connection settings, etc).
    final Boolean isNtlmUsedOldValue = (Boolean) ctx.getContextObject(NTLM_IS_IN_USE_KEY);
    if (isNtlmUsedOldValue == null || isNtlmUsedOldValue.booleanValue() != isNtlmUsed) {
        if (isNtlmUsed) {
            ctx.putContextObject(NTLM_IS_IN_USE_KEY, Boolean.TRUE);
        } else {
            ctx.putContextObject(NTLM_IS_IN_USE_KEY, Boolean.FALSE);
        }
    }
}