Example usage for org.apache.http.conn.ssl SSLContextBuilder loadTrustMaterial

List of usage examples for org.apache.http.conn.ssl SSLContextBuilder loadTrustMaterial

Introduction

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

Prototype

public SSLContextBuilder loadTrustMaterial(final KeyStore truststore, final TrustStrategy trustStrategy)
            throws NoSuchAlgorithmException, KeyStoreException 

Source Link

Usage

From source file:org.bimserver.build.CreateGitHubRelease.java

public static void main(String[] args) {
    String username = args[0];//from   ww w  .  jav  a2  s  . c  o  m
    String password = args[1];
    String repo = args[2];
    String project = args[3];
    String tagname = args[4];
    String name = args[5];
    String body = args[6];
    String draft = args[7];
    String prerelease = args[8];
    String filesString = args[9];
    String[] filenames = filesString.split(";");

    GitHubClient gitHubClient = new GitHubClient("api.github.com");
    gitHubClient.setCredentials(username, password);

    Map<String, String> map = new HashMap<String, String>();
    map.put("tag_name", tagname);
    // map.put("target_commitish", "test");
    map.put("name", name);
    map.put("body", body);
    //      map.put("draft", draft);
    //      map.put("prerelease", prerelease);
    try {
        String string = "/repos/" + repo + "/" + project + "/releases";
        System.out.println(string);
        JsonObject gitHubResponse = gitHubClient.post(string, map, JsonObject.class);
        System.out.println(gitHubResponse);
        String id = gitHubResponse.get("id").getAsString();

        HttpHost httpHost = new HttpHost("uploads.github.com", 443, "https");

        BasicCredentialsProvider basicCredentialsProvider = new BasicCredentialsProvider();
        basicCredentialsProvider.setCredentials(new AuthScope(httpHost),
                new UsernamePasswordCredentials(username, password));

        HostnameVerifier hostnameVerifier = new AllowAllHostnameVerifier();

        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient client = HttpClients.custom()
                .setDefaultCredentialsProvider(basicCredentialsProvider)
                .setHostnameVerifier((X509HostnameVerifier) hostnameVerifier).setSSLSocketFactory(sslsf)
                .build();

        AuthCache authCache = new BasicAuthCache();
        BasicScheme basicAuth = new BasicScheme();
        authCache.put(httpHost, basicAuth);

        HttpClientContext context = HttpClientContext.create();
        context.setCredentialsProvider(basicCredentialsProvider);
        context.setAuthCache(authCache);

        for (String filename : filenames) {
            File file = new File(filename);
            String url = "https://uploads.github.com/repos/" + repo + "/" + project + "/releases/" + id
                    + "/assets?name=" + file.getName();
            HttpPost post = new HttpPost(url);
            post.setHeader("Accept", "application/vnd.github.manifold-preview");
            post.setHeader("Content-Type", "application/zip");
            post.setEntity(new InputStreamEntity(new FileInputStream(file), file.length()));
            HttpResponse execute = client.execute(httpHost, post, context);
            execute.getEntity().getContent().close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:com.vmware.content.samples.client.util.HttpUtil.java

private static CloseableHttpClient getCloseableHttpClient()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}

From source file:org.wso2.carbon.device.mgt.iot.input.adapter.mqtt.util.MQTTUtil.java

/**
 * Return a http client instance//from  www .  j  a  va2 s  . c  o  m
 *
 * @param protocol- service endpoint protocol http/https
 * @return
 */
public static HttpClient getHttpClient(String protocol)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClient httpclient;
    if (HTTPS_PROTOCOL.equals(protocol)) {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } else {
        httpclient = HttpClients.createDefault();
    }
    return httpclient;
}

From source file:org.wso2.carbon.device.mgt.iot.util.IoTUtil.java

/**
 * Return a http client instance// ww w .j  a  v a2s  . c o  m
 * @param protocol- service endpoint protocol http/https
 * @return
 */
public static HttpClient getHttpClient(int port, String protocol)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    HttpClient httpclient;
    if (HTTPS_PROTOCOL.equals(protocol)) {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } else {
        httpclient = HttpClients.createDefault();
    }
    return httpclient;
}

From source file:com.ibm.watson.app.common.util.http.HttpClientBuilder.java

public static CloseableHttpClient buildDefaultHttpClient(Credentials cred) {

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    RequestConfig defaultRequestConfig;/*ww  w .ja v a 2 s .  c o m*/

    //private DefaultHttpClient client;
    connManager.setMaxTotal(200);
    connManager.setDefaultMaxPerRoute(50);
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        // Create a registry of custom connection socket factories for supported
        // protocol schemes.
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(builder.build())).build();
    } catch (Exception e) {
        logger.warn(MessageKey.AQWEGA02000W_unable_init_ssl_context.getMessage(), e);
    }
    // Create global request configuration
    defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(
                    Arrays.asList(AuthSchemes.BASIC, AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setAuthenticationEnabled(true).build();

    if (cred != null)
        credentialsProvider.setCredentials(AuthScope.ANY, cred);

    return HttpClients.custom().setConnectionManager(connManager).setDefaultCookieStore(cookieStore)
            .setDefaultCredentialsProvider(credentialsProvider).setDefaultRequestConfig(defaultRequestConfig)
            .build();
}

From source file:photosharing.api.ExecutorUtil.java

/**
 * helper method that returns an HTTPClient executor with credentials
 * available./*from ww  w.ja  va2 s. co  m*/
 * 
 * Also enables the test case to connect to ANY SSL Certificate
 * valid/invalid
 * 
 * @return {Executor} or Null if there is an issue
 */
public static Executor getExecutor() {
    Executor executor = null;

    /*
     * if using one of the environments without a trusted CA chain or
     * you are using Fiddler, you want to set TRUST=TRUE in appconfig.properties
     */
    Configuration config = Configuration.getInstance(null);
    String sTrust = config.getValue(Configuration.TRUST);
    boolean trusted = Boolean.parseBoolean(sTrust);
    if (trusted) {
        try {
            HttpClientBuilder builder = HttpClients.custom();

            // Setup the SSL Context to Trust Any SSL Certificate
            SSLContextBuilder sslBuilder = new SSLContextBuilder();
            sslBuilder.loadTrustMaterial(null, new TrustStrategy() {
                /**
                 * override for fiddler proxy
                 */
                public boolean isTrusted(X509Certificate[] certs, String host) throws CertificateException {
                    return true;
                }
            });
            SSLContext sslContext = sslBuilder.build();
            builder.setHostnameVerifier(new AllowAllHostnameVerifier());
            builder.setSslcontext(sslContext);

            CloseableHttpClient httpClient = builder.build();
            executor = Executor.newInstance(httpClient);
        } catch (NoSuchAlgorithmException e) {
            logger.log(Level.SEVERE, "Issue with No Algorithm " + e.toString());
        } catch (KeyStoreException e) {
            logger.log(Level.SEVERE, "Issue with KeyStore " + e.toString());
        } catch (KeyManagementException e) {
            logger.log(Level.SEVERE, "Issue with KeyManagement  " + e.toString());
        }
    }

    return executor;
}

From source file:org.jenkinsci.plugins.kubernetesworkflowsteps.KubeStepExecution.java

private static CloseableHttpClient getClient()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    if (client == null) {
        synchronized (client_lock) {
            if (client == null) {
                SSLContextBuilder builder = SSLContexts.custom();
                builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

                SSLContext sslContext = builder.build();

                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                        SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

                Collection<BasicHeader> headers = new ArrayList<BasicHeader>();
                headers.add(new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json"));
                headers.add(new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + env.get("BEARER_TOKEN")));

                client = HttpClients.custom().setDefaultHeaders(headers).setSSLSocketFactory(sslsf).build();
            }//ww w. j a  va 2  s  .co  m
        }
    }
    return client;
}

From source file:org.apache.camel.component.solr.JettySolrFactory.java

private static void installAllTrustingClientSsl()
        throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

    // // Create a trust manager that does not validate certificate chains
    final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override/* ww w  . jav  a2 s  . c o  m*/
        public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    } };
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
    SSLContext.setDefault(sslContext);

    // // Install the all-trusting trust manager
    // final SSLContext sslContext = SSLContext.getInstance( "SSL" );
    // sslContext.init( null, trustAllCerts, new
    // java.security.SecureRandom() );
    // // Create an ssl socket factory with our all-trusting manager
    // final SSLSocketFactory sslSocketFactory =
    // sslContext.getSocketFactory();
    // HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
}

From source file:com.vmware.vim25.ws.ApacheTrustSelfSigned.java

public static SSLConnectionSocketFactory trust() {
    SSLContextBuilder builder = new SSLContextBuilder();
    log.trace("Set SSL Context Builder to trust self signed certs.");
    try {/*from   ww w .  ja v  a 2s  .  c  om*/
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        log.trace("Added Self Signed Strategy to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("NoSuchAlgorithm caught trying to add SelfSignedStrategy.", e);
        return null;
    } catch (KeyStoreException e) {
        log.error("KeyStoreException caught trying to add TrustSelfSignedStrategy.", e);
        return null;
    }
    SSLConnectionSocketFactory sslConnectionSocketFactory;
    try {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                new AllowAllHostnameVerifier());
        log.trace("Added SSLConnectionSocketFactory to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    } catch (KeyManagementException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    }
    log.trace("Created self signed trust.");
    return sslConnectionSocketFactory;
}

From source file:com.toastcoders.vcumeter.ws.util.ApacheTrustSelfSignedSSL.java

/**
 * Method that intentionally break SSL by accepting any self signed SSL
 * certs. This is how the default VMware certs are signed.
 *
 * @return// w ww .ja  va 2 s  . c o m
 */
public static SSLConnectionSocketFactory trust() {
    SSLContextBuilder builder = new SSLContextBuilder();
    log.trace("Set SSL Context Builder to trust self signed certs.");
    try {
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        log.trace("Added Self Signed Strategy to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("NoSuchAlgorithm caught trying to add SelfSignedStrategy.", e);
        return null;
    } catch (KeyStoreException e) {
        log.error("KeyStoreException caught trying to add TrustSelfSignedStrategy.", e);
        return null;
    }
    SSLConnectionSocketFactory sslConnectionSocketFactory;
    try {
        sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build(),
                new AllowAllHostnameVerifier());
        log.trace("Added SSLConnectionSocketFactory to builder.");
    } catch (NoSuchAlgorithmException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    } catch (KeyManagementException e) {
        log.error("Error trying to trust self signed certs.", e);
        return null;
    }
    log.trace("Created self signed trust.");
    return sslConnectionSocketFactory;
}