Example usage for org.apache.http.impl.conn PoolingHttpClientConnectionManager PoolingHttpClientConnectionManager

List of usage examples for org.apache.http.impl.conn PoolingHttpClientConnectionManager PoolingHttpClientConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.conn PoolingHttpClientConnectionManager PoolingHttpClientConnectionManager.

Prototype

public PoolingHttpClientConnectionManager() 

Source Link

Usage

From source file:org.hupo.psi.mi.psicquic.ws.SolrBasedPsicquicService.java

private HttpClient createHttpClient() {

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setMaxTotal(maxTotalConnections);
    cm.setDefaultMaxPerRoute(defaultMaxConnectionsPerHost);
    RequestConfig.Builder requestBuilder = RequestConfig.custom();
    requestBuilder = requestBuilder.setConnectTimeout(connectionTimeOut);
    requestBuilder = requestBuilder.setSocketTimeout(soTimeOut);

    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setDefaultRequestConfig(requestBuilder.build());
    builder.setConnectionManager(cm);//from   www. j  av a 2  s  . c  o  m

    return builder.build();
}

From source file:org.apache.manifoldcf.agents.output.solr.HttpPoster.java

/** Initialize the standard http poster.
*///from   w w w  . j  a  va 2 s  . c om
public HttpPoster(String protocol, String server, int port, String webapp, String core, int connectionTimeout,
        int socketTimeout, String updatePath, String removePath, String statusPath, String realm, String userID,
        String password, String allowAttributeName, String denyAttributeName, String idAttributeName,
        String modifiedDateAttributeName, String createdDateAttributeName, String indexedDateAttributeName,
        String fileNameAttributeName, String mimeTypeAttributeName, String contentAttributeName,
        IKeystoreManager keystoreManager, Long maxDocumentLength, String commitWithin,
        boolean useExtractUpdateHandler) throws ManifoldCFException {
    // These are the paths to the handlers in Solr that deal with the actions we need to do
    this.postUpdateAction = updatePath;
    this.postRemoveAction = removePath;
    this.postStatusAction = statusPath;

    this.commitWithin = commitWithin;

    this.allowAttributeName = allowAttributeName;
    this.denyAttributeName = denyAttributeName;
    this.idAttributeName = idAttributeName;
    this.modifiedDateAttributeName = modifiedDateAttributeName;
    this.createdDateAttributeName = createdDateAttributeName;
    this.indexedDateAttributeName = indexedDateAttributeName;
    this.fileNameAttributeName = fileNameAttributeName;
    this.mimeTypeAttributeName = mimeTypeAttributeName;
    this.contentAttributeName = contentAttributeName;
    this.useExtractUpdateHandler = useExtractUpdateHandler;

    this.maxDocumentLength = maxDocumentLength;

    String location = "";
    if (webapp != null)
        location = "/" + webapp;
    if (core != null) {
        if (webapp == null)
            throw new ManifoldCFException("Webapp must be specified if core is specified.");
        location += "/" + core;
    }

    // Initialize standard solr-j.
    // First, we need an HttpClient where basic auth is properly set up.
    connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setMaxTotal(1);

    SSLConnectionSocketFactory myFactory;
    if (keystoreManager != null) {
        myFactory = new SSLConnectionSocketFactory(keystoreManager.getSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } else {
        // Use the "trust everything" one
        myFactory = new SSLConnectionSocketFactory(KeystoreManagerFactory.getTrustingSecureSocketFactory(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(connectionManager)
            .setMaxConnTotal(1).disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setRedirectStrategy(new DefaultRedirectStrategy()).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build());

    if (userID != null && userID.length() > 0 && password != null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        Credentials credentials = new UsernamePasswordCredentials(userID, password);
        if (realm != null)
            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, realm),
                    credentials);
        else
            credentialsProvider.setCredentials(AuthScope.ANY, credentials);

        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }

    HttpClient localClient = clientBuilder.build();

    String httpSolrServerUrl = protocol + "://" + server + ":" + port + location;
    solrServer = new ModifiedHttpSolrServer(httpSolrServerUrl, localClient, new XMLResponseParser());
}

From source file:org.archive.modules.recrawl.wbm.WbmPersistLoadProcessor.java

public synchronized HttpClient getHttpClient() {
    if (client == null) {
        if (conman == null) {
            conman = new PoolingHttpClientConnectionManager();
            conman.setDefaultMaxPerRoute(maxConnections);
            conman.setMaxTotal(Math.max(conman.getMaxTotal(), maxConnections));
        }// w ww  . j  a  va 2 s. c  o m
        HttpClientBuilder builder = HttpClientBuilder.create().disableCookieManagement()
                .setConnectionManager(conman);
        builder.useSystemProperties();
        // TODO: use setDefaultHeaders for adding requestHeaders? It's a bit painful
        // because we need to convert it to a Collection of Header objects.

        // config code for older version of httpclient.
        //            builder.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(socketTimeout).build());
        //            HttpParams params = client.getParams();
        //            params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, socketTimeout);
        //            params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout);
        // setup request/response intercepter for handling gzip-compressed response.
        // Disabled because httpclient 4.3.3 sends "Accept-Encoding: gzip,deflate" by
        // default. Response parsing will fail If gzip-decompression ResponseInterceptor
        // is installed.
        builder.addInterceptorLast(new HttpRequestInterceptor() {
            @Override
            public void process(final HttpRequest request, final HttpContext context) {
                //                    System.err.println("RequestInterceptor");
                //                    if (request.containsHeader("Accept-Encoding")) {
                //                        System.err.println("already has Accept-Encoding: " + request.getHeaders("Accept-Encoding")[0]);
                //                    }
                //                    if (gzipAccepted) {
                //                        if (!request.containsHeader("Accept-Encoding")) {
                //                            request.addHeader("Accept-Encoding", "gzip");
                //                        }
                //                    }
                // add extra headers configured.
                if (requestHeaders != null) {
                    for (Entry<String, String> ent : requestHeaders.entrySet()) {
                        request.addHeader(ent.getKey(), ent.getValue());
                    }
                }
            }
        });
        //            builder.addInterceptorFirst(new HttpResponseInterceptor() {
        //                @Override
        //                public void process(final HttpResponse response, final HttpContext context)
        //                        throws HttpException, IOException {
        //                    HttpEntity entity = response.getEntity();
        //                    Header ceheader = entity.getContentEncoding();
        //                    if (ceheader != null && contains(ceheader.getElements(), "gzip")) {
        //                        response.setEntity(new GzipInflatingHttpEntityWrapper(response.getEntity()));
        //                    }
        //                }
        //            });
        this.client = builder.build();
    }
    return client;
}

From source file:hello.MyPostHTTP.java

private Config getConfig(final String url, final ProcessContext context) {
    final String baseUrl = getBaseUrl(url);
    Config config = configMap.get(baseUrl);
    if (config != null) {
        return config;
    }/*from  w  w  w. j av a  2 s.  c  om*/

    final PoolingHttpClientConnectionManager conMan;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE)
            .asControllerService(SSLContextService.class);
    if (sslContextService == null) {
        conMan = new PoolingHttpClientConnectionManager();
    } else {
        final SSLContext sslContext;
        try {
            sslContext = createSSLContext(sslContextService);
        } catch (final Exception e) {
            throw new ProcessException(e);
        }

        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                new String[] { "TLSv1" }, null,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

        // Also use a plain socket factory for regular http connections (especially proxies)
        final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("https", sslsf)
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();

        conMan = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    }

    conMan.setDefaultMaxPerRoute(context.getMaxConcurrentTasks());
    conMan.setMaxTotal(context.getMaxConcurrentTasks());
    config = new Config(conMan);
    final Config existingConfig = configMap.putIfAbsent(baseUrl, config);

    return existingConfig == null ? config : existingConfig;
}

From source file:com.gooddata.GoodData.java

private HttpClientBuilder createHttpClientBuilder(final GoodDataSettings settings) {
    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    connectionManager.setDefaultMaxPerRoute(settings.getMaxConnections());
    connectionManager.setMaxTotal(settings.getMaxConnections());

    final SocketConfig.Builder socketConfig = SocketConfig.copy(SocketConfig.DEFAULT);
    socketConfig.setSoTimeout(settings.getSocketTimeout());
    connectionManager.setDefaultSocketConfig(socketConfig.build());

    final RequestConfig.Builder requestConfig = RequestConfig.copy(RequestConfig.DEFAULT);
    requestConfig.setConnectTimeout(settings.getConnectionTimeout());
    requestConfig.setConnectionRequestTimeout(settings.getConnectionRequestTimeout());
    requestConfig.setSocketTimeout(settings.getSocketTimeout());

    return HttpClientBuilder.create()
            .setUserAgent(StringUtils.isNotBlank(settings.getUserAgent())
                    ? String.format("%s %s", settings.getUserAgent(), getUserAgent())
                    : getUserAgent())//  ww  w. j a v  a 2 s  .c o m
            .setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig.build());
}

From source file:org.apache.manifoldcf.meridio.MeridioWrapper.java

/** The Meridio Wrapper constructor that calls the Meridio login method
*
*@param log                                     a handle to a Log4j logger
*@param meridioDmwsUrl          the URL to the Meridio Document Management Web Service
*@param meridioRmwsUrl          the URL to the Meridio Records Management Web Service
*@param dmwsProxyHost           the proxy for DMWS, or null if none
*@param dmwsProxyPort           the proxy port for DMWS, or -1 if default
*@param rmwsProxyHost           the proxy for RMWS, or null if none
*@param rmwsProxyPort           the proxy port for RMWS, or -1 if default
*@param userName                        the username of the user to log in as, must include the Windows, e.g. domain\\user
*@param password                        the password of the user who is logging in
*@param clientWorkstation       an identifier for the client workstation, could be the IP address, for auditing purposes
*@param protocolFactory         the protocol factory object to use for https communication
*@param engineConfigurationFile the engine configuration object to use to communicate with the web services
*
*@throws RemoteException        if an error is encountered logging into Meridio
*///from w w w.  j ava  2s  .  c o m
public MeridioWrapper(Logger log, URL meridioDmwsUrl, URL meridioRmwsUrl, URL meridioManifoldCFWSUrl,
        String dmwsProxyHost, String dmwsProxyPort, String rmwsProxyHost, String rmwsProxyPort,
        String mcwsProxyHost, String mcwsProxyPort, String userName, String password, String clientWorkstation,
        javax.net.ssl.SSLSocketFactory mySSLFactory, Class resourceClass, String engineConfigurationFile)
        throws RemoteException, NumberFormatException {
    // Initialize local instance variables
    oLog = log;
    this.engineConfiguration = new ResourceProvider(resourceClass, engineConfigurationFile);
    this.clientWorkstation = clientWorkstation;

    SSLConnectionSocketFactory myFactory = null;
    if (mySSLFactory != null) {
        myFactory = new SSLConnectionSocketFactory(mySSLFactory, new BrowserCompatHostnameVerifier());
    }

    // Set up the pool.
    // We have a choice: We can either have one httpclient instance, which gets reinitialized for every service
    // it connects with (because each one has a potentially different proxy setup), OR we can have a different
    // httpclient for each service.  The latter approach is obviously the more efficient, so I've chosen to do it
    // that way.

    // Parse the user and password values
    int index = userName.indexOf("\\");
    String domainUser;
    String domain;
    if (index != -1) {
        domainUser = userName.substring(index + 1);
        domain = userName.substring(0, index);
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "', domain is '" + domain + "'");
    } else {
        domain = null;
        domainUser = userName;
        if (oLog != null && oLog.isDebugEnabled())
            oLog.debug("Meridio: User is '" + domainUser + "'; there is no domain specified");
    }

    if (oLog != null && oLog.isDebugEnabled()) {
        if (password != null && password.length() > 0)
            oLog.debug("Meridio: Password exists");
        else
            oLog.debug("Meridio: Password is null");
    }

    int socketTimeout = 900000;
    int connectionTimeout = 300000;

    dmwsConnectionManager = new PoolingHttpClientConnectionManager();
    rmwsConnectionManager = new PoolingHttpClientConnectionManager();
    mcwsConnectionManager = new PoolingHttpClientConnectionManager();

    // Initialize the three httpclient objects

    CredentialsProvider dmwsCredentialsProvider = new BasicCredentialsProvider();
    CredentialsProvider rmwsCredentialsProvider = new BasicCredentialsProvider();

    RequestConfig.Builder dmwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
            .setExpectContinueEnabled(false).setConnectTimeout(connectionTimeout)
            .setConnectionRequestTimeout(socketTimeout);
    RequestConfig.Builder rmwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // Set up credentials
    if (domainUser != null) {
        dmwsCredentialsProvider.setCredentials(
                new AuthScope(meridioDmwsUrl.getHost(), meridioDmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
        rmwsCredentialsProvider.setCredentials(
                new AuthScope(meridioRmwsUrl.getHost(), meridioRmwsUrl.getPort()),
                new NTCredentials(domainUser, password, currentHost, domain));
    }

    // Initialize DMWS proxy
    if (dmwsProxyHost != null && dmwsProxyHost.length() > 0) {
        int port = (dmwsProxyPort == null || dmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(dmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            dmwsCredentialsProvider.setCredentials(new AuthScope(dmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(dmwsProxyHost, port);
        dmwsRequestBuilder.setProxy(proxy);
    }

    // Initialize RMWS proxy
    if (rmwsProxyHost != null && rmwsProxyHost.length() > 0) {
        int port = (rmwsProxyPort == null || rmwsProxyPort.length() == 0) ? 8080
                : Integer.parseInt(rmwsProxyPort);
        // Configure proxy authentication
        if (domainUser != null && domainUser.length() > 0) {
            rmwsCredentialsProvider.setCredentials(new AuthScope(rmwsProxyHost, port),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        HttpHost proxy = new HttpHost(rmwsProxyHost, port);
        rmwsRequestBuilder.setProxy(proxy);
    }

    dmwsHttpClient = HttpClients.custom().setConnectionManager(dmwsConnectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(dmwsRequestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(dmwsCredentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

    rmwsHttpClient = HttpClients.custom().setConnectionManager(rmwsConnectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(rmwsRequestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(rmwsCredentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

    if (meridioManifoldCFWSUrl != null) {
        CredentialsProvider mcwsCredentialsProvider = new BasicCredentialsProvider();

        RequestConfig.Builder mcwsRequestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        if (domainUser != null) {
            mcwsCredentialsProvider.setCredentials(
                    new AuthScope(meridioManifoldCFWSUrl.getHost(), meridioManifoldCFWSUrl.getPort()),
                    new NTCredentials(domainUser, password, currentHost, domain));
        }

        // Initialize MCWS proxy
        if (mcwsProxyHost != null && mcwsProxyHost.length() > 0) {
            int port = (mcwsProxyPort == null || mcwsProxyPort.length() == 0) ? 8080
                    : Integer.parseInt(mcwsProxyPort);
            // Configure proxy authentication
            if (domainUser != null && domainUser.length() > 0) {
                mcwsCredentialsProvider.setCredentials(new AuthScope(mcwsProxyHost, port),
                        new NTCredentials(domainUser, password, currentHost, domain));
            }

            HttpHost proxy = new HttpHost(mcwsProxyHost, port);
            mcwsRequestBuilder.setProxy(proxy);
        }

        mcwsHttpClient = HttpClients.custom().setConnectionManager(mcwsConnectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(mcwsRequestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(mcwsCredentialsProvider).setSSLSocketFactory(myFactory)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
                .setRedirectStrategy(new DefaultRedirectStrategy()).build();
    }

    // Set up the stub handles
    /*=================================================================
    * Get a handle to the DMWS
    *================================================================*/
    MeridioDMLocator meridioDMLocator = new MeridioDMLocator(engineConfiguration);
    MeridioDMSoapStub meridioDMWebService = new MeridioDMSoapStub(meridioDmwsUrl, meridioDMLocator);

    meridioDMWebService.setPortName(meridioDMLocator.getMeridioDMSoapWSDDServiceName());
    meridioDMWebService.setUsername(userName);
    meridioDMWebService.setPassword(password);
    meridioDMWebService._setProperty(HTTPCLIENT_PROPERTY, dmwsHttpClient);

    meridioDMWebService_ = meridioDMWebService;

    /*=================================================================
    * Get a handle to the RMWS
    *================================================================*/
    MeridioRMLocator meridioRMLocator = new MeridioRMLocator(engineConfiguration);
    MeridioRMSoapStub meridioRMWebService = new MeridioRMSoapStub(meridioRmwsUrl, meridioRMLocator);

    meridioRMWebService.setPortName(meridioRMLocator.getMeridioRMSoapWSDDServiceName());
    meridioRMWebService.setUsername(userName);
    meridioRMWebService.setPassword(password);
    meridioRMWebService._setProperty(HTTPCLIENT_PROPERTY, rmwsHttpClient);

    meridioRMWebService_ = meridioRMWebService;

    /*=================================================================
    * Get a handle to the MeridioMetaCarta Web Service
    *================================================================*/
    if (meridioManifoldCFWSUrl != null) {
        MetaCartaLocator meridioMCWS = new MetaCartaLocator(engineConfiguration);
        Service McWsService = null;
        MetaCartaSoapStub meridioMetaCartaWebService = new MetaCartaSoapStub(meridioManifoldCFWSUrl,
                McWsService);

        meridioMetaCartaWebService.setPortName(meridioMCWS.getMetaCartaSoapWSDDServiceName());
        meridioMetaCartaWebService.setUsername(userName);
        meridioMetaCartaWebService.setPassword(password);
        meridioMetaCartaWebService._setProperty(HTTPCLIENT_PROPERTY, mcwsHttpClient);

        meridioMCWS_ = meridioMetaCartaWebService;
    }

    this.loginUnified();
}

From source file:org.apache.manifoldcf.crawler.connectors.wiki.WikiConnector.java

protected void getSession() throws ManifoldCFException, ServiceInterruption {
    if (hasBeenSetup == false) {
        String emailAddress = params.getParameter(WikiConfig.PARAM_EMAIL);
        if (emailAddress != null)
            userAgent = "Mozilla/5.0 (ApacheManifoldCFWikiReader; "
                    + ((emailAddress == null) ? "" : emailAddress) + ")";
        else/*  ww  w. ja  va2  s. co  m*/
            userAgent = null;

        String protocol = params.getParameter(WikiConfig.PARAM_PROTOCOL);
        if (protocol == null || protocol.length() == 0)
            protocol = "http";
        String portString = params.getParameter(WikiConfig.PARAM_PORT);
        if (portString == null || portString.length() == 0)
            portString = null;
        String path = params.getParameter(WikiConfig.PARAM_PATH);
        if (path == null)
            path = "/w";

        baseURL = protocol + "://" + server + ((portString != null) ? ":" + portString : "") + path
                + "/api.php?format=xml&";

        int socketTimeout = 900000;
        int connectionTimeout = 300000;

        javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory
                .getTrustingSecureSocketFactory();
        SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
                new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        // Set up connection manager
        connectionManager = new PoolingHttpClientConnectionManager();

        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

        if (accessUser != null && accessUser.length() > 0 && accessPassword != null) {
            Credentials credentials = new UsernamePasswordCredentials(accessUser, accessPassword);
            if (accessRealm != null && accessRealm.length() > 0)
                credentialsProvider.setCredentials(
                        new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, accessRealm), credentials);
            else
                credentialsProvider.setCredentials(AuthScope.ANY, credentials);
        }

        RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
                .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true)
                .setExpectContinueEnabled(true).setConnectTimeout(connectionTimeout)
                .setConnectionRequestTimeout(socketTimeout);

        // If there's a proxy, set that too.
        if (proxyHost != null && proxyHost.length() > 0) {

            int proxyPortInt;
            if (proxyPort != null && proxyPort.length() > 0) {
                try {
                    proxyPortInt = Integer.parseInt(proxyPort);
                } catch (NumberFormatException e) {
                    throw new ManifoldCFException("Bad number: " + e.getMessage(), e);
                }
            } else
                proxyPortInt = 8080;

            // Configure proxy authentication
            if (proxyUsername != null && proxyUsername.length() > 0) {
                if (proxyPassword == null)
                    proxyPassword = "";
                if (proxyDomain == null)
                    proxyDomain = "";

                credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPortInt),
                        new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
            }

            HttpHost proxy = new HttpHost(proxyHost, proxyPortInt);
            requestBuilder.setProxy(proxy);
        }

        httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
                .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
                .setDefaultSocketConfig(
                        SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
                .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
                .setRequestExecutor(new HttpRequestExecutor(socketTimeout)).build();

        /*
        BasicHttpParams params = new BasicHttpParams();
        params.setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE,true);
        params.setIntParameter(CoreProtocolPNames.WAIT_FOR_CONTINUE,socketTimeout);
        params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY,true);
        params.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK,true);
        params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT,socketTimeout);
        params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,connectionTimeout);
        params.setBooleanParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);
        DefaultHttpClient localHttpClient = new DefaultHttpClient(connectionManager,params);
        // No retries
        localHttpClient.setHttpRequestRetryHandler(new HttpRequestRetryHandler()
          {
            public boolean retryRequest(
              IOException exception,
              int executionCount,
              HttpContext context)
            {
              return false;
            }
                 
          });
        */

        loginToAPI();

        hasBeenSetup = true;
    }
}

From source file:com.brsanthu.googleanalytics.GoogleAnalytics.java

protected CloseableHttpClient createHttpClient(GoogleAnalyticsConfig config) {
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(getDefaultMaxPerRoute(config));

    HttpClientBuilder builder = HttpClients.custom().setConnectionManager(connManager);

    if (isNotEmpty(config.getUserAgent())) {
        builder.setUserAgent(config.getUserAgent());
    }/*from  w w  w  .  ja v a  2s .  c  o m*/

    if (isNotEmpty(config.getProxyHost())) {
        builder.setProxy(new HttpHost(config.getProxyHost(), config.getProxyPort()));

        if (isNotEmpty(config.getProxyUserName())) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUserName(), config.getProxyPassword()));
            builder.setDefaultCredentialsProvider(credentialsProvider);
        }
    }

    return builder.build();
}