Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory.

Prototype

public SSLConnectionSocketFactory(final SSLContext sslContext) 

Source Link

Usage

From source file:io.wcm.caravan.commons.httpclient.impl.HttpClientItem.java

private static PoolingHttpClientConnectionManager buildConnectionManager(HttpClientConfig config,
        SSLContext sslContext) {//from   ww  w  . ja va2  s. c  o  m
    // scheme configuration
    ConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
    Registry<ConnectionSocketFactory> schemeRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    // pooling settings
    PoolingHttpClientConnectionManager conmgr = new PoolingHttpClientConnectionManager(schemeRegistry);
    conmgr.setMaxTotal(config.getMaxTotalConnections());
    conmgr.setDefaultMaxPerRoute(config.getMaxConnectionsPerHost());
    return conmgr;
}

From source file:com.palominolabs.crm.sf.rest.RestConnectionPoolImpl.java

/**
 * Create a new pool with a specific idle connection timeout.
 *
 * @param metricRegistry metric registry
 * @param idleConnTimeout how long an unused connection must sit idle before it is eligible for removal from the
 *///w w  w. j a va 2  s. c  o  m
public RestConnectionPoolImpl(MetricRegistry metricRegistry, int idleConnTimeout) {
    this.metricRegistry = metricRegistry;

    SSLContext sslContext = null;
    try {
        sslContext = SSLContexts.custom().useProtocol("TLSv1.2").build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);

    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslsf).build();

    connectionManager = new PoolingHttpClientConnectionManager(r);
    connectionManager.setDefaultMaxPerRoute(20);
    connectionManager.setMaxTotal(60);

    SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(300000).build();
    connectionManager.setDefaultSocketConfig(socketConfig);

    objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.httpClient = HttpClientBuilder.create().setConnectionManager(connectionManager).build();
    this.idleConnTimeout = idleConnTimeout;
}

From source file:org.springframework.xd.shell.security.SecuredShellAccessWithSslTest.java

@Test
public void testSpringXDTemplate() throws Exception {
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "whosThere"));
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(new SSLContextBuilder()
                            .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build()))
                    .build());/*from   w ww  .ja v  a2  s  . c  o m*/
    SpringXDTemplate template = new SpringXDTemplate(requestFactory, new URI("https://localhost:" + adminPort));
    PagedResources<ModuleDefinitionResource> moduleDefinitions = template.moduleOperations()
            .list(RESTModuleType.sink);
    assertThat(moduleDefinitions.getLinks().size(), greaterThan(0));
}

From source file:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

public static String sendHttpGet(String url, String user, String password, int returnCodeIDP, int returnCodeRP,
        int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    try {/*  www  . j  a v  a  2s .com*/
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", idpPort),
                new UsernamePasswordCredentials(user, password));

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        FileInputStream instream = new FileInputStream(new File("./target/test-classes/client.jks"));
        try {
            trustStore.load(instream, "clientpass".toCharArray());
        } finally {
            try {
                instream.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy());
        sslContextBuilder.loadKeyMaterial(trustStore, "clientpass".toCharArray());

        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
        httpClientBuilder.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);

        HttpResponse response = httpClient.execute(httpget);
        HttpEntity entity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }
        Assert.assertTrue("IDP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeIDP + "]", returnCodeIDP == response.getStatusLine().getStatusCode());

        if (response.getStatusLine().getStatusCode() != 200) {
            return null;
        }

        //            Redirect to a POST is not supported without user interaction
        //            http://www.ietf.org/rfc/rfc2616.txt
        //            If the 301 status code is received in response to a request other
        //            than GET or HEAD, the user agent MUST NOT automatically redirect the
        //            request unless it can be confirmed by the user, since this might
        //            change the conditions under which the request was issued.

        Source source = new Source(EntityUtils.toString(entity));
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        FormFields formFields = source.getFormFields();

        List<Element> forms = source.getAllElements(HTMLElementName.FORM);
        Assert.assertEquals("Only one form expected but got " + forms.size(), 1, forms.size());
        String postUrl = forms.get(0).getAttributeValue("action");

        Assert.assertNotNull("Form field 'wa' not found", formFields.get("wa"));
        Assert.assertNotNull("Form field 'wresult' not found", formFields.get("wresult"));

        for (FormField formField : formFields) {
            if (formField.getUserValueCount() != 0) {
                nvps.add(new BasicNameValuePair(formField.getName(), formField.getValues().get(0)));
            }
        }
        HttpPost httppost = new HttpPost(postUrl);
        httppost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));

        response = httpClient.execute(httppost);

        entity = response.getEntity();
        System.out.println(response.getStatusLine());
        Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
                + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

        if (entity != null) {
            System.out.println("Response content length: " + entity.getContentLength());
        }

        return EntityUtils.toString(entity);
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:com.insys.cfclient.nozzle.InfluxDBSender.java

@PostConstruct
public void postConstruct() throws Exception {
    if (properties.isSkipSslValidation()) {
        TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;

        SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom()
                .loadTrustMaterial(null, acceptingTrustStrategy).build();

        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);

        CloseableHttpClient apacheHttpClient = HttpClients.custom().setSSLSocketFactory(csf).build();

        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();

        requestFactory.setHttpClient(apacheHttpClient);

        this.httpClient.setRequestFactory(requestFactory);
    }//from w w w. j  av  a 2s .  c  o  m
}

From source file:org.wso2.carbon.identity.cloud.web.jaggery.clients.MutualSSLHttpClient.java

public MutualSSLHttpClient() {
    String filePath = null;/*from ww  w  .  j  a  v  a2  s.c o m*/
    try {
        final KeyStore keyStore = KeyStore.getInstance(keyStoreType);
        filePath = ServerConfiguration.getInstance().getFirstProperty(SecurityKeyStoreLocation);
        InputStream keystoreInput = new FileInputStream(new File(filePath));
        keyStore.load(keystoreInput,
                ServerConfiguration.getInstance().getFirstProperty(SecurityKeyStorePassword).toCharArray());

        final KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        filePath = ServerConfiguration.getInstance().getFirstProperty(SecurityTrustStoreLocation);
        InputStream truststoreInput = new FileInputStream(new File(filePath));
        trustStore.load(truststoreInput,
                ServerConfiguration.getInstance().getFirstProperty(SecurityTrustStorePassword).toCharArray());

        SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore).loadKeyMaterial(keyStore,
                ServerConfiguration.getInstance().getFirstProperty(SecurityKeyStorePassword).toCharArray())
                .build();

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext);
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (KeyStoreException e) {
        log.error("Error while instantiating key store for key store type : " + keyStoreType, e);
    } catch (FileNotFoundException e) {
        log.error("File not found in the given path : " + filePath, e);
    } catch (IOException e) {
        log.error("Error while loading the key store in the given path : " + filePath, e);
    } catch (CertificateException e) {
        log.error("Certificate error in the key store : " + filePath, e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Algorithm error in the key store : " + filePath, e);
    } catch (UnrecoverableKeyException e) {
        log.error("Error while creating the SSLContext", e);
    } catch (KeyManagementException e) {
        log.error("Error while creating the SSLContext", e);
    }
}

From source file:org.edeoliveira.oauth2.dropwizard.oauth2.auth.RestClientBuilder.java

public RestClientBuilder setupSSL(ApiServerConfig cfg) {
    SSLContext sslContext;//from  w w w.j  a va 2  s .c o  m
    ConnectorFactory factory = cfg.getClientConfig();

    if (factory == null || !(factory instanceof HttpsConnectorFactory))
        return this;

    HttpsConnectorFactory hcf = (HttpsConnectorFactory) factory;

    if (hcf.getKeyStorePath() != null) {
        keyStore = hcf.getKeyStorePath();
        keyStorePassword = hcf.getKeyStorePassword();
        trustStore = hcf.getTrustStorePath();
        trustStorePassword = hcf.getTrustStorePassword();

        sslContext = getSSLContext();
    } else {
        SslConfigurator sslConfig = SslConfigurator.newInstance();
        sslContext = sslConfig.createSSLContext();
    }

    SSLConnectionSocketFactory sslConnectionSocketFactory = hcf.isValidateCerts()
            ? new SSLConnectionSocketFactory(sslContext)
            : new SSLConnectionSocketFactory(sslContext,
                    SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslConnectionSocketFactory).build();
    using(registry);

    return this;
}

From source file:org.ensembl.gti.seqstore.database.cramstore.EnaCramSubmitter.java

protected static HttpClient getHttpsClient() {
    try {/*  w  w  w .  j ava2  s.  c  o m*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        return HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.itesla_project.histodb.client.impl.HistoDbHttpClientImpl.java

private synchronized CloseableHttpClient getHttpclient(HistoDbConfig config) {
    if (httpClient == null) {
        try {/*from  w ww .  ja v  a2 s.  c o m*/
            ConnectionSocketFactory plainsf = PlainConnectionSocketFactory.getSocketFactory();
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                @Override
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {
                }
            } };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            LayeredConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
            Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("http", plainsf).register("https", sslsf).build();
            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);
            cm.setDefaultMaxPerRoute(10);
            cm.setMaxTotal(20);
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setConnectionManager(cm);
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    new AuthScope(new HttpHost(config.getConnectionParameters().getHost(),
                            config.getConnectionParameters().getPort())),
                    new UsernamePasswordCredentials(config.getConnectionParameters().getUserName(),
                            config.getConnectionParameters().getPassword()));
            if (config.getProxyParameters() != null) {
                HttpHost proxy = new HttpHost(config.getProxyParameters().getHost(),
                        config.getProxyParameters().getPort());
                credentialsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(
                        config.getProxyParameters().getUserName(), config.getProxyParameters().getPassword()));
                httpClientBuilder.setProxy(proxy);
            }
            httpClient = httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).build();
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
    return httpClient;
}

From source file:io.fabric8.maven.docker.access.hc.http.HttpClientBuilder.java

private static Registry<ConnectionSocketFactory> getSslFactoryRegistry(String certPath) throws IOException {
    try {/*w ww  . j  av  a 2  s  .  co  m*/
        KeyStore keyStore = KeyStoreUtil.createDockerKeyStore(certPath);

        SSLContext sslContext = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS)
                .loadKeyMaterial(keyStore, "docker".toCharArray()).loadTrustMaterial(keyStore, null).build();
        String tlsVerify = System.getenv("DOCKER_TLS_VERIFY");
        SSLConnectionSocketFactory sslsf = tlsVerify != null && !tlsVerify.equals("0")
                && !tlsVerify.equals("false") ? new SSLConnectionSocketFactory(sslContext)
                        : new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);

        return RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslsf).build();
    } catch (GeneralSecurityException e) {
        // this isn't ideal but the net effect is the same
        throw new IOException(e);
    }
}