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:org.apache.cxf.fediz.integrationtests.HTTPTestUtils.java

/**
 * Same as sendHttpGet above, except that we return the HttpClient so that it can
 * subsequently be re-used (for e.g. logout)
 *///from   www . j  a  v a  2  s  .  com
public static CloseableHttpClient sendHttpGetForSignIn(String url, String user, String password,
        int returnCodeIDP, int returnCodeRP, int idpPort) throws Exception {

    CloseableHttpClient httpClient = null;
    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();

    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();
    Assert.assertTrue("RP HTTP Response code: " + response.getStatusLine().getStatusCode() + " [Expected: "
            + returnCodeRP + "]", returnCodeRP == response.getStatusLine().getStatusCode());

    String responseStr = EntityUtils.toString(entity);
    Assert.assertTrue("Principal not " + user, responseStr.indexOf("userPrincipal=" + user) > 0);

    return httpClient;
}

From source file:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java

public static void setTruststore(File file, String password) throws CertificateException,
        NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
    if (!file.isFile()) {
        throw new RuntimeException("Truststore file not found: " + file.getAbsolutePath());
    }//from   ww w . ja  v a2s.c om
    SSLContext theContext = SSLContexts.custom().useProtocol("TLS")
            .loadTrustMaterial(file, password == null ? null : password.toCharArray()).build();
    sslsf = new SSLConnectionSocketFactory(theContext);
}

From source file:com.liferay.sync.engine.session.Session.java

private static SSLConnectionSocketFactory _getDefaultSSLSocketFactory() throws Exception {

    if (_defaultSSLSocketFactory == null) {
        _defaultSSLSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault());
    }/*from  ww  w.j a va 2s. c  o m*/

    return _defaultSSLSocketFactory;
}

From source file:org.esbtools.message.admin.common.EsbMessageAdminServiceImpl.java

private Boolean sendMessageToRestEndPoint(String message, List<String> endpoints) {
    CloseableHttpClient httpClient;/*from w  w w . java 2 s.c o m*/
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        for (String restEndPoint : endpoints) {
            try {
                HttpPost httpPost = new HttpPost(restEndPoint);
                httpPost.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
                httpPost.setEntity(new StringEntity(message.toString()));

                CloseableHttpResponse httpResponse = httpClient.execute(httpPost);

                if (httpResponse.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
                    // status is Success by default
                    return true;
                } else {
                    // try another host
                    LOG.warn("Message failed to transmit, received HTTP response code:"
                            + httpResponse.getStatusLine().getStatusCode() + " with message:"
                            + httpResponse.getEntity().toString() + " from:" + restEndPoint);
                }
            } catch (IOException e) {
                LOG.error(e.getMessage(), e);
            }
        }
        httpClient.close();
    } catch (Exception e) {
        LOG.error(e.getMessage());
    }
    return false;
}

From source file:org.wso2.greg.plugin.Utils.java

/**
 * Method to initialize the http client. We use only one instance of http client since there can not be concurrent
 * invocations/*from w w  w.  ja v  a  2 s . com*/
 *
 * @return @link{HttpClient} httpClient instance
 */
public static HttpClient getHttpClient() {

    HttpClient httpClient = null;
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build());
        httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();

    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to load the trust store", e);
    } catch (KeyStoreException e) {
        log.error("Unable to get the key store instance", e);
    } catch (KeyManagementException e) {
        log.error("Unable to load trust store material", e);
    }
    return httpClient;
}

From source file:org.elasticsearch.test.rest.client.RestTestClient.java

private static RestClient createRestClient(URL[] urls, Settings settings) throws IOException {
    String protocol = settings.get(PROTOCOL, "http");
    HttpHost[] hosts = new HttpHost[urls.length];
    for (int i = 0; i < hosts.length; i++) {
        URL url = urls[i];//  w w w. j  av a 2 s  . co m
        hosts[i] = new HttpHost(url.getHost(), url.getPort(), protocol);
    }
    RestClient.Builder builder = RestClient.builder(hosts).setMaxRetryTimeoutMillis(30000)
            .setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setSocketTimeout(30000));

    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslcontext);
            builder.setHttpClientConfigCallback(
                    new SSLSocketFactoryHttpConfigCallback(sslConnectionSocketFactory));
        } catch (KeyStoreException | NoSuchAlgorithmException | KeyManagementException
                | CertificateException e) {
            throw new RuntimeException(e);
        }
    }

    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}

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

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

    CloseableHttpClient httpClient = null;
    try {//from www .  ja v a2s  .  c  o m
        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.setSSLSocketFactory(sslSocketFactory);
        httpClientBuilder.setRedirectStrategy(new LaxRedirectStrategy());

        httpClient = httpClientBuilder.build();

        HttpGet httpget = new HttpGet(url);
        httpget.addHeader("Authorization", "Negotiate " + ticket);

        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:de.zazaz.iot.bosch.indego.ifttt.IftttIndegoAdapter.java

/**
 * This creates a HTTP client instance for connecting the IFTTT server.
 * //from   w  ww. j  a  v a 2s. c om
 * @return the HTTP client instance
 */
private CloseableHttpClient buildHttpClient() {
    if (configuration.isIftttIgnoreServerCertificate()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] chain_, String authType_)
                        throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (Exception ex) {
            LOG.error(ex);
            // This should never happen, but we have to handle it
            throw new RuntimeException(ex);
        }
    } else {
        return HttpClients.createDefault();
    }
}

From source file:org.springframework.boot.web.servlet.server.AbstractServletWebServerFactoryTests.java

@Test
public void sslDisabled() throws Exception {
    AbstractServletWebServerFactory factory = getFactory();
    Ssl ssl = getSsl(null, "password", "classpath:test.jks");
    ssl.setEnabled(false);/*from w w  w  .j  av a  2 s.  c o  m*/
    factory.setSsl(ssl);
    this.webServer = factory
            .getWebServer(new ServletRegistrationBean<>(new ExampleServlet(true, false), "/hello"));
    this.webServer.start();
    SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
            new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
    HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);
    this.thrown.expect(SSLException.class);
    getResponse(getLocalUrl("https", "/hello"), requestFactory);
}