Example usage for javax.net.ssl SSLContext getDefault

List of usage examples for javax.net.ssl SSLContext getDefault

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getDefault.

Prototype

public static SSLContext getDefault() throws NoSuchAlgorithmException 

Source Link

Document

Returns the default SSL context.

Usage

From source file:com.sonatype.nexus.ssl.plugin.internal.repository.RepositoryClientConnectionOperatorSelectorTest.java

/**
 * Verify that an {@link ClientConnectionOperator} is returned when trust store is enabled for repository
 * (repository present in context under {@link HttpClientFactory#HTTP_CTX_KEY_REPOSITORY} key).
 *//*from ww w  .  j  a v a 2s  . c  om*/
@Test
public void operatorReturnedWhenTrustStoreEnabled() throws Exception {
    final Repository repository = mock(Repository.class);
    when(repository.getId()).thenReturn("foo");

    final TrustStore trustStore = mock(TrustStore.class);
    when(trustStore.getSSLContextFor(repositoryTrustStoreKey("foo"))).thenReturn(SSLContext.getDefault());

    final HttpContext httpContext = mock(HttpContext.class);
    when(httpContext.getAttribute(HttpClientFactory.HTTP_CTX_KEY_REPOSITORY)).thenReturn(repository);

    final RepositoryClientConnectionOperatorSelector underTest = new RepositoryClientConnectionOperatorSelector(
            trustStore);
    final SSLContext context = underTest.select(httpContext);

    assertThat(context, is(notNullValue()));
}

From source file:sample.tomcat.X509ApplicationTests.java

@Before
public void setUp() throws Exception {
    this.defaultContext = SSLContext.getDefault();
}

From source file:com.metamx.rdiclient.RdiClients.java

/**
 * Generate HttpClient with default settings
 *
 * @param config default config.  1 connection. Timeout duration set in RdiClientConfig.
 * @param lifecycle lifecycle for HttpClient
 * @return HttpClient/*from  ww  w .jav  a  2s.  c  om*/
 */
private static HttpClient makeDefaultHttpClient(final RdiClientConfig config, final Lifecycle lifecycle) {
    try {
        final HttpClientConfig httpClientConfig = new HttpClientConfig(config.getMaxConnectionCount(),
                SSLContext.getDefault(), new Duration(config.getPostTimeoutMillis()));
        return HttpClientInit.createClient(httpClientConfig, lifecycle);
    } catch (NoSuchAlgorithmException e) {
        throw Throwables.propagate(e);
    }
}

From source file:HCEngine.java

private CloseableHttpClient createCloseableHttpClient() throws Exception {
    HttpClientBuilder builder = HttpClientBuilder.create();
    builder.useSystemProperties();/*from www  .jav  a  2s.co  m*/
    builder.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE);
    builder.setSSLContext(SSLContext.getDefault());
    CloseableHttpClient hc = builder.build();
    return hc;
}

From source file:com.kenai.redminenb.repository.RedmineManagerFactoryHelper.java

public static HttpClient getTransportConfig() {
    /**/*from w w w.  jav  a 2  s .  c o  m*/
    * Implement a minimal hostname verifier. This is needed to be able to use
    * hosts with certificates, that don't match the used hostname (VServer).
     *
     * This is implemented by first trying the "Browser compatible" hostname
     * verifier and if that fails, fall back to the default java hostname
     * verifier.
     *
     * If the default case the hostname verifier in java always rejects, but
     * for netbeans the "SSL Certificate Exception" module is available that
     * catches this and turns a failure into a request to the GUI user.
     */
    X509HostnameVerifier hostnameverified = new X509HostnameVerifier() {
        @Override
        public void verify(String string, SSLSocket ssls) throws IOException {
            if (SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.verify(string, ssls.getSession())) {
                return;
            }
            if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls.getSession())) {
                throw new SSLException("Hostname did not verify");
            }
        }

        @Override
        public void verify(String string, X509Certificate xc) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public void verify(String string, String[] strings, String[] strings1) throws SSLException {
            throw new SSLException("Check not implemented yet");
        }

        @Override
        public boolean verify(String string, SSLSession ssls) {
            if (SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER.verify(string, ssls)) {
                return true;
            }
            return HttpsURLConnection.getDefaultHostnameVerifier().verify(string, ssls);
        }
    };

    try {
        SSLConnectionSocketFactory scsf = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                hostnameverified);

        HttpClient hc = HttpClientBuilder.create()
                .setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()))
                .setSSLSocketFactory(scsf).build();

        return hc;
    } catch (NoSuchAlgorithmException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.elasticsearch.client.RestClientBuilderIntegTests.java

public void testBuilderUsesDefaultSSLContext() throws Exception {
    final SSLContext defaultSSLContext = SSLContext.getDefault();
    try {/*from w w w  .  j ava  2s . c o  m*/
        try (RestClient client = buildRestClient()) {
            try {
                client.performRequest("GET", "/");
                fail("connection should have been rejected due to SSL handshake");
            } catch (Exception e) {
                assertThat(e.getMessage(), containsString("General SSLEngine problem"));
            }
        }

        SSLContext.setDefault(getSslContext());
        try (RestClient client = buildRestClient()) {
            Response response = client.performRequest("GET", "/");
            assertEquals(200, response.getStatusLine().getStatusCode());
        }
    } finally {
        SSLContext.setDefault(defaultSSLContext);
    }
}

From source file:securitytools.common.http.HttpClientFactory.java

public static CloseableHttpAsyncClient buildAsync(ClientConfiguration clientConfiguration)
        throws NoSuchAlgorithmException {
    HttpAsyncClientBuilder builder = HttpAsyncClients.custom();

    // Certificate Validation
    // TODO//  ww  w.java 2 s . c  o m
    if (clientConfiguration.isCertificateValidationEnabled()) {
        builder.setSSLStrategy(new SSLIOSessionStrategy(SSLContext.getDefault(),
                SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER));
    } else {
        // Disable
        SSLIOSessionStrategy sslStrategy = new SSLIOSessionStrategy(SSLContext.getDefault(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        builder.setSSLStrategy(sslStrategy);
    }

    // Timeouts
    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom();
    requestConfigBuilder.setConnectTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setConnectionRequestTimeout(clientConfiguration.getConnectionTimeout());
    requestConfigBuilder.setSocketTimeout(clientConfiguration.getSocketTimeout());
    builder.setDefaultRequestConfig(requestConfigBuilder.build());

    // User Agent
    builder.setUserAgent(clientConfiguration.getUserAgent());

    // Proxy
    if (clientConfiguration.getProxyHost() != null) {
        builder.setProxy(clientConfiguration.getProxyHost());
    }

    return builder.build();
}

From source file:HCNIOEngine.java

private CloseableHttpAsyncClient createCloseableHttpAsyncClient() throws Exception {
    HttpAsyncClientBuilder builder = HttpAsyncClientBuilder.create();
    builder.useSystemProperties();/*  w  ww.ja va2s  .co m*/
    builder.setSSLContext(SSLContext.getDefault());
    builder.setConnectionReuseStrategy(DefaultConnectionReuseStrategy.INSTANCE);
    builder.setMaxConnPerRoute(2);
    builder.setMaxConnTotal(2);
    builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(1000)
            .setConnectTimeout(2000).setSocketTimeout(2000).build());
    //        builder.setHttpProcessor()
    CloseableHttpAsyncClient hc = builder.build();
    hc.start();
    return hc;
}

From source file:org.ulyssis.ipp.publisher.HttpOutput.java

private SSLContext createSslCustomContext() {
    try {/*from w ww. j  ava 2s  .c o  m*/
        SSLContextBuilder builder = SSLContexts.custom();
        if (options.getKeystore().isPresent()) {
            KeyStore cks = KeyStore.getInstance(KeyStore.getDefaultType());
            cks.load(new FileInputStream(options.getKeystore().get().toFile()),
                    options.getKeystorePass().toCharArray());
            builder.loadKeyMaterial(cks, options.getKeystorePass().toCharArray());
        }

        if (options.getTruststore().isPresent()) {
            KeyStore tks = KeyStore.getInstance(KeyStore.getDefaultType());
            tks.load(new FileInputStream(options.getTruststore().get().toFile()),
                    options.getTruststorePass().toCharArray());
            builder.loadTrustMaterial(tks, new TrustSelfSignedStrategy());
        }

        if (!options.getKeystore().isPresent() && !options.getKeystore().isPresent()) {
            return SSLContext.getDefault();
        }

        return builder.build();
    } catch (Exception e) {
        // TODO: DO SOMETHING WITH THE EXCEPTION!
        LOG.error("Exception", e);
    }
    return null;
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransportTests.java

private ProtocolSocketFactory getSocketFactory() throws Exception {
    final SSLSocketFactory delegate = SSLContext.getDefault().getSocketFactory();
    return new ProtocolSocketFactory() {

        @Override//w  ww.  ja v a 2 s . co m
        public Socket createSocket(String host, int port, InetAddress localAddress, int localPort)
                throws IOException, UnknownHostException {
            return delegate.createSocket(host, port, localAddress, localPort);
        }

        @Override
        public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
                HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
            return this.createSocket(host, port, localAddress, localPort);
        }

        @Override
        public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
            return delegate.createSocket(host, port);
        }
    };
}