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

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

Introduction

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

Prototype

public SSLContextBuilder loadTrustMaterial(final KeyStore truststore, final TrustStrategy trustStrategy)
            throws NoSuchAlgorithmException, KeyStoreException 

Source Link

Usage

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

private SSLConnectionSocketFactory getSSLSocketFactory() {
    KeyStore trustStore;//from   w w  w. j  a v  a2s .  com
    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  w  w  w  .  j  av  a 2s .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.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);
            }/*from  w w  w. j a va2 s  .c o 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;
}

From source file:org.wso2.apiManager.plugin.client.APIManagerClient.java

/**
 * Method to initialize the http client. We use only one instance of http client since there can not be concurrent
 * invocations/*from  w  ww .  j  av  a  2s. c  o m*/
 *
 * @return @link{HttpClient} httpClient instance
 */
private HttpClient getHttpClient() {
    if (httpClient == null) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                    builder.build());
            httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (NoSuchAlgorithmException e) {
            SoapUI.logError(e, "Unable to load the trust store");
        } catch (KeyStoreException e) {
            SoapUI.logError(e, "Unable to get the key store instance");
        } catch (KeyManagementException e) {
            SoapUI.logError(e, "Unable to load trust store material");
        }
    }
    return httpClient;
}

From source file:org.wso2.store.client.ArtifactPublisher.java

/**
 * Initialize resources/* www. j a  va2 s.  co  m*/
 * @throws StoreAssetClientException
 */
private void init() throws StoreAssetClientException {

    httpContext = new BasicHttpContext();
    rxtFileAttributesMap = new HashMap<String, List<String>>();
    SSLContextBuilder builder = new SSLContextBuilder();
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
    } catch (GeneralSecurityException genSecEx) {
        String errorMsg = "SSL initiation fail.general security exception";
        throw new StoreAssetClientException(errorMsg, genSecEx);
    }
    clientBuilder = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory);
    gson = new Gson();
}

From source file:com.nridge.connector.common.con_com.crawl.CrawlStart.java

private CloseableHttpClient createHttpClient() throws NSException {
    Logger appLogger = mAppMgr.getLogger(this, "createHttpClient");

    appLogger.trace(mAppMgr.LOGMSG_TRACE_ENTER);

    // http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
    // http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3

    CloseableHttpClient httpClient = null;
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    try {// w  ww .  j a va  2 s  . c om

        // Note: This logic will trust CA and self-signed certificates.

        sslContextBuilder.loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] aChain, String anAuthType) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
                sslContextBuilder.build());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
    } catch (Exception e) {
        String msgStr = String.format("HTTP Client Error: %s", e.getMessage());
        appLogger.error(msgStr, e);
        throw new NSException(msgStr);
    }

    appLogger.trace(mAppMgr.LOGMSG_TRACE_DEPART);

    return httpClient;
}

From source file:org.apache.streams.components.http.provider.SimpleHttpProvider.java

@Override
public void prepare(Object configurationObject) {

    mapper = StreamsJacksonMapper.getInstance();

    uriBuilder = new URIBuilder().setScheme(this.configuration.getProtocol())
            .setHost(this.configuration.getHostname()).setPort(this.configuration.getPort().intValue())
            .setPath(this.configuration.getResourcePath());

    SSLContextBuilder builder = new SSLContextBuilder();
    SSLConnectionSocketFactory sslsf = null;
    try {//from www. j av a2 s  . co m
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (NoSuchAlgorithmException e) {
        LOGGER.warn(e.getMessage());
    } catch (KeyManagementException e) {
        LOGGER.warn(e.getMessage());
    } catch (KeyStoreException e) {
        LOGGER.warn(e.getMessage());
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

    executor = Executors.newSingleThreadExecutor();

}