Java Code Examples for org.apache.http.ssl.SSLContexts#createDefault()

The following examples show how to use org.apache.http.ssl.SSLContexts#createDefault() . 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: MPRestClient.java    From dx-java with MIT License 10 votes vote down vote up
/**
 * Create a HttpClient
 * @return a HttpClient
 */
private HttpClient createHttpClient() {
    SSLContext sslContext = SSLContexts.createDefault();
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
            new String[]{"TLSv1.1", "TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
    connectionManager.setMaxTotal(MercadoPago.SDK.getMaxConnections());
    connectionManager.setDefaultMaxPerRoute(MercadoPago.SDK.getMaxConnections());
    connectionManager.setValidateAfterInactivity(VALIDATE_INACTIVITY_INTERVAL_MS);

    DefaultHttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(MercadoPago.SDK.getRetries(), false);

    HttpClientBuilder httpClientBuilder = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setKeepAliveStrategy(new KeepAliveStrategy())
            .setRetryHandler(retryHandler)
            .disableCookieManagement()
            .disableRedirectHandling();

    return httpClientBuilder.build();
}
 
Example 2
Source File: HttpGenericOperationUnitTestCase.java    From wildfly-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
private static CloseableHttpClient createHttpClient(String host, int port, String username, String password) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(host, port, MANAGEMENT_REALM, AuthSchemes.DIGEST),
                new UsernamePasswordCredentials(username, password));
        PoolingHttpClientConnectionManager connectionPool = new PoolingHttpClientConnectionManager(registry);
        HttpClientBuilder.create().setConnectionManager(connectionPool).build();
        return HttpClientBuilder.create()
                .setConnectionManager(connectionPool)
                .setRetryHandler(new StandardHttpRequestRetryHandler(5, true))
                .setDefaultCredentialsProvider(credsProvider).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 3
Source File: ClientUtil.java    From oxAuth with MIT License 6 votes vote down vote up
/**
 * Creates a special SSLContext using a custom TLS version and a set of ciphers enabled to process SSL connections.
 * @param tlsVersion TLS version, for example TLSv1.2
 * @param ciphers Set of ciphers used to create connections.
 */
public static CloseableHttpClient createHttpClient(String tlsVersion, String[] ciphers) {
    try {
        SSLContext sslContext = SSLContexts.createDefault();
        SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(sslContext,
                new String[] { tlsVersion }, ciphers, NoopHostnameVerifier.INSTANCE);

        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory> create()
                .register("https", sslConnectionFactory)
                .register("http", new PlainConnectionSocketFactory())
                .build();

        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);

        return HttpClients.custom()
                .setSSLContext(sslContext)
                .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
                .setConnectionManager(cm)
                .build();
    } catch (Exception e) {
        log.error("Error creating HttpClient with a custom TLS version and custom ciphers", e);
        return null;
    }
}
 
Example 4
Source File: AsyncClientCustomSSL.java    From yunpian-java-sdk with MIT License 5 votes vote down vote up
public final static void main(String[] args) throws Exception {
    // KeyStore trustStore =
    // KeyStore.getInstance(KeyStore.getDefaultType());
    // FileInputStream instream = new FileInputStream(new
    // File("my.keystore"));
    // try {
    // trustStore.load(instream, "nopassword".toCharArray());
    // } finally {
    // instream.close();
    // }
    // // Trust own CA and all self-signed certs
    // SSLContext sslcontext =
    // SSLContexts.custom().loadTrustMaterial(trustStore, new
    // TrustSelfSignedStrategy())
    // .build();
    SSLContext sslcontext = SSLContexts.createDefault();
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" }, null,
            SSLIOSessionStrategy.getDefaultHostnameVerifier());
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).build();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("https://github.com/dzh");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
 
Example 5
Source File: ExtendedHttpClientBuilder.java    From lavaplayer with Apache License 2.0 5 votes vote down vote up
private static SSLContext setupSslContext() {
  try {
    X509TrustManager trustManager = new TrustManagerBuilder()
        .addBuiltinCertificates()
        .addFromResourceDirectory("/certificates")
        .build();

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new X509TrustManager[] { trustManager }, null);
    return context;
  } catch (Exception e) {
    log.error("Failed to build custom SSL context, using default one.", e);
    return SSLContexts.createDefault();
  }
}
 
Example 6
Source File: HttpClientFactory.java    From riptide with MIT License 5 votes vote down vote up
private static SSLContext createSSLContext(final Client client) throws GeneralSecurityException, IOException {
    final CertificatePinning pinning = client.getCertificatePinning();

    if (pinning.getEnabled()) {
        final Keystore keystore = pinning.getKeystore();
        final String path = keystore.getPath();
        final String password = keystore.getPassword();

        final URL resource = HttpClientFactory.class.getClassLoader().getResource(path);

        if (resource == null) {
            throw new FileNotFoundException(format("Keystore [%s] not found.", path));
        }

        try {
            return SSLContexts.custom()
                    .loadTrustMaterial(resource, password == null ? null : password.toCharArray())
                    .build();
        } catch (final Exception e) {
            log.error("Error loading keystore [{}]:", path,
                    e); // log full exception, bean initialization code swallows it
            throw e;
        }
    }

    return SSLContexts.createDefault();
}
 
Example 7
Source File: EwsSSLProtocolSocketFactory.java    From ews-java-api with MIT License 5 votes vote down vote up
/**
 * Create SSL context and initialize it using specific trust manager.
 *
 * @param trustManager trust manager
 * @return initialized SSL context
 * @throws GeneralSecurityException on security error
 */
public static SSLContext createSslContext(TrustManager trustManager)
  throws GeneralSecurityException {
  EwsX509TrustManager x509TrustManager = new EwsX509TrustManager(null, trustManager);
  SSLContext sslContext = SSLContexts.createDefault();
  sslContext.init(
    null,
    new TrustManager[] { x509TrustManager },
    null
  );
  return sslContext;
}
 
Example 8
Source File: AbstractHttpClientGenerator.java    From cetty with Apache License 2.0 4 votes vote down vote up
protected SSLIOSessionStrategy buildSSLIOSessionStrategy() {
    SSLContext sslcontext = SSLContexts.createDefault();
    return new SSLIOSessionStrategy(sslcontext);
}
 
Example 9
Source File: SkipVerifyDockerCertificatesStore.java    From hazelcast-docker-swarm-discovery-spi with Apache License 2.0 4 votes vote down vote up
@Override
public SSLContext sslContext() {
    return SSLContexts.createDefault();
}
 
Example 10
Source File: HttpClientRestClient.java    From pardot-java-client with MIT License 4 votes vote down vote up
/**
 * Initialization method.  This takes in the configuration and sets up the underlying
 * http client appropriately.
 * @param configuration The user defined configuration.
 */
@Override
public void init(final Configuration configuration) {
    // Save reference to configuration
    this.configuration = configuration;

    // Load RequestMutator instance from configuration.
    requestInterceptor = configuration.getRequestInterceptor();

    // Create default SSLContext
    final SSLContext sslcontext = SSLContexts.createDefault();

    // Initialize ssl context with configured key and trust managers.
    try {
        sslcontext.init(new KeyManager[0], getTrustManagers(), new SecureRandom());
    } catch (final KeyManagementException exception) {
        throw new RuntimeException(exception.getMessage(), exception);
    }

    // Create hostname verifier instance.
    final HostnameVerifier hostnameVerifier;
    // Emit an warning letting everyone know we're using an insecure configuration.
    if (configuration.getIgnoreInvalidSslCertificates()) {
        logger.warn("Using insecure configuration, skipping server-side certificate validation checks.");

        // If we're configured to ignore invalid certificates, use the Noop verifier.
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    } else {
        // Use default implementation
        hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier();
    }

    // Allow TLSv1_1 and TLSv1_2 protocols
    final LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
        sslcontext,
        new String[] { "TLSv1.1", "TLSv1.2" },
        null,
        hostnameVerifier
    );

    // Setup client builder
    final HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    clientBuilder
        // Pardot disconnects requests after 120 seconds.
        .setConnectionTimeToLive(130, TimeUnit.SECONDS)
        .setSSLSocketFactory(sslsf);

    // Define our RequestConfigBuilder
    final RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();

    // If we have a configured proxy host
    if (configuration.getProxyHost() != null) {
        // Define proxy host
        final HttpHost proxyHost = new HttpHost(
            configuration.getProxyHost(),
            configuration.getProxyPort(),
            configuration.getProxyScheme()
        );

        // If we have proxy auth enabled
        if (configuration.getProxyUsername() != null) {
            // Create credential provider
            final CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(
                new AuthScope(configuration.getProxyHost(), configuration.getProxyPort()),
                new UsernamePasswordCredentials(configuration.getProxyUsername(), configuration.getProxyPassword())
            );

            // Attach Credentials provider to client builder.
            clientBuilder.setDefaultCredentialsProvider(credsProvider);
        }

        // Attach Proxy to request config builder
        requestConfigBuilder.setProxy(proxyHost);
    }

    // Attach default request config
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    // build http client
    httpClient = clientBuilder.build();
}
 
Example 11
Source File: HttpClientConnectionManagerFactory.java    From signalfx-java with Apache License 2.0 4 votes vote down vote up
public SSLConnectionSocketFactoryWithTimeout(int timeoutMs) {
  super(SSLContexts.createDefault(), SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER);
  this.timeoutMs = timeoutMs;
}