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

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

Introduction

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

Prototype

public SSLContextBuilder() 

Source Link

Usage

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

public static void main(String[] args) {
    String username = args[0];//from w ww . j av a2s.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.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 w w w  .  java 2s .c o  m
        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//  ww  w .  ja v  a 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;
}

From source file:utils.HttpClientGenerator.java

public static CloseableHttpClient getHttpClient(boolean checkCert) {

    if (checkCert == false) {
        HttpClientBuilder b = HttpClientBuilder.create();

        // setup a Trust Strategy that allows all certificates.
        SSLContext sslContext = null;
        try {//from  w w w .  j a  v  a 2s.  c  om
            sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build();
        } catch (NoSuchAlgorithmException e) {
            String err = "error occurred while creating SSL disables hhtp client";
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        b.setSslcontext(sslContext);

        // not to check Hostnames
        HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

        //       create an SSL Socket Factory, to use weakened "trust strategy";
        //       and create a Registry, to register it.
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                (X509HostnameVerifier) hostnameVerifier);
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslSocketFactory).build();

        // creating connection-manager using our Registry.
        //      -- allows multi-threaded use
        PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(
                socketFactoryRegistry);
        connMgr.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        connMgr.setMaxPerRoute(new HttpRoute(localhost), 10);
        b.setConnectionManager(connMgr);

        // finally, build the HttpClient;
        CloseableHttpClient client = b.build();
        return client;
    } else {
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        // Increase default max connection per route to 20
        cm.setDefaultMaxPerRoute(20);
        // Increase max connections for localhost:80 to 50
        HttpHost localhost = new HttpHost("localhost", 9443);
        cm.setMaxPerRoute(new HttpRoute(localhost), 10);
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(cm).build();
        return client;
    }
}

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

/**
 * Return a http client instance/*from ww  w .  j a  v a2 s.com*/
 *
 * @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//from   w  w w . j ava 2  s  .co 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:org.workin.http.httpclient.v4.factory.DefaultSSLContextFacotry.java

@Override
public SSLContext create() throws GeneralSecurityException {
    SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
        @Override//from  www. ja v a  2  s  .co m
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // 
            return true;
        }
    }).build();

    return sslContext;
}

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/* w  ww  .  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:photosharing.api.ExecutorUtil.java

/**
 * helper method that returns an HTTPClient executor with credentials
 * available.//from   w w  w  .jav  a 2 s. c  om
 * 
 * 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:com.muhardin.endy.training.ws.aplikasi.absen.rest.client.AbsenRestClient.java

public AbsenRestClient() {
    try {//from  ww w  . java2s. co  m
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("endy", "123");
        provider.setCredentials(AuthScope.ANY, credentials);
        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(provider)
                .setSSLSocketFactory(sslsf).build();

        restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(client));
        restTemplate.setErrorHandler(new AbsenRestClientErrorHandler());
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) {
        Logger.getLogger(AbsenRestClient.class.getName()).log(Level.SEVERE, null, ex);
    }
}