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.arangodb.example.ssl.SslExample.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  w  w  . j av  a  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.github.vbauer.yta.service.transport.impl.RestClientImpl.java

private HttpClient createClient() throws Exception {
    final SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());

    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_TIMEOUT)
            .setConnectTimeout(DEFAULT_TIMEOUT).setConnectionRequestTimeout(DEFAULT_TIMEOUT)
            .setRedirectsEnabled(true).build();

    return HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
            .setSSLSocketFactory(socketFactory).setDefaultRequestConfig(requestConfig).build();
}

From source file:crawler.PageFetcher.java

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

    RequestConfig requestConfig = RequestConfig.custom().setExpectContinueEnabled(false)
            .setCookieSpec(config.getCookiePolicy()).setRedirectsEnabled(false)
            .setSocketTimeout(config.getSocketTimeout()).setConnectTimeout(config.getConnectionTimeout())
            .build();//from   w w w  . java 2  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 SniSSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);
            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 SniPoolingHttpClientConnectionManager(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:org.sonatype.nexus.testsuite.NexusHttpsITSupport.java

/**
 * @return SSL socket factory that accepts self-signed certificates from any host
 *///from   w  w w .  ja  v a 2 s  .co  m
protected SSLConnectionSocketFactory sslSocketFactory() throws Exception {
    SSLContext context = SSLContexts.custom().loadTrustMaterial(trustStore(), new TrustSelfSignedStrategy())
            .build();
    return new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
}

From source file:org.phenotips.data.internal.MonarchPatientScorer.java

@Override
public void initialize() throws InitializationException {
    try {//from  w w  w .j a v  a  2 s.  c  o m
        this.scorerURL = this.configuration.getProperty("phenotips.patientScoring.monarch.serviceURL",
                "https://monarchinitiative.org/score");
        CacheConfiguration config = new LRUCacheConfiguration("monarchSpecificityScore", 2048, 3600);
        this.cache = this.cacheManager.createNewCache(config);
    } catch (CacheException ex) {
        throw new InitializationException("Failed to create cache", ex);
    }
    try {
        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(null, new TrustAllStrategy()).build();
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, null, null,
                NoopHostnameVerifier.INSTANCE);
        this.client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException ex) {
        this.logger.warn("Failed to set custom certificate trust, using the default", ex);
        this.client = HttpClients.createSystem();
    }
}

From source file:org.thingsboard.server.msa.AbstractContainerTest.java

protected WsClient subscribeToWebSocket(DeviceId deviceId, String scope, CmdsType property) throws Exception {
    WsClient wsClient = new WsClient(
            new URI(WSS_URL + "/api/ws/plugins/telemetry?token=" + restClient.getToken()));
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true);
    wsClient.setSocket(builder.build().getSocketFactory().createSocket());
    wsClient.connectBlocking();// w w w.j  a  v a2  s .co  m

    JsonObject cmdsObject = new JsonObject();
    cmdsObject.addProperty("entityType", EntityType.DEVICE.name());
    cmdsObject.addProperty("entityId", deviceId.toString());
    cmdsObject.addProperty("scope", scope);
    cmdsObject.addProperty("cmdId", new Random().nextInt(100));

    JsonArray cmd = new JsonArray();
    cmd.add(cmdsObject);
    JsonObject wsRequest = new JsonObject();
    wsRequest.add(property.toString(), cmd);
    wsClient.send(wsRequest.toString());
    wsClient.waitForFirstReply();
    return wsClient;
}

From source file:dev.snowdrop.example.OpenShiftIT.java

/**
 * We need a simplified setup that allows us to work with self-signed certificates.
 * To support this we need to provide a custom http client.
 *///w ww.java 2s.  c o  m
private AuthzClient createAuthzClient() throws Exception {
    InputStream configStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream("keycloak.json");
    if (configStream == null) {
        throw new IllegalStateException("Could not find any keycloak.json file in classpath.");
    }

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial((chain, authType) -> true).build();
    HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext)
            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();

    // the injected @RouteURL always contains a port number, which means the URL is different from SSO_AUTH_SERVER_URL,
    // and that causes failures during token validation
    String ssoUrl = ssoUrlBase.toString().replace(":443", "") + "auth";

    System.setProperty("SSO_AUTH_SERVER_URL", ssoUrl);
    Configuration baseline = JsonSerialization.readValue(configStream, Configuration.class, true // system property replacement
    );

    return AuthzClient.create(new Configuration(baseline.getAuthServerUrl(), baseline.getRealm(),
            baseline.getResource(), baseline.getCredentials(), httpClient));
}

From source file:org.apache.calcite.avatica.remote.AvaticaCommonsHttpClientImpl.java

private void initializeClient() {
    SSLConnectionSocketFactory sslFactory = null;
    if (null != truststore && null != truststorePassword) {
        try {/*from  w w w.  j a va2  s.c  o m*/
            SSLContext sslcontext = SSLContexts.custom()
                    .loadTrustMaterial(truststore, truststorePassword.toCharArray()).build();
            sslFactory = new SSLConnectionSocketFactory(sslcontext);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    } else {
        LOG.debug("Not configuring HTTPS because of missing truststore/password");
    }

    RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.create();
    registryBuilder.register("http", PlainConnectionSocketFactory.getSocketFactory());
    // Only register the SSL factory when provided
    if (null != sslFactory) {
        registryBuilder.register("https", sslFactory);
    }
    pool = new PoolingHttpClientConnectionManager(registryBuilder.build());
    // Increase max total connection to 100
    final String maxCnxns = System.getProperty(MAX_POOLED_CONNECTIONS_KEY, MAX_POOLED_CONNECTIONS_DEFAULT);
    pool.setMaxTotal(Integer.parseInt(maxCnxns));
    // Increase default max connection per route to 25
    final String maxCnxnsPerRoute = System.getProperty(MAX_POOLED_CONNECTION_PER_ROUTE_KEY,
            MAX_POOLED_CONNECTION_PER_ROUTE_DEFAULT);
    pool.setDefaultMaxPerRoute(Integer.parseInt(maxCnxnsPerRoute));

    this.authCache = new BasicAuthCache();

    // A single thread-safe HttpClient, pooling connections via the ConnectionManager
    this.client = HttpClients.custom().setConnectionManager(pool).build();
}

From source file:com.spotify.sshagenttls.CertHttpsHandler.java

public void handle(final HttpsURLConnection conn) {
    final CertKey certKey;
    try {//from   w ww.  j ava  2  s.  c om
        certKey = createCertKey();
    } catch (IOException | GeneralSecurityException e) {
        if (failOnCertError) {
            throw new RuntimeException(e);
        } else {
            LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. "
                    + "No cert will be sent with request.", getCertSource(), e.toString());
            LOG.debug("full exception fromPaths setting up ClientCertificate follows", e);
            return;
        }
    }

    final Certificate cert = certKey.cert();
    final PrivateKey key = certKey.key();

    // Generate a keystore password.
    // Do all this locally to not make copies of the password in memory.
    final SecureRandom random = new SecureRandom();
    final int numBytes = 60;
    final char[] keyStorePassword = new char[numBytes];
    for (int i = 0; i < numBytes; i++) {
        // Only use ASCII characters for the password. The corresponding integer range is [32, 126].
        keyStorePassword[i] = (char) (random.nextInt(95) + 32);
    }

    try {
        // We're creating a keystore in memory and putting the cert & key into it.
        // The keystore needs a password when we put the key into it, even though it's only going to
        // exist for the lifetime of the process. So we just have some random password that we use.

        final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setCertificateEntry("client", cert);
        keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert });

        // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that
        final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS")
                .loadKeyMaterial(keyStore, keyStorePassword).build();

        // Clear out arrays that had password
        Arrays.fill(keyStorePassword, '\0');

        conn.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException
            | UnrecoverableKeyException | KeyManagementException e) {
        // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more.
        throw new RuntimeException(e);
    }
}

From source file:com.cloud.agent.direct.download.HttpsDirectTemplateDownloader.java

private SSLContext getSSLContext() throws KeyStoreException, NoSuchAlgorithmException, CertificateException,
        IOException, KeyManagementException {
    KeyStore trustStore = KeyStore.getInstance("jks");
    FileInputStream instream = new FileInputStream(new File("/etc/cloudstack/agent/cloud.jks"));
    try {//from  www . java 2  s  .c  om
        String privatePasswordFormat = "sed -n '/keystore.passphrase/p' '%s' 2>/dev/null  | sed 's/keystore.passphrase=//g' 2>/dev/null";
        String privatePasswordCmd = String.format(privatePasswordFormat,
                "/etc/cloudstack/agent/agent.properties");
        String privatePassword = Script.runSimpleBashScript(privatePasswordCmd);
        trustStore.load(instream, privatePassword.toCharArray());
    } finally {
        instream.close();
    }
    return SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
}