Example usage for org.apache.http.conn.ssl SSLContextBuilder build

List of usage examples for org.apache.http.conn.ssl SSLContextBuilder build

Introduction

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

Prototype

public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException 

Source Link

Usage

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;//from w  ww .  j a  v a 2s .co 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:org.apache.stratos.metadata.client.rest.DefaultRestClient.java

public DefaultRestClient(String username, String password) throws RestClientException {
    this.username = username;
    this.password = password;

    SSLContextBuilder builder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslConnectionFactory;
    try {/*from   w w  w . j  a va  2  s .  c o m*/
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslConnectionFactory = new SSLConnectionSocketFactory(builder.build());
    } catch (NoSuchAlgorithmException e) {
        throw new RestClientException(e);
    } catch (KeyManagementException e) {
        throw new RestClientException(e);
    } catch (KeyStoreException e) {
        throw new RestClientException(e);
    }
    CloseableHttpClient closableHttpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionFactory)
            .setConnectionManager(HTTPConnectionManager.getInstance().getHttpConnectionManager()).build();
    this.httpClient = closableHttpClient;
}

From source file:co.elastic.tealess.SSLChecker.java

public SSLChecker(SSLContextBuilder cb)
        throws KeyManagementException, KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException {
    cb.setTracker(this::setPeerCertificateDetails);
    ctxbuilder = cb;/* w  ww  . ja v a 2 s  .c o  m*/
    ctx = cb.build();
}

From source file:com.esri.geoevent.test.performance.provision.GeoEventProvisioner.java

private SSLConnectionSocketFactory getSSLSocketFactory() {
    KeyStore trustStore;/*from  w w  w  .j av  a  2s .  c  o m*/
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        TrustStrategy trustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }

        };

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
        sslContextBuilder.useTLS();
        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
        return sslSocketFactory;
    } catch (GeneralSecurityException | IOException e) {
        System.err.println("SSL Error : " + e.getMessage());
    }
    return null;
}

From source file:org.kaaproject.kaa.server.appenders.rest.appender.RestLogAppender.java

@Override
protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) {
    this.configuration = configuration;
    this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize());
    target = new HttpHost(configuration.getHost(), configuration.getPort(),
            configuration.getSsl() ? "https" : "http");
    HttpClientBuilder builder = HttpClients.custom();
    if (configuration.getUsername() != null && configuration.getPassword() != null) {
        LOG.info("Adding basic auth credentials provider");
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
                new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()));
        builder.setDefaultCredentialsProvider(credsProvider);
    }/*from  www  .j av  a 2 s  .c o  m*/
    if (!configuration.getVerifySslCert()) {
        LOG.info("Adding trustful ssl context");
        SSLContextBuilder sslBuilder = new SSLContextBuilder();
        try {
            sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build());
            builder.setSSLSocketFactory(sslsf);
        } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
            LOG.error("Failed to init socket factory {}", ex.getMessage(), ex);
        }
    }
    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
    cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize());
    cm.setMaxTotal(configuration.getConnectionPoolSize());
    builder.setConnectionManager(cm);
    this.client = builder.build();
}

From source file:org.hawkular.component.pinger.Pinger.java

public Pinger() throws Exception {
    SSLContext tmpSslContext;//from   w w w .  j ava 2  s . co m

    try {
        SSLContextBuilder builder = SSLContexts.custom();
        builder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                return true;
            }
        });
        tmpSslContext = builder.build();

    } catch (Exception e) {
        tmpSslContext = null;
    }

    sslContext = tmpSslContext;
}

From source file:cn.wanghaomiao.seimi.http.hc.HttpClientCMPBox.java

public HttpClientCMPBox() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {/* w ww.  ja  va2 s. c  o  m*/
        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> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();
        poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry);
        poolingHttpClientConnectionManager.setMaxTotal(500);
        poolingHttpClientConnectionManager.setDefaultMaxPerRoute(1000);
    } catch (Exception e) {
        Logger logger = LoggerFactory.getLogger(getClass());
        logger.error("init fail,err={}", e.getMessage(), e);
    }

}

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

/**
 * This is a sample web service operation
 *//*  w  w w .  j  a  va  2s .c  o  m*/
@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.GnreLoteRecepcao.java

@WebMethod(operationName = "processarSimples")
public String processarSimples(@WebParam(name = "gnreDadosMsg") Object TLoteGNRE) {
    br.gov.pe.gnre.TRetLoteGNRE retorno = null;
    String recibo = null;/*from   ww w. j  ava2s  .com*/
    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);

            recibo = util.getRecibo(retornoStr);
            System.out.println("ResponseOBJ  " + retorno.getAmbiente());
            recibo = retorno.getRecibo().getNumero();
        }
        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:org.piwigo.remotesync.api.client.WSClient.java

protected CloseableHttpClient getHttpClient() throws Exception {
    if (httpClient == null) {
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

        if (clientConfiguration.getUsesProxy()) {
            String proxyUrl = clientConfiguration.getProxyUrl();
            int proxyPort = clientConfiguration.getProxyPort();

            String proxyUsername = clientConfiguration.getProxyUsername();
            String proxyPassword = clientConfiguration.getProxyPassword();

            if (proxyUsername != null && proxyUsername.length() > 0 && proxyPassword != null
                    && proxyPassword.length() > 0) {
                CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(proxyUrl, proxyPort),
                        new UsernamePasswordCredentials(proxyUsername, proxyPassword));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }// w w  w  .  j  a v  a  2  s .co  m

            HttpHost proxy = new HttpHost(proxyUrl, proxyPort);
            requestConfig = RequestConfig.custom().setProxy(proxy).build();
        }

        if (clientConfiguration.getTrustSSLCertificates()) {
            SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
            sslContextBuilder.loadTrustMaterial(null, new TrustSSLCertificatesStrategy());
            httpClientBuilder.setSSLSocketFactory(new SSLConnectionSocketFactory(sslContextBuilder.build()));
        }

        httpClient = httpClientBuilder.build();
    }

    return httpClient;
}