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:ru.anr.base.facade.web.api.RestClient.java

/**
 * Configuring an apache client to support untrusted ssl connections. This
 * can be useful for test purposes only.
 * // w w  w.  jav  a  2 s .com
 * @return Apache {@link HttpClient}
 */
private HttpClient buildSSLClient() {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {

        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {

            return true;
        }
    };

    try {

        SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy);
        SSLContext sslContext = sslBuilder.useTLS().build();

        SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext,
                new AllowAllHostnameVerifier());
        return HttpClients.custom().setSSLSocketFactory(sf).build();

    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        throw new ApplicationException(ex);
    }
}

From source file:com.couchbase.jdbc.core.ProtocolImpl.java

public ProtocolImpl(String url, Properties props) {

    if (props.containsKey(ConnectionParameters.USER)) {
        user = props.getProperty(ConnectionParameters.USER);
    }//ww  w  .  j a  v a 2 s  .  co m
    if (props.containsKey(ConnectionParameters.PASSWORD)) {
        password = props.getProperty(ConnectionParameters.PASSWORD);
    }
    if (props.containsKey("credentials")) {
        credentials = props.getProperty("credentials");
    }
    this.url = url;
    setConnectionTimeout(props.getProperty(ConnectionParameters.CONNECTION_TIMEOUT));
    if (props.containsKey(ConnectionParameters.SCAN_CONSISTENCY)) {
        scanConsistency = props.getProperty(ConnectionParameters.SCAN_CONSISTENCY);
    }

    requestConfig = RequestConfig.custom().setConnectionRequestTimeout(0).setConnectTimeout(connectTimeout)
            .setSocketTimeout(connectTimeout).build();

    if (props.containsKey(ConnectionParameters.ENABLE_SSL)
            && props.getProperty(ConnectionParameters.ENABLE_SSL).equals("true")) {
        SSLContextBuilder builder = SSLContexts.custom();

        try {
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            });
            SSLContext sslContext = builder.build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new X509HostnameVerifier() {
                        @Override
                        public void verify(String host, SSLSocket ssl) throws IOException {
                        }

                        @Override
                        public void verify(String host, X509Certificate cert) throws SSLException {
                        }

                        @Override
                        public void verify(String host, String[] cns, String[] subjectAlts)
                                throws SSLException {
                        }

                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    });

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create().register("https", sslsf).build();
            HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig)
                    .build();
            ssl = true;

        } catch (Exception ex) {
            logger.error("Error creating ssl client", ex);
        }

    } else {
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build();
    }
}

From source file:com.bosch.cr.examples.inventorybrowser.server.ProxyServlet.java

private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {// w w w . j  a  va 2 s  .  c om
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (props.getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                        Integer.parseInt(props.getProperty("http.proxyPort"))));
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:com.bosch.cr.examples.jwt.CustomProxyServlet.java

private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {// w w w . jav a  2s .  c  o m
            final HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            final SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, (chain, authType) -> true).build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            final SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    sslContext, NoopHostnameVerifier.INSTANCE);

            final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            final PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            final boolean proxyEnabled = configurationProperties
                    .getPropertyAsBoolean(ConfigurationProperty.PROXY_ENABLED);
            if (proxyEnabled) {
                final String proxyHost = configurationProperties
                        .getPropertyAsString(ConfigurationProperty.PROXY_HOST);
                final int proxyPort = configurationProperties
                        .getPropertyAsInt(ConfigurationProperty.PROXY_PORT);
                final HttpHost proxy = new HttpHost(proxyHost, proxyPort);
                httpClientBuilder.setProxy(proxy);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

/**
 * Create http client//from  ww w.  j  ava 2  s.c  om
 */
private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (props.getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                        Integer.parseInt(props.getProperty("http.proxyPort"))));
            }

            if (props.getProperty("http.proxyUser") != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(
                        props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd")));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

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

/**
 * This is a sample web service operation
 *///w  w w.j  a  v a  2 s  . c o m
//@WebMethod(operationName = "consultarLote")
private TResultLoteGNRE consultarLote(@WebParam(name = "gnreDadosMsgLote") TConsLote_GNRE gnreDadosMsg) {
    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>" + gnreDadosMsg
                + "</gnr:gnreDadosMsg></soap:Body></soap:Envelope>";

        System.out.println("PARAMETRO envio ==== " + gnreDadosMsg);
        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);

        }
        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:com.arvato.thoroughly.util.RestTemplateUtil.java

private LayeredConnectionSocketFactory setUpSSL() {
    LayeredConnectionSocketFactory sslSF = null;
    try {//from   ww  w. java  2s  .c om
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadTrustMaterial(trustStore, new AnyTrustStrategy()).build();
        sslSF = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    } catch (Exception e) {
        LOGGER.error(e.getMessage());
    }
    return sslSF;
}

From source file:com.crosstreelabs.cognitio.gumshoe.transport.HttpTransport.java

private void buildHttpClient() {
    requestConfig = RequestConfig.custom().setExpectContinueEnabled(false).setCookieSpec(CookieSpecs.DEFAULT)
            .setRedirectsEnabled(false).setSocketTimeout(5000).setConnectTimeout(5000)
            .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build();

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174
          // By always trusting the ssl certificate
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override/*from   ww w. j av  a  2 s.  c o  m*/
            public boolean isTrusted(final X509Certificate[] chain, String authType) {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        connRegistryBuilder.register("https", sslsf);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn("Exception thrown while trying to register https");
        LOGGER.debug("Stacktrace", e);
    }

    Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build();
    connectionManager = new PoolingHttpClientConnectionManager(connRegistry);
    connectionManager.setMaxTotal(5);
    connectionManager.setDefaultMaxPerRoute(5);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent("Cognitio");

    httpClient = clientBuilder.build();
}

From source file:groovyx.net.http.ApacheHttpBuilder.java

private Registry<ConnectionSocketFactory> registry(final HttpObjectConfig config) {
    final ProxyInfo proxyInfo = config.getExecution().getProxyInfo();

    final boolean isSocksProxied = (proxyInfo != null && proxyInfo.getProxy().type() == Proxy.Type.SOCKS);

    if (isSocksProxied) {
        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new SocksHttp(proxyInfo.getProxy()))
                .register("https", new SocksHttps(proxyInfo.getProxy(), sslContext(config),
                        config.getExecution().getHostnameVerifier()))
                .build();//from w ww.  j  av  a2s.c o  m
    } else {
        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslContext(config),
                        config.getExecution().getHostnameVerifier()))
                .build();
    }
}

From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java

/**
 * Set up http client with credentials/* www.j  av  a2 s . c om*/
 * @return Http client
 * @throws MojoExecutionException Mojo execution exception
 */
protected final CloseableHttpClient getHttpClient() throws MojoExecutionException {
    try {
        URI crxUri = new URI(getCrxPackageManagerUrl());

        final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort());
        final Credentials credentials = new UsernamePasswordCredentials(this.userId, this.password);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(authScope, credentials);

        HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .addInterceptorFirst(new HttpRequestInterceptor() {
                    @Override
                    public void process(HttpRequest request, HttpContext context)
                            throws HttpException, IOException {
                        // enable preemptive authentication
                        AuthState authState = (AuthState) context
                                .getAttribute(HttpClientContext.TARGET_AUTH_STATE);
                        authState.update(new BasicScheme(), credentials);
                    }
                });

        if (this.relaxedSSLCheck) {
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new NoopHostnameVerifier());
            httpClientBuilder.setSSLSocketFactory(sslsf);
        }

        return httpClientBuilder.build();
    } catch (URISyntaxException ex) {
        throw new MojoExecutionException("Invalid url: " + getCrxPackageManagerUrl(), ex);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) {
        throw new MojoExecutionException("Could not set relaxedSSLCheck", ex);
    }
}