Example usage for org.apache.http.ssl SSLContexts custom

List of usage examples for org.apache.http.ssl SSLContexts custom

Introduction

In this page you can find the example usage for org.apache.http.ssl SSLContexts custom.

Prototype

public static SSLContextBuilder custom() 

Source Link

Document

Creates custom SSL context.

Usage

From source file:com.mirth.connect.client.core.ServerConnection.java

public ServerConnection(int timeout, String[] httpsProtocols, String[] httpsCipherSuites, boolean allowHTTP) {
    SSLContext sslContext = null;
    try {//from w  w w .  jav a 2s .  c o m
        sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
    } catch (Exception e) {
        logger.error("Unable to build SSL context.", e);
    }

    String[] enabledProtocols = MirthSSLUtil.getEnabledHttpsProtocols(httpsProtocols);
    String[] enabledCipherSuites = MirthSSLUtil.getEnabledHttpsCipherSuites(httpsCipherSuites);
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            enabledProtocols, enabledCipherSuites, NoopHostnameVerifier.INSTANCE);
    RegistryBuilder<ConnectionSocketFactory> builder = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory);
    if (allowHTTP) {
        builder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    }
    Registry<ConnectionSocketFactory> socketFactoryRegistry = builder.build();

    PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry);
    httpClientConnectionManager.setDefaultMaxPerRoute(5);
    httpClientConnectionManager.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(timeout).build());
    // MIRTH-3962: The stale connection settings has been deprecated, and this is recommended instead
    httpClientConnectionManager.setValidateAfterInactivity(5000);

    HttpClientBuilder clientBuilder = HttpClients.custom().setConnectionManager(httpClientConnectionManager);
    HttpUtil.configureClientBuilder(clientBuilder);

    client = clientBuilder.build();
    requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT)
            .setConnectionRequestTimeout(CONNECT_TIMEOUT).setSocketTimeout(timeout).build();
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * <br>//from w  ww  .j  av  a 2s.com
 * Client?httpsURL?keystore?storePasswordkeystore??? 
 * <a href="http://docs.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html">keytool</a>
 * 
 * @param appKey
 *            APP Key?APIAPP?
 * @param appSecret
 *            APP?APIAPP?
 * @param testEnv
 *            ?truefalse
 */
public Client(String appKey, String appSecret, boolean testEnv) {
    HttpClientBuilder builder = HttpClients.custom();
    try {
        SSLContext sslContext = null;
        if (testEnv) {
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    //truetrue
                    return true;
                }
            }).build();
        } else {
            //keytool?keystorekeystore
            KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
            ks.load(null, null);
            sslContext = SSLContexts.custom().loadTrustMaterial(ks, new TrustSelfSignedStrategy()).build();
        }
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" },
                null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        builder.setSSLSocketFactory(sslsf);
    } catch (KeyStoreException | KeyManagementException | NoSuchAlgorithmException | CertificateException
            | IOException e) {
        log.error(e.getMessage(), e);
    }
    httpClient = builder.setUserAgent(Constants.USER_AGENT).build();
    this.appKey = appKey;
    this.appSecret = appSecret;
    this.testEnv = testEnv;
}

From source file:crawler.java.edu.uci.ics.crawler4j.fetcher.PageFetcher.java

public PageFetcher(CrawlConfig config) {
    super(config);

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(CookieSpecs.DEFAULT).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();/*from   w  w  w.  ja va2  s.c  o  m*/

    RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create();
    connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    if (config.isIncludeHttpsPages()) {
        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
                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 (Exception 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(config.getMaxTotalConnections());
    connectionManager.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder.setDefaultRequestConfig(requestConfig);
    clientBuilder.setConnectionManager(connectionManager);
    clientBuilder.setUserAgent(config.getUserAgentString());
    clientBuilder.setDefaultHeaders(config.getDefaultHeaders());

    if (config.getProxyHost() != null) {
        if (config.getProxyUsername() != null) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(new AuthScope(config.getProxyHost(), config.getProxyPort()),
                    new UsernamePasswordCredentials(config.getProxyUsername(), config.getProxyPassword()));
            clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpHost proxy = new HttpHost(config.getProxyHost(), config.getProxyPort());
        clientBuilder.setProxy(proxy);
        logger.debug("Working through Proxy: {}", proxy.getHostName());
    }

    httpClient = clientBuilder.build();
    if ((config.getAuthInfos() != null) && !config.getAuthInfos().isEmpty()) {
        doAuthetication(config.getAuthInfos());
    }

    if (connectionMonitorThread == null) {
        connectionMonitorThread = new IdleConnectionMonitorThread(connectionManager);
    }
    connectionMonitorThread.start();
}

From source file:cool.pandora.modeller.ModellerClient.java

public static SSLConnectionSocketFactory getSSLFactory() throws CertificateException, NoSuchAlgorithmException,
        KeyStoreException, IOException, KeyManagementException {
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(new File(ModellerClient.class.getResource("/modeller.jks").getFile()),
                    "changeme".toCharArray(), new TrustSelfSignedStrategy())
            .build();// w w  w . j a va2  s.co m
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
            null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    return sslsf;
}

From source file:com.arangodb.ArangoConfigureTest.java

@Test
public void sslWithSelfSignedCertificateTest() throws ArangoException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, URISyntaxException {

    // create a sslContext for the self signed certificate
    URL resource = this.getClass().getResource(SSL_TRUSTSTORE);
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(Paths.get(resource.toURI()).toFile(), SSL_TRUSTSTORE_PASSWORD.toCharArray())
            .build();//from   w ww  .  ja  va  2  s . co m

    ArangoConfigure configuration = new ArangoConfigure("/ssl-arangodb.properties");
    configuration.setSslContext(sslContext);
    configuration.init();

    ArangoDriver arangoDriver = new ArangoDriver(configuration);

    ArangoVersion version = arangoDriver.getVersion();

    Assert.assertNotNull(version);
}

From source file:com.arangodb.example.ssl.SslExample.java

@Test
public void sslPeerUnverifiedExceptionTest() throws ArangoException, KeyManagementException,
        NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, URISyntaxException {

    // create a sslContext for the self signed certificate
    URL resource = this.getClass().getResource(SSL_TRUSTSTORE);
    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(Paths.get(resource.toURI()).toFile(), SSL_TRUSTSTORE_PASSWORD.toCharArray())
            .build();/* ww w .  j  a va  2  s . c om*/

    ArangoConfigure configuration = new ArangoConfigure("/ssl-arangodb.properties");
    // 127.0.0.1 is the wrong name
    configuration.getArangoHost().setHost("127.0.0.1");
    configuration.setSslContext(sslContext);
    configuration.init();

    ArangoDriver arangoDriver = new ArangoDriver(configuration);

    try {
        arangoDriver.getVersion();
        Assert.fail("this should fail");
    } catch (ArangoException e) {
        Throwable cause = e.getCause();
        Assert.assertTrue(cause instanceof javax.net.ssl.SSLPeerUnverifiedException);
    }

}

From source file:com.ethercamp.harmony.service.ImportContractIndexTest.java

@BeforeClass
public static void beforeClass() throws Exception {
    // ignore https errors
    SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
    CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    Unirest.setHttpClient(httpclient);/*  w ww.  java 2  s. c  om*/

    SystemProperties.getDefault()
            .setBlockchainConfig(new FrontierConfig(new FrontierConfig.FrontierConstants() {
                @Override
                public BigInteger getMINIMUM_DIFFICULTY() {
                    return BigInteger.ONE;
                }
            }));
}

From source file:org.opentravel.otm.forum2016.am.APIOperationFactory.java

/**
 * Returns a new HTTP client instance for use with API Manager REST API invocations.
 * //from   w w w.j  a  va2  s.  co m
 * @return CloseableHttpClient
 * @throws IOException  thrown if an error occurs while constructing the HTTP client
 */
public static CloseableHttpClient newHttpClient() throws IOException {
    try {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .build();
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());

        return HttpClientBuilder.create().useSystemProperties().setSSLSocketFactory(connectionFactory).build();

    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IOException("Error constructing SSL context for HTTP client.", e);
    }

}

From source file:com.gargoylesoftware.htmlunit.httpclient.HtmlUnitSSLConnectionSocketFactory.java

private HtmlUnitSSLConnectionSocketFactory(final KeyStore keystore, final char[] keystorePassword,
        final KeyStore truststore, final boolean useInsecureSSL, final String[] supportedProtocols,
        final String[] supportedCipherSuites)
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    super(SSLContexts.custom().loadKeyMaterial(keystore, keystorePassword).loadTrustMaterial(truststore, null)
            .build(), supportedProtocols, supportedCipherSuites, new DefaultHostnameVerifier());
    useInsecureSSL_ = useInsecureSSL;/*w  w  w.j  av a2 s  . co  m*/
}