Java Code Examples for org.apache.http.ssl.SSLContextBuilder#create()

The following examples show how to use org.apache.http.ssl.SSLContextBuilder#create() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HttpEventPublisher.java    From DataflowTemplates with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to create a {@link CloseableHttpClient} to make http POSTs against Splunk's
 * HEC.
 *
 * @param maxConnections max number of parallel connections.
 * @param disableCertificateValidation should disable certificate validation.
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
Example 2
Source File: RestClient.java    From ats-framework with Apache License 2.0 5 votes vote down vote up
private Registry constructRegistry() {

        try {
            SSLContextBuilder builder = SSLContextBuilder.create();

            builder.useProtocol(this.supportedProtocols[0]);

            if (!StringUtils.isNullOrEmpty(clientConfigurator.getCertificateFileName())) {
                builder.loadKeyMaterial(SslUtils.loadKeystore(clientConfigurator.getCertificateFileName(),
                                                              clientConfigurator.getCertificateFilePassword()),
                                        clientConfigurator.getCertificateFilePassword().toCharArray());
            }

            // Trust all certificates
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted( X509Certificate[] chain, String authType ) throws CertificateException {

                    return true;
                }
            });
            SSLContext sslContext = builder.build();

            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                                                                              new NoopHostnameVerifier());

            Registry registry = RegistryBuilder.create().register("https", sslsf).build();

            return registry;
        } catch (Exception e) {
            throw new RuntimeException("Unable to setup SSL context for REST client with Apache connector provider", e);
        }
    }
 
Example 3
Source File: HttpEventPublisher.java    From beam with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a {@link CloseableHttpClient} to make HTTP POSTs against Splunk's HEC.
 *
 * @param maxConnections max number of parallel connections
 * @param disableCertificateValidation should disable certificate validation
 */
private CloseableHttpClient getHttpClient(
    int maxConnections, boolean disableCertificateValidation)
    throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {

  HttpClientBuilder builder = ApacheHttpTransport.newDefaultHttpClientBuilder();

  if (genericUrl().getScheme().equalsIgnoreCase(HTTPS_PROTOCOL_PREFIX)) {
    LOG.info("SSL connection requested");

    HostnameVerifier hostnameVerifier =
        disableCertificateValidation
            ? NoopHostnameVerifier.INSTANCE
            : new DefaultHostnameVerifier();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
    if (disableCertificateValidation) {
      LOG.info("Certificate validation is disabled");
      sslContextBuilder.loadTrustMaterial((TrustStrategy) (chain, authType) -> true);
    }

    SSLConnectionSocketFactory connectionSocketFactory =
        new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(connectionSocketFactory);
  }

  builder.setMaxConnTotal(maxConnections);
  builder.setDefaultRequestConfig(
      RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());

  return builder.build();
}
 
Example 4
Source File: DeviceSimulatorUpdater.java    From hawkbit-examples with Eclipse Public License 1.0 5 votes vote down vote up
private static CloseableHttpClient createHttpClientThatAcceptsAllServerCerts()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    final SSLContextBuilder builder = SSLContextBuilder.create();
    builder.loadTrustMaterial(null, (chain, authType) -> true);
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}
 
Example 5
Source File: CommonsDataLoader.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private RegistryBuilder<ConnectionSocketFactory> setConnectionManagerSchemeHttps(
		final RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistryBuilder) {
	try {

		SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
		sslContextBuilder.setProtocol(sslProtocol);
		
		TrustStrategy trustStrategy = getTrustStrategy();
		if (trustStrategy != null) {
			LOG.debug("Set the TrustStrategy");
			sslContextBuilder.loadTrustMaterial(null, trustStrategy);
		}

		final KeyStore sslTrustStore = getSSLTrustStore();
		if (sslTrustStore != null) {
			LOG.debug("Set the SSL trust store as trust materials");
			sslContextBuilder.loadTrustMaterial(sslTrustStore, trustStrategy);
		}

		final KeyStore sslKeystore = getSSLKeyStore();
		if (sslKeystore != null) {
			LOG.debug("Set the SSL keystore as key materials");
			final char[] password = sslKeystorePassword != null ? sslKeystorePassword.toCharArray() : null;
			sslContextBuilder.loadKeyMaterial(sslKeystore, password);
			if (loadKeyStoreAsTrustMaterial) {
				LOG.debug("Set the SSL keystore as trust materials");
				sslContextBuilder.loadTrustMaterial(sslKeystore, trustStrategy);
			}
		}

		SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), getSupportedSSLProtocols(),
				getSupportedSSLCipherSuites(), getHostnameVerifier());
		return socketFactoryRegistryBuilder.register("https", sslConnectionSocketFactory);
	} catch (final Exception e) {
		throw new DSSException("Unable to configure the SSLContext/SSLConnectionSocketFactory", e);
	}
}
 
Example 6
Source File: GoAgentServerHttpClientBuilder.java    From gocd with Apache License 2.0 5 votes vote down vote up
@Override
public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();
    builder
            .setDefaultSocketConfig(SocketConfig.custom()
                    .setTcpNoDelay(true)
                    .setSoKeepAlive(true)
                    .build()
            )
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    KeyStore keystore = agentKeystore();

    if (keystore != null) {
        sslContextBuilder.loadKeyMaterial(keystore, agentKeystorePassword);
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}
 
Example 7
Source File: DefaultEsClientFactory.java    From apiman with Apache License 2.0 5 votes vote down vote up
/**
 * Configures the SSL connection to use certificates by setting the keystores
 * @param httpConfig the http client configuration
 * @param config the configuration
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig, Map<String, String> config) {
    try {
        String clientKeystorePath = config.get("client.keystore");
        String clientKeystorePassword = config.get("client.keystore.password");
        String trustStorePath = config.get("client.truststore");
        String trustStorePassword = config.get("client.truststore.password");

        SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();

        String trustCertificate = config.get("client.trust.certificate");
        if (!StringUtils.isBlank(trustCertificate) && trustCertificate.equals("true")) {
            sslContextBuilder = sslContextBuilder.loadTrustMaterial(new TrustSelfSignedStrategy());
        }

        SSLContext sslContext = sslContextBuilder.build();
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), new SecureRandom());

        String trustHost = config.get("client.trust.host");
        HostnameVerifier hostnameVerifier = !StringUtils.isBlank(trustHost) && trustHost.equals("true") ? NoopHostnameVerifier.INSTANCE : new DefaultHostnameVerifier();

        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 8
Source File: UnusedDependencies.java    From tutorials with MIT License 4 votes vote down vote up
private static void useHttpCore() {
    SSLContextBuilder.create();
}