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: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  ww  . j  av  a 2 s.  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:com.aliyun.oss.common.comm.DefaultServiceClient.java

protected HttpClientConnectionManager createHttpClientConnectionManager() {
    SSLContext sslContext = null;
    try {/*from   www.j a  v a 2 s . c  o  m*/
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {

            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        }).build();

    } catch (Exception e) {
        throw new ClientException(e.getMessage());
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register(Protocol.HTTP.toString(), PlainConnectionSocketFactory.getSocketFactory())
            .register(Protocol.HTTPS.toString(), sslSocketFactory).build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnections());
    connectionManager.setMaxTotal(config.getMaxConnections());
    connectionManager.setValidateAfterInactivity(config.getValidateAfterInactivity());
    connectionManager.setDefaultSocketConfig(
            SocketConfig.custom().setSoTimeout(config.getSocketTimeout()).setTcpNoDelay(true).build());
    if (config.isUseReaper()) {
        IdleConnectionReaper.setIdleConnectionTime(config.getIdleConnectionTime());
        IdleConnectionReaper.registerConnectionManager(connectionManager);
    }
    return connectionManager;
}

From source file:nl.uva.mediamosa.impl.MediaMosaImpl.java

private HttpClient getHttpClient() {
    HttpClientBuilder b = HttpClientBuilder.create().setDefaultCookieStore(httpCookieStore);

    SSLContext sslContext = null;
    try {//from   w  ww  . j a  v  a  2  s . com
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        log.warn("Unexpected error occurerd while setting up SSL context", e);
    }
    b.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 connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
    b.setConnectionManager(connMgr);

    return b.build();
}

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

/** Initialize the standard http poster.
*//*from www  .  j  a va 2 s  . c o m*/
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.apache.solr.util.SSLTestConfig.java

/** 
 * Constructs a new SSLConnectionSocketFactory for HTTP <b>clients</b> to use when communicating 
 * with servers which have been configured based on the settings of this object. Will return null
 * unless {@link #isSSLMode} is true./*from ww  w .  j  a  v a  2s.  com*/
 */
public SSLConnectionSocketFactory buildClientSSLConnectionSocketFactory() {
    if (!isSSLMode()) {
        return null;
    }
    SSLConnectionSocketFactory sslConnectionFactory;
    try {
        boolean sslCheckPeerName = toBooleanDefaultIfNull(
                toBooleanObject(System.getProperty(HttpClientUtil.SYS_PROP_CHECK_PEER_NAME)), true);
        SSLContext sslContext = buildClientSSLContext();
        if (sslCheckPeerName == false) {
            sslConnectionFactory = new SSLConnectionSocketFactory(sslContext,
                    SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        } else {
            sslConnectionFactory = new SSLConnectionSocketFactory(sslContext);
        }
    } catch (KeyManagementException | UnrecoverableKeyException | NoSuchAlgorithmException
            | KeyStoreException e) {
        throw new IllegalStateException("Unable to setup https scheme for HTTPClient to test SSL.", e);
    }
    return sslConnectionFactory;
}

From source file:org.jboss.as.test.integration.management.http.HttpGenericOperationUnitTestCase.java

private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {/* w ww.  j  a  v a 2 s .  c o  m*/
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory()).build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create().setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.infinispan.server.test.rest.security.RESTCertSecurityTest.java

public static CloseableHttpClient securedClient(String alias) {
    try {/*  ww  w  .  j a v a 2 s  . com*/
        SSLContext ctx = SSLContext.getInstance("TLS");
        JBossJSSESecurityDomain jsseSecurityDomain = new JBossJSSESecurityDomain("client_cert_auth");
        jsseSecurityDomain.setKeyStorePassword("changeit");
        ClassLoader tccl = Thread.currentThread().getContextClassLoader();
        URL keystore = tccl.getResource("client.keystore");
        jsseSecurityDomain.setKeyStoreURL(keystore.getPath());
        jsseSecurityDomain.setClientAlias(alias);
        jsseSecurityDomain.reloadKeyAndTrustStore();
        KeyManager[] keyManagers = jsseSecurityDomain.getKeyManagers();
        TrustManager[] trustManagers = jsseSecurityDomain.getTrustManagers();
        ctx.init(keyManagers, trustManagers, null);
        X509HostnameVerifier verifier = new X509HostnameVerifier() {

            @Override
            public void verify(String s, SSLSocket sslSocket) throws IOException {
            }

            @Override
            public void verify(String s, X509Certificate x509Certificate) throws SSLException {
            }

            @Override
            public void verify(String s, String[] strings, String[] strings1) throws SSLException {
            }

            @Override
            public boolean verify(String string, SSLSession ssls) {
                return true;
            }
        };
        ConnectionSocketFactory sslssf = new SSLConnectionSocketFactory(ctx, verifier);//SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ConnectionSocketFactory plainsf = new PlainConnectionSocketFactory();
        Registry<ConnectionSocketFactory> sr = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", plainsf).register("https", sslssf).build();
        HttpClientConnectionManager pcm = new PoolingHttpClientConnectionManager(sr);
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).build();

        return httpClient;
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
}

From source file:org.apache.juneau.rest.client.RestClientBuilder.java

/**
 * Creates the {@link HttpClientConnectionManager} returned by {@link #createConnectionManager()}.
 * <p>/*from w w  w  .  j a  v  a 2s.  c  om*/
 * Subclasses can override this method to provide their own connection manager.
 * <p>
 * The default implementation returns an instance of a {@link PoolingHttpClientConnectionManager}.
 *
 * @return The HTTP client builder to use to create the HTTP client.
 */
protected HttpClientConnectionManager createConnectionManager() {
    if (sslOpts != null) {
        HostnameVerifier hv = null;
        switch (sslOpts.getHostVerify()) {
        case LAX:
            hv = new NoopHostnameVerifier();
            break;
        case DEFAULT:
            hv = new DefaultHostnameVerifier();
            break;
        default:
            throw new RuntimeException("Programmer error");
        }

        for (String p : StringUtils.split(sslOpts.getProtocols(), ',')) {
            try {
                TrustManager tm = new SimpleX509TrustManager(
                        sslOpts.getCertValidate() == SSLOpts.CertValidate.LAX);

                SSLContext ctx = SSLContext.getInstance(p);
                ctx.init(null, new TrustManager[] { tm }, null);

                // Create a socket to ensure this algorithm is acceptable.
                // This will correctly disallow certain configurations (such as SSL_TLS under FIPS)
                ctx.getSocketFactory().createSocket().close();
                SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(ctx, hv);
                setSSLSocketFactory(sf);

                Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("https", sf).build();

                return (pooled ? new PoolingHttpClientConnectionManager(r)
                        : new BasicHttpClientConnectionManager(r));
            } catch (Throwable t) {
            }
        }
    }

    // Using pooling connection so that this client is threadsafe.
    return (pooled ? new PoolingHttpClientConnectionManager() : new BasicHttpClientConnectionManager());
}

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

@WebMethod(operationName = "consultarSimples")
public String consultarSimples(@WebParam(name = "nrRecibo") String nrRecibo) {
    String resultado = null;/*from   w  ww.  j av  a  2s  .c  o m*/
    TResultLoteGNRE retorno = null;
    loadConfig();
    try {
        //<TConsLote_GNRE xmlns="http://www.gnre.pe.gov.br"><ambiente>1</ambiente><numeroRecibo>2012314940</numeroRecibo></TConsLote_GNRE>
        String XML_DATA = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:gnr=\"http://www.gnre.pe.gov.br/webservice/GnreResultadoLote\">"
                + "<soap:Header><gnr:gnreCabecMsg><gnr:versaoDados>1.00</gnr:versaoDados></gnr:gnreCabecMsg></soap:Header>"
                + " <soap:Body><gnr:gnreDadosMsg><TConsLote_GNRE xmlns=\"http://www.gnre.pe.gov.br\"><ambiente>1</ambiente><numeroRecibo>"
                + nrRecibo + "</numeroRecibo></TConsLote_GNRE></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());
        System.out.println("Conteudo envio ==== " + XML_DATA);
        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 str = EntityUtils.toString(entity);
            System.out.println(str);
            XmlUtil util = new XmlUtil();
            retorno = util.getTResultLoteGNRE(str);
            resultado = retorno.getResultado();

        }
        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 resultado;
}