Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory.

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:com.tremolosecurity.config.util.UnisonConfigManagerImpl.java

private void initSSL() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException,
        KeyStoreException, CertificateException, FileNotFoundException, IOException {
    if (this.getKeyManagerFactory() == null) {
        return;/*from w  w w  .ja  va2  s  . c  o m*/
    }

    KeyStore cacerts = KeyStore.getInstance(KeyStore.getDefaultType());

    String cacertsPath = System.getProperty("javax.net.ssl.trustStore");
    if (cacertsPath == null) {
        cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts";
    }

    cacerts.load(new FileInputStream(cacertsPath), null);

    Enumeration<String> enumer = cacerts.aliases();
    while (enumer.hasMoreElements()) {
        String alias = enumer.nextElement();
        java.security.cert.Certificate cert = cacerts.getCertificate(alias);
        this.ks.setCertificateEntry(alias, cert);
    }

    SSLContext sslctx = SSLContexts.custom().loadTrustMaterial(this.ks)
            .loadKeyMaterial(this.ks, this.cfg.getKeyStorePassword().toCharArray()).build();
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory();
    httpClientRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", sf)
            .register("https", sslsf).build();

    globalHttpClientConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES)
            .setRedirectsEnabled(false).setAuthenticationEnabled(false).build();

}

From source file:ee.ria.xroad.common.request.ManagementRequestClient.java

private static CloseableHttpClient createHttpClient(KeyManager km, TrustManager tm) throws Exception {
    RegistryBuilder<ConnectionSocketFactory> sfr = RegistryBuilder.<ConnectionSocketFactory>create();

    sfr.register("http", PlainConnectionSocketFactory.INSTANCE);

    SSLContext ctx = SSLContext.getInstance(CryptoUtils.SSL_PROTOCOL);
    ctx.init(km != null ? new KeyManager[] { km } : null, tm != null ? new TrustManager[] { tm } : null,
            new SecureRandom());

    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx,
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    sfr.register("https", sf);

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(sfr.build());
    cm.setMaxTotal(CLIENT_MAX_TOTAL_CONNECTIONS);
    cm.setDefaultMaxPerRoute(CLIENT_MAX_CONNECTIONS_PER_ROUTE);

    int timeout = SystemProperties.getClientProxyTimeout();
    int socketTimeout = SystemProperties.getClientProxyHttpClientTimeout();

    RequestConfig.Builder rb = RequestConfig.custom();
    rb.setConnectTimeout(timeout);//from  w ww. j  av a  2  s. com
    rb.setConnectionRequestTimeout(timeout);
    rb.setSocketTimeout(socketTimeout);

    HttpClientBuilder cb = HttpClients.custom();
    cb.setConnectionManager(cm);
    cb.setDefaultRequestConfig(rb.build());

    // Disable request retry
    cb.setRetryHandler(new DefaultHttpRequestRetryHandler(0, false));

    return cb.build();
}

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 {/*from  w ww  .  ja  va2  s  .co  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:org.neo4j.ogm.drivers.http.driver.HttpDriver.java

private synchronized CloseableHttpClient httpClient() {

    if (httpClient == null) { // most of the time this will be false, branch-prediction will be very fast and the lock released immediately

        try {/*from   w ww. jav a  2 s .  co m*/
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            SSLContext sslContext = SSLContext.getDefault();

            if (configuration.getTrustStrategy() != null) {

                if (configuration.getTrustStrategy().equals("ACCEPT_UNSIGNED")) {
                    sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build();

                    LOGGER.warn("Certificate validation has been disabled");
                }
            }

            // setup the default or custom ssl context
            httpClientBuilder.setSSLContext(sslContext);

            HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    hostnameVerifier);
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslSocketFactory).build();

            // allows multi-threaded use
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);

            Integer connectionPoolSize = configuration.getConnectionPoolSize();

            connectionManager.setMaxTotal(connectionPoolSize);
            connectionManager.setDefaultMaxPerRoute(connectionPoolSize);

            httpClientBuilder.setConnectionManager(connectionManager);

            httpClient = httpClientBuilder.build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    return httpClient;
}

From source file:org.keycloak.connections.httpclient.HttpClientBuilder.java

public CloseableHttpClient build() {
    X509HostnameVerifier verifier = null;
    if (this.verifier != null)
        verifier = new VerifierWrapper(this.verifier);
    else {/*from w  ww .jav a  2 s.co m*/
        switch (policy) {
        case ANY:
            verifier = new AllowAllHostnameVerifier();
            break;
        case WILDCARD:
            verifier = new BrowserCompatHostnameVerifier();
            break;
        case STRICT:
            verifier = new StrictHostnameVerifier();
            break;
        }
    }
    try {
        SSLConnectionSocketFactory sslsf = null;
        SSLContext theContext = sslContext;
        if (disableTrustManager) {
            theContext = SSLContext.getInstance("TLS");
            theContext.init(null, new TrustManager[] { new PassthroughTrustManager() }, new SecureRandom());
            verifier = new AllowAllHostnameVerifier();
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else if (theContext != null) {
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else if (clientKeyStore != null || truststore != null) {
            theContext = createSslContext("TLS", clientKeyStore, clientPrivateKeyPassword, truststore, null);
            sslsf = new SSLConnectionSocketFactory(theContext, verifier);
        } else {
            final SSLContext tlsContext = SSLContext.getInstance("TLS");
            tlsContext.init(null, null, null);
            sslsf = new SSLConnectionSocketFactory(tlsContext, verifier);
        }

        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout((int) establishConnectionTimeout)
                .setSocketTimeout((int) socketTimeout).build();

        org.apache.http.impl.client.HttpClientBuilder builder = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig).setSSLSocketFactory(sslsf)
                .setMaxConnTotal(connectionPoolSize).setMaxConnPerRoute(maxPooledPerRoute)
                .setConnectionTimeToLive(connectionTTL, connectionTTLUnit);

        if (proxyMappings != null && !proxyMappings.isEmpty()) {
            builder.setRoutePlanner(new ProxyMappingsAwareRoutePlanner(proxyMappings));
        }

        if (maxConnectionIdleTime > 0) {
            // Will start background cleaner thread
            builder.evictIdleConnections(maxConnectionIdleTime, maxConnectionIdleTimeUnit);
        }

        if (disableCookies)
            builder.disableCookieManagement();
        return builder.build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:br.com.intercomex.ws.GnreLoteRecepcao.java

/**
 * This is a sample web service operation
 *///from  www.jav a 2s.c  om
@WebMethod(operationName = "processar")
public br.gov.pe.gnre.TRetLoteGNRE processar(@WebParam(name = "gnreDadosMsg") TLoteGNRE TLoteGNRE) {
    br.gov.pe.gnre.TRetLoteGNRE retorno = null;
    try {
        loadConfig();
        XmlUtil util = new XmlUtil();
        //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf>
        String gnreDadosMsgSTR = util.convertToXml(TLoteGNRE, br.gov.pe.gnre.TLoteGNRE.class);
        //System.out.println("PARAMETRO envio ==== "+TLoteGNRE);
        //String gnreDadosMsgSTR= util.nodeToString((Node)TLoteGNRE);

        String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreLoteRecepcao\">"
                + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>"
                + "<soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsgSTR
                + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>";
        System.out.println("PARAMETRO envio ==== " + XML_DATA);

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8"));
        httpPost.setHeader(new BasicHeader("SOAPAction", action));
        StringEntity s = new StringEntity(XML_DATA, "UTF-8");
        httpPost.setEntity(s);
        FileInputStream instream = null;
        FileInputStream instreamTrust = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente));
        keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("JKS");
        instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado));
        trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray());

        SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore);
        builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray());
        SSLContext sslcontext = builder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        System.out.println("executing request" + httpPost.getRequestLine());
        HttpResponse response = httpclientSLL.execute(httpPost);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            String retornoStr = EntityUtils.toString(entity);
            System.out.println("Response  " + retornoStr);
            retorno = util.getTRetLoteGNRE(retornoStr);

        }
        if (entity != null) {
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    }

    return retorno;
}

From source file:br.com.intercomex.ws.EnviarLoteService.java

private String processarServico(Object TLoteGNRE, String urlParam, String actionParam) {

    br.gov.pe.gnre.TRetLoteGNRE retorno = null;
    String recibo = null;/* w  w w .  j a  v a 2 s .  c  o m*/
    try {
        loadConfig();
        XmlUtil util = new XmlUtil();
        //<TConsultaConfigUf xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><uf>MG</uf><receita>100048</receita></TConsultaConfigUf>
        System.out.println("PARAMETRO envio ==== " + TLoteGNRE);
        //String gnreDadosMsgSTR= util.convertToXml(TLoteGNRE, br.gov.pe.gnre.TLoteGNRE.class);
        //String gnreDadosMsgSTR= TLoteGNRE;
        String gnreDadosMsgSTR = util.nodeToString((Node) TLoteGNRE);

        String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreLoteRecepcao\">"
                + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>"
                + "<soap:Body><gnr:gnreDadosMsg>" + gnreDadosMsgSTR
                + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>";
        System.out.println("PARAMETRO envio ==== " + XML_DATA);

        HttpPost httpPost = new HttpPost(urlParam);
        httpPost.setHeader(new BasicHeader("Content-Type", "application/soap+xml;charset=UTF-8"));
        httpPost.setHeader(new BasicHeader("SOAPAction", actionParam));
        StringEntity s = new StringEntity(XML_DATA, "UTF-8");
        httpPost.setEntity(s);
        FileInputStream instream = null;
        FileInputStream instreamTrust = null;
        KeyStore keyStore = KeyStore.getInstance("PKCS12");
        instream = new FileInputStream(new File(caminhoDoCertificadoDoCliente));
        keyStore.load(instream, senhaDoCertificadoDoCliente.toCharArray());

        KeyStore trustStore = KeyStore.getInstance("JKS");
        instreamTrust = new FileInputStream(new File(arquivoCacertsGeradoParaCadaEstado));
        trustStore.load(instreamTrust, senhaDoCertificadoDoCliente.toCharArray());

        SSLContextBuilder builder = SSLContexts.custom().loadTrustMaterial(trustStore);
        builder.loadKeyMaterial(keyStore, senhaDoCertificadoDoCliente.toCharArray());
        SSLContext sslcontext = builder.build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
                SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
        CloseableHttpClient httpclientSLL = HttpClients.custom().setSSLSocketFactory(sslsf).build();

        System.out.println("executing request" + httpPost.getRequestLine());
        HttpResponse response = httpclientSLL.execute(httpPost);
        HttpEntity entity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
            String retornoStr = EntityUtils.toString(entity);
            System.out.println("Response  " + retornoStr);
            retorno = util.getTRetLoteGNRE(retornoStr);

            recibo = util.getRecibo(retornoStr);
            System.out.println("ResponseOBJ  " + recibo);

        }
        if (entity != null) {
            entity.consumeContent();
        }
        httpclient.getConnectionManager().shutdown();

    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyStoreException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (CertificateException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (UnrecoverableKeyException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    } catch (KeyManagementException ex) {
        Logger.getLogger(GnreConfigUF.class.getName()).log(Level.SEVERE, null, ex);
    }

    return recibo;
}

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

/**
 * Create a new client (with an explicit proxy and possibly transparent authentication)
 * //from   w w  w . j a v a2s  . c o 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);
}