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

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

Introduction

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

Prototype

public void setMaxTotal(final int max) 

Source Link

Usage

From source file:com.zacwolf.commons.wbxcon.WBXCONorg.java

/**
 * Class <code>Contructor</code> initializes WBXCONorg instance for the given managed org (domain) instance.
 * As part of initialization the Constructor makes a call to establish orgID and namespaceID for the domain.
 * //  w ww  .  ja  va2s .  c om
 * The REST API calls are made via https GET and POST.  As such, the <code>HTTPSCLIENT</code> needs to be
 * initialized via a certificate stored in a default keystore.  Since the keystore contains a "static"
 * certificate provided by WebEx Connect, the keystore is generated "in source".  If WebEx Connect modifies
 * their default https certificate, you will need to download the latest version of this package from:<br />
 * <br />
 * <a href="https://github.com/ZacWolf/com.zacwolf.commons">https://github.com/ZacWolf/com.zacwolf.commons</a>
 * 
 * 
 * Whatever user is specified for wapiUSER, the following special privileges need to be granted to the account:
 * 
 * WBX:ManageDomain
 * WBX:ManageUsers
 * WBX:ManageRoles
 * 
 * @param domain_name   Name of the WebEx Connect Managed Org
 * @param wapiAUTHURL   (optional) URL used to override the default URL used to generate the initial login token
 * @param wapiUSER      WebEx UserName to use in making the REST calls
 * @param wapiPASS      WebEx user password to use in making the REST calls
 * @throws WBXCONexception
 */
WBXCONorg(final String domain_name, final String wapiAUTHURL, final String wapiUSER, final String wapiPASS)
        throws WBXCONexception {
    if (HTTPSCLIENT == null)
        try {
            //Quiet the various apache http client loggers
            Logger.getLogger("org.apache.http").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.wire").setLevel(Level.SEVERE);
            Logger.getLogger("org.apache.http.headers").setLevel(Level.SEVERE);
            System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
            System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
            System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http", "ERROR");
            System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.http.headers", "ERROR");

            final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
            cm.setMaxTotal(MAX_HTTP_REQUESTS);
            final KeyStore trustStore = KeyStore.getInstance("JCEKS");
            // Use the default keystore that is in the same package directory
            final InputStream instream = WBXCONorg.class.getClassLoader().getResourceAsStream(
                    WBXCONorg.class.getPackage().getName().replaceAll("\\.", "/") + "/" + TRUSTSTOREFILENAME);
            try {
                trustStore.load(instream, TRUSTSTOREPASS.toCharArray());
            } finally {
                instream.close();
            }
            final SSLContext sslcontext = SSLContexts.custom()// Trust own CA and all self-signed certs
                    .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
            final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                    new String[] { "TLSv1" }, // Allow TLSv1 protocol only
                    null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            final RequestConfig config = RequestConfig.custom().setConnectTimeout(HTTP_TIMEOUT * 60000)
                    .setConnectionRequestTimeout(HTTP_TIMEOUT * 60000).setSocketTimeout(HTTP_TIMEOUT * 60000)
                    .build();
            HTTPSCLIENT = HttpClients.custom().setConnectionManager(cm).setSSLSocketFactory(sslsf)
                    .setDefaultRequestConfig(config).build();
        } catch (final Exception e) {
            System.err.println(WBXCONorg.class.getCanonicalName()
                    + " UNABLE TO ESTABLISH HTTPSCLIENT FOR WAPI CALLS. All WAPI CALLS WILL FAIL!!!");
            e.printStackTrace();
            //System.exit(2);
        }
    Runtime.getRuntime().addShutdownHook(new Thread("WBXCONorg shutdownhook") {
        @Override
        public void run() {
            try {
                finalize();
            } catch (final Throwable e) {
                e.printStackTrace();
            }
        }
    });
    this.orgName = domain_name;
    this.wapiAUTHURL = wapiAUTHURL != null ? wapiAUTHURL : this.wapiAUTHURL;
    this.wapiUSER = wapiUSER + (!wapiUSER.endsWith("@" + domain_name) ? "@" + domain_name : "");
    this.wapiPASS = wapiPASS;

    final Document dom;
    try {
        System.out.println("===============  1");
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        System.out.println("===============  2");
        factory.setValidating(false);
        System.out.println("===============  3");
        factory.setCoalescing(true);
        System.out.println("===============  4");
        final DocumentBuilder db = factory.newDocumentBuilder();
        System.out.println("===============  5");
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        System.out.println("===============  6");
        params.add(new BasicNameValuePair("cmd", "get"));
        System.out.println("===============  7");
        params.add(new BasicNameValuePair("type", "org"));
        System.out.println("===============  8");
        params.add(new BasicNameValuePair("select", "org/orgID:/org/namespaceID:ext/WBX/PWSRule"));
        System.out.println("===============  9");
        params.add(new BasicNameValuePair("id", "current"));
        System.out.println("===============  10");
        System.out.println("===============  getDomainCredToken() :" + getDomainCredToken());
        params.add(new BasicNameValuePair("cred", getDomainCredToken()));
        System.out.println("===============  11");
        System.out.println("===============  params" + params.toString());
        System.out.println("===============Before wapiURL :" + this.wapiURL);
        final HttpPost httpPost = new HttpPost(this.wapiURL);
        System.out.println("=============== after wapiURL :" + this.wapiURL);

        httpPost.setEntity(new UrlEncodedFormEntity(params, org.apache.http.Consts.UTF_8));
        System.out.println("===============  12");
        final CloseableHttpResponse httpRes = HTTPSCLIENT.execute(httpPost, new BasicHttpContext());
        System.out.println("===============  13");

        if (httpRes == null) {
            System.out.println("===============  httpRes is NULL");
        }

        try {
            dom = db.parse(httpRes.getEntity().getContent());
            System.out.println("===============  14");
        } finally {
            httpRes.close();
        }
    } catch (final Exception e) {
        throw new WBXCONexception(e);
    }
    final NodeList result = dom.getElementsByTagName("result");
    if (result == null || result.item(0) == null
            || !result.item(0).getTextContent().equalsIgnoreCase("success"))
        throw new WBXCONexception(
                "ERROR::WBXCONorg:constructor(\"" + domain_name + "\")::" + documentGetErrorString(dom));

    this.orgID = dom.getElementsByTagName("orgID").item(0).getTextContent();
    this.namespaceID = dom.getElementsByTagName("namespaceID").item(0).getTextContent();
    this.passwordrule = new PWSRule(Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumLength_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumAlpha_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumNumeric_9")),
            Integer.parseInt(documentGetTextContentByTagName(dom, "PWMinimumSpecial_9")),
            documentGetTextContentByTagName(dom, "PWRequireMixedCase_B").equalsIgnoreCase("true"));
    this.wapiUser = restapiAccountGet(this.wapiUSER);
}

From source file:org.wso2.carbon.mdm.mobileservices.windows.common.authenticator.OAuthTokenValidationStubFactory.java

/**
 * Creates an instance of PoolingHttpClientConnectionManager using HttpClient 4.x APIs
 *
 * @param properties Properties to configure PoolingHttpClientConnectionManager
 * @return An instance of properly configured PoolingHttpClientConnectionManager
 *//*from w ww. j ava  2 s. c om*/
private HttpClientConnectionManager createClientConnectionManager(Properties properties) {
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    if (properties != null) {
        String maxConnectionsPerHostParam = properties
                .getProperty(PluginConstants.AuthenticatorProperties.MAX_CONNECTION_PER_HOST);
        if (maxConnectionsPerHostParam == null || maxConnectionsPerHostParam.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("MaxConnectionsPerHost parameter is not explicitly defined. Therefore, the default, "
                        + "which is 2, will be used");
            }
        } else {
            connectionManager.setDefaultMaxPerRoute(Integer.parseInt(maxConnectionsPerHostParam));
        }

        String maxTotalConnectionsParam = properties
                .getProperty(PluginConstants.AuthenticatorProperties.MAX_TOTAL_CONNECTIONS);
        if (maxTotalConnectionsParam == null || maxTotalConnectionsParam.isEmpty()) {
            if (log.isDebugEnabled()) {
                log.debug("MaxTotalConnections parameter is not explicitly defined. Therefore, the default, "
                        + "which is 10, will be used");
            }
        } else {
            connectionManager.setMaxTotal(Integer.parseInt(maxTotalConnectionsParam));
        }
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Properties, i.e. MaxTotalConnections/MaxConnectionsPerHost, required to tune the "
                    + "HttpClient used in OAuth token validation service stub instances are not provided. "
                    + "Therefore, the defaults, 2/10 respectively, will be used");
        }
    }
    return connectionManager;
}

From source file:com.ibm.og.client.ApacheClient.java

private HttpClientConnectionManager createConnectionManager() {
    final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(
            RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", createPlainConnectionSocketFactory())
                    .register("https", createSslConnectionSocketFactory()).build(),
            null, null, null, -1, TimeUnit.MILLISECONDS);
    manager.setDefaultSocketConfig(createSocketConfig());
    manager.setMaxTotal(Integer.MAX_VALUE);
    manager.setDefaultMaxPerRoute(Integer.MAX_VALUE);
    manager.setValidateAfterInactivity(this.validateAfterInactivity);
    return manager;
}

From source file:com.spotify.docker.client.DefaultDockerClient.java

private PoolingHttpClientConnectionManager getConnectionManager(Builder builder) {
    final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
            getSchemeRegistry(builder));

    // Use all available connections instead of artificially limiting ourselves to 2 per server.
    cm.setMaxTotal(builder.connectionPoolSize);
    cm.setDefaultMaxPerRoute(cm.getMaxTotal());

    return cm;//from  w ww  . j a v  a  2 s  .c om
}

From source file:com.uber.stream.kafka.mirrormaker.manager.core.ControllerHelixManager.java

public ControllerHelixManager(SourceKafkaClusterValidationManager srcKafkaValidationManager,
        ManagerConf managerConf) {/*from  w ww  . j  a va 2  s.c om*/
    _conf = managerConf;
    _enableRebalance = managerConf.getEnableRebalance();
    _srcKafkaValidationManager = srcKafkaValidationManager;
    _initMaxNumPartitionsPerRoute = managerConf.getInitMaxNumPartitionsPerRoute();
    _maxNumPartitionsPerRoute = managerConf.getMaxNumPartitionsPerRoute();
    _initMaxNumWorkersPerRoute = managerConf.getInitMaxNumWorkersPerRoute();
    _maxNumWorkersPerRoute = managerConf.getMaxNumWorkersPerRoute();
    _workloadRefreshPeriodInSeconds = managerConf.getWorkloadRefreshPeriodInSeconds();
    _workerHelixManager = new WorkerHelixManager(managerConf);
    _pipelineWorkloadMap = new ConcurrentHashMap<>();
    _helixZkURL = HelixUtils.getAbsoluteZkPathForHelix(managerConf.getManagerZkStr());
    _helixClusterName = MANAGER_CONTROLLER_HELIX_PREFIX + "-" + managerConf.getManagerDeployment();
    _instanceId = managerConf.getManagerInstanceId();
    _topicToPipelineInstanceMap = new ConcurrentHashMap<>();
    _pipelineToInstanceMap = new ConcurrentHashMap<>();
    _availableControllerList = new ArrayList<>();
    _routeToCounterMap = new ConcurrentHashMap<>();
    _zkClient = new ZkClient(_helixZkURL, 30000, 30000, ZKStringSerializer$.MODULE$);
    registerMetrics();

    PoolingHttpClientConnectionManager limitedConnMgr = new PoolingHttpClientConnectionManager();
    // TODO: make it configurable
    limitedConnMgr.setDefaultMaxPerRoute(100);
    limitedConnMgr.setMaxTotal(100);
    _httpClient = HttpClients.createMinimal(limitedConnMgr);
    _controllerPort = managerConf.getControllerPort();
    // requestConfig is immutable. These three timeouts are for
    // 1. getting connection from connection manager;
    // 2. establishing connection with server;
    // 3. getting next data snippet from server.
    _requestConfig = RequestConfig.custom().setConnectionRequestTimeout(30000).setConnectTimeout(30000)
            .setSocketTimeout(30000).build();
}

From source file:de.tudarmstadt.ukp.shibhttpclient.ShibHttpClient.java

/**
 * Create a new client (with an explicit proxy and possibly transparent authentication)
 * // w w w.java2  s . co m
 * @param aIdpUrl
 *            the URL of the IdP. Should probably be something ending in "/SAML2/SOAP/ECP"
 * @param aUsername
 *            the user name to log into the IdP.
 * @param aPassword
 *            the password to log in to the IdP.
 * @param aProxy
 *            if not {@code null}, use this proxy instead of the default system proxy (if any)
 * @param anyCert
 *            if {@code true}, accept any certificate from any remote host. Otherwise,
 *            certificates need to be installed in the JRE.
 * @param transparentAuth
 *            if {@code true} (default), add a HttpRequestPostProcessor to transparently 
 *            authenticate. Otherwise, you must handle the authentication process yourself.
 */
public ShibHttpClient(String aIdpUrl, String aUsername, String aPassword, HttpHost aProxy, boolean anyCert,
        boolean transparentAuth) {

    setIdpUrl(aIdpUrl);
    setUsername(aUsername);
    setPassword(aPassword);

    // Use a pooling connection manager, because we'll have to do a call out to the IdP
    // while still being in a connection with the SP
    PoolingHttpClientConnectionManager connMgr;
    if (anyCert) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("http", new PlainConnectionSocketFactory())
                    .register("https", new SSLConnectionSocketFactory(builder.build(),
                            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER))
                    .build();
            connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        } catch (GeneralSecurityException e) {
            // There shouldn't be any of these exceptions, because we do not use an actual
            // keystore
            throw new IllegalStateException(e);
        }
    } else {
        connMgr = new PoolingHttpClientConnectionManager();
    }
    connMgr.setMaxTotal(10);
    connMgr.setDefaultMaxPerRoute(5);

    // The client needs to remember the auth cookie
    cookieStore = new BasicCookieStore();
    RequestConfig globalRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BROWSER_COMPATIBILITY)
            .build();

    // Let's throw all common client elements into one builder object
    HttpClientBuilder customClient = HttpClients.custom().setConnectionManager(connMgr)
            // The client needs to remember the auth cookie
            .setDefaultRequestConfig(globalRequestConfig).setDefaultCookieStore(cookieStore)
            // Add the ECP/PAOS headers - needs to be added first so the cookie we get from
            // the authentication can be handled by the RequestAddCookies interceptor later
            .addInterceptorFirst(new HttpRequestPreprocessor());

    // Automatically log into IdP if transparent Shibboleth authentication handling is requested (default)
    if (transparentAuth) {
        customClient = customClient.addInterceptorFirst(new HttpRequestPostprocessor());
    }

    // Build the client with/without proxy settings 
    if (aProxy == null) {
        // use the proxy settings of the JVM, if specified 
        client = customClient.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .build();
    } else {
        // use the explicit proxy
        client = customClient.setProxy(aProxy).build();
    }

    parserPool = new BasicParserPool();
    parserPool.setNamespaceAware(true);
}

From source file:com.thinkbiganalytics.rest.JerseyRestClient.java

public JerseyRestClient(JerseyClientConfig config) {
    useConnectionPooling = config.isUseConnectionPooling();
    SSLContext sslContext = null;
    if (config.isHttps()) {
        SslConfigurator sslConfig = null;
        byte[] keyStoreFile = null;
        byte[] truststoreFile = null;

        try {//  w w w  .  j a  v a2s .  c  o  m
            if (StringUtils.isNotBlank(config.getKeystorePath())) {
                InputStream keystore = JerseyRestClient.class.getResourceAsStream(config.getKeystorePath());
                if (keystore != null) {
                    keyStoreFile = ByteStreams.toByteArray(keystore);
                }
            }
        } catch (IOException e) {
        }

        try {
            if (StringUtils.isNotBlank(config.getTruststorePath())) {
                InputStream truststore = JerseyRestClient.class.getResourceAsStream(config.getTruststorePath());
                if (truststore != null) {
                    truststoreFile = ByteStreams.toByteArray(truststore);
                }
            }
        } catch (IOException e) {
        }

        if (keyStoreFile != null) {
            sslConfig = SslConfigurator.newInstance()
                    .trustStoreBytes(truststoreFile != null ? truststoreFile : keyStoreFile)
                    .trustStorePassword(config.getTruststorePassword() != null ? config.getTruststorePassword()
                            : config.getKeystorePassword())
                    .trustStoreType(config.getTrustStoreType())
                    .keyStoreBytes(keyStoreFile != null ? keyStoreFile : truststoreFile)
                    .keyStorePassword(config.getKeystorePassword());
        } else {
            sslConfig = SslConfigurator.newInstance()
                    .keyStoreFile(config.getKeystorePath() == null ? config.getTruststorePath()
                            : config.getKeystorePath())
                    .keyStorePassword(config.getKeystorePassword() == null ? config.getTruststorePassword()
                            : config.getKeystorePassword())
                    .trustStoreFile(config.getTruststorePath() == null ? config.getKeystorePath()
                            : config.getTruststorePath())
                    .trustStorePassword(config.getTruststorePassword() == null ? config.getKeystorePassword()
                            : config.getTruststorePassword())
                    .trustStoreType(config.getTrustStoreType());
        }

        try {
            sslContext = sslConfig.createSSLContext();
        } catch (Exception e) {
            log.error("ERROR creating CLient SSL Context.  " + e.getMessage()
                    + " Falling back to Jersey Client without SSL.  Rest Integration with '" + config.getUrl()
                    + "'  will probably not work until this is fixed!");
        }
    }

    ClientConfig clientConfig = new ClientConfig();

    // Add in Timeouts if configured.  Values are in milliseconds
    if (config.getReadTimeout() != null) {
        clientConfig.property(ClientProperties.READ_TIMEOUT, config.getReadTimeout());
    }
    if (config.getConnectTimeout() != null) {
        clientConfig.property(ClientProperties.CONNECT_TIMEOUT, config.getConnectTimeout());
    }

    if (useConnectionPooling) {

        PoolingHttpClientConnectionManager connectionManager = null;
        if (sslContext != null) {

            HostnameVerifier defaultHostnameVerifier = new DefaultHostnameVerifier();

            LayeredConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    defaultHostnameVerifier);

            final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory).build();

            connectionManager = new PoolingHttpClientConnectionManager(registry);
        } else {
            connectionManager = new PoolingHttpClientConnectionManager();
        }
        connectionManager.setDefaultMaxPerRoute(100); // # of connections allowed per host/address
        connectionManager.setMaxTotal(200); // number of connections allowed in total

        clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
        HttpUrlConnectorProvider connectorProvider = new HttpUrlConnectorProvider();
        clientConfig.connectorProvider(connectorProvider);

    }

    clientConfig.register(MultiPartFeature.class);

    // allow derived classes to modify the client config
    extendClientConfig(clientConfig);

    if (sslContext != null) {
        log.info("Created new Jersey Client with SSL connecting to {} ", config.getUrl());
        client = new JerseyClientBuilder().withConfig(clientConfig).sslContext(sslContext).build();
    } else {
        log.info("Created new Jersey Client without SSL connecting to {} ", config.getUrl());
        client = JerseyClientBuilder.createClient(clientConfig);
    }

    // Register Jackson for the internal mapper
    objectMapper = new JacksonObjectMapperProvider().getContext(null);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    //register custom features
    registerClientFeatures(client);

    // Configure authentication
    if (StringUtils.isNotBlank(config.getUsername())) {
        HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic(config.getUsername(),
                config.getPassword());
        client.register(feature);
    }
    this.uri = config.getUrl();
    this.username = config.getUsername();

    if (StringUtils.isNotBlank(config.getHost()) && !HOST_NOT_SET_VALUE.equals(config.getHost())) {
        this.isHostConfigured = true;
    } else {
        log.info("Jersey Rest Client not initialized.  Host name is Not set!!");
    }
}

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 a  v  a2  s  .c  o m

    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.github.lpezet.antiope.dao.DefaultHttpClientFactory.java

@Override
public HttpClient createHttpClient(APIConfiguration pConfiguration) {

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> oConnFactory = new ManagedHttpClientConnectionFactory(
            new DefaultHttpRequestWriterFactory(), new DefaultHttpResponseParserFactory());

    SSLContext oSslContext = null;
    X509HostnameVerifier oHostnameVerifier = null;
    if (pConfiguration.isCheckSSLCertificates()) {
        oSslContext = SSLContexts.createSystemDefault();
        oHostnameVerifier = new BrowserCompatHostnameVerifier();
    } else {/* w  w  w.ja v  a2 s . c  om*/
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        // Install the all-trusting trust manager
        try {
            final SSLContext sslContext = SSLContext.getInstance(SSL);
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            //final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            oSslContext = sslContext;
        } catch (NoSuchAlgorithmException e) {
            throw new APIClientException(e);
        } catch (KeyManagementException e) {
            throw new APIClientException(e);
        }
        oHostnameVerifier = new AllowAllHostnameVerifier();
    }

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> oSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(HTTP, PlainConnectionSocketFactory.INSTANCE)
            .register(HTTPS, new SSLConnectionSocketFactory(oSslContext, oHostnameVerifier)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver oDnsResolver = new SystemDefaultDnsResolver(); /* {
                                                               @Override
                                                               public InetAddress[] resolve(final String host) throws UnknownHostException {
                                                               if (host.equalsIgnoreCase("myhost")) {
                                                               return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
                                                               } else {
                                                               return super.resolve(host);
                                                               }
                                                               }
                                                               };*/

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager oConnManager = new PoolingHttpClientConnectionManager(
            oSocketFactoryRegistry, oConnFactory, oDnsResolver);

    // Create socket configuration
    SocketConfig oSocketConfig = SocketConfig.custom().setTcpNoDelay(true)
            .setSoTimeout(pConfiguration.getSocketTimeout()).build();

    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    oConnManager.setDefaultSocketConfig(oSocketConfig);
    // connManager.setSocketConfig(new HttpHost("somehost", 80), oSocketConfig);

    // Create message constraints
    MessageConstraints oMessageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig oConnectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(oMessageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    oConnManager.setDefaultConnectionConfig(oConnectionConfig);
    // connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    oConnManager.setMaxTotal(100);
    oConnManager.setDefaultMaxPerRoute(10);
    //oConnManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore oCookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    //
    // Create global request configuration
    RequestConfig oDefaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            //.setExpectContinueEnabled(true)         // WARNING: setting it to true slows things down by 4s!!!!
            .setStaleConnectionCheckEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC))
            .setConnectTimeout(pConfiguration.getConnectionTimeout()).build();

    CredentialsProvider oCredentialsProvider = new BasicCredentialsProvider();
    HttpHost oProxy = null;

    if (pConfiguration.getProxyHost() != null && pConfiguration.getProxyPort() > 0) {
        String proxyHost = pConfiguration.getProxyHost();
        int proxyPort = pConfiguration.getProxyPort();
        String proxyUsername = pConfiguration.getProxyUsername();
        String proxyPassword = pConfiguration.getProxyPassword();
        String proxyDomain = pConfiguration.getProxyDomain();
        String proxyWorkstation = pConfiguration.getProxyWorkstation();

        oProxy = new HttpHost(proxyHost, proxyPort);

        if (proxyUsername != null && proxyPassword != null) {
            oCredentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, proxyWorkstation, proxyDomain));
        }
    }

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient oHttpClient = HttpClients.custom().setConnectionManager(oConnManager)
            .setDefaultCookieStore(oCookieStore).setDefaultCredentialsProvider(oCredentialsProvider)
            .setProxy(oProxy).setDefaultRequestConfig(oDefaultRequestConfig).build();

    return oHttpClient;
    /*
    RequestConfig oRequestConfig = RequestConfig.custom()
    .setConnectTimeout(pConfiguration.getConnectionTimeout())
    .setSocketTimeout(pConfiguration.getSocketTimeout())
    .setStaleConnectionCheckEnabled(true)
    .build();
    */
}