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

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

Introduction

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

Prototype

public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException 

Source Link

Usage

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

public static void main(String[] args) {
    String username = args[0];//from  w  w  w  .jav  a  2  s.com
    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:be.dnsbelgium.rdap.client.RDAPCLI.java

public static void main(String[] args) {

    LOGGER.debug("Create the command line parser");
    CommandLineParser parser = new GnuParser();

    LOGGER.debug("Create the options");
    Options options = new RDAPOptions(Locale.ENGLISH);

    try {/*from   w  ww  . j a  v a2 s . co m*/
        LOGGER.debug("Parse the command line arguments");
        CommandLine line = parser.parse(options, args);

        if (line.hasOption("help")) {
            printHelp(options);
            return;
        }

        if (line.getArgs().length == 0) {
            throw new IllegalArgumentException("You must provide a query");
        }
        String query = line.getArgs()[0];

        Type type = (line.getArgs().length == 2) ? Type.valueOf(line.getArgs()[1].toUpperCase())
                : guessQueryType(query);

        LOGGER.debug("Query: {}, Type: {}", query, type);

        try {
            SSLContextBuilder sslContextBuilder = SSLContexts.custom();
            if (line.hasOption(RDAPOptions.TRUSTSTORE)) {
                sslContextBuilder.loadTrustMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.TRUSTSTORE)),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.TRUSTSTORE_PASS, RDAPOptions.DEFAULT_PASS)));
            }
            if (line.hasOption(RDAPOptions.KEYSTORE)) {
                sslContextBuilder.loadKeyMaterial(
                        RDAPClient.getKeyStoreFromFile(new File(line.getOptionValue(RDAPOptions.KEYSTORE)),
                                line.getOptionValue(RDAPOptions.KEYSTORE_TYPE, RDAPOptions.DEFAULT_STORETYPE),
                                line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS)),
                        line.getOptionValue(RDAPOptions.KEYSTORE_PASS, RDAPOptions.DEFAULT_PASS).toCharArray());
            }
            SSLContext sslContext = sslContextBuilder.build();

            final String url = line.getOptionValue(RDAPOptions.URL);
            final HttpHost host = Utils.httpHost(url);

            HashSet<Header> headers = new HashSet<Header>();
            headers.add(new BasicHeader("Accept-Language",
                    line.getOptionValue(RDAPOptions.LANG, Locale.getDefault().toString())));
            HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultHeaders(headers)
                    .setSSLSocketFactory(new SSLConnectionSocketFactory(sslContext,
                            (line.hasOption(RDAPOptions.INSECURE) ? new AllowAllHostnameVerifier()
                                    : new BrowserCompatHostnameVerifier())));

            if (line.hasOption(RDAPOptions.USERNAME) && line.hasOption(RDAPOptions.PASSWORD)) {
                BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                credentialsProvider.setCredentials(new AuthScope(host.getHostName(), host.getPort()),
                        new UsernamePasswordCredentials(line.getOptionValue(RDAPOptions.USERNAME),
                                line.getOptionValue(RDAPOptions.PASSWORD)));
                httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }

            RDAPClient rdapClient = new RDAPClient(httpClientBuilder.build(), url);
            ObjectMapper mapper = new ObjectMapper();

            JsonNode json = null;
            switch (type) {
            case DOMAIN:
                json = rdapClient.getDomainAsJson(query);
                break;
            case ENTITY:
                json = rdapClient.getEntityAsJson(query);
                break;
            case AUTNUM:
                json = rdapClient.getAutNum(query);
                break;
            case IP:
                json = rdapClient.getIp(query);
                break;
            case NAMESERVER:
                json = rdapClient.getNameserver(query);
                break;
            }
            PrintWriter out = new PrintWriter(System.out, true);
            if (line.hasOption(RDAPOptions.RAW)) {
                mapper.writer().writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.PRETTY)) {
                mapper.writer(new DefaultPrettyPrinter()).writeValue(out, json);
            } else if (line.hasOption(RDAPOptions.YAML)) {
                DumperOptions dumperOptions = new DumperOptions();
                dumperOptions.setPrettyFlow(true);
                dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                dumperOptions.setSplitLines(true);
                Yaml yaml = new Yaml(dumperOptions);
                Map data = mapper.convertValue(json, Map.class);
                yaml.dump(data, out);
            } else {
                mapper.writer(new MinimalPrettyPrinter()).writeValue(out, json);
            }
            out.flush();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            System.exit(-1);
        }
    } catch (org.apache.commons.cli.ParseException e) {
        printHelp(options);
        System.exit(-1);
    }
}

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   w  w w  .j  a va2  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.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();
            }// www.  j  av  a 2 s. c  o m
        }
    }
    return client;
}

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

/**
 * Return a http client instance//from   w w w.  j a va2  s .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.ecofactor.qa.automation.consumerapi.dr.HTTPSClient.java

/**
 * Gets the http client.// ww w . j a va 2s  . c om
 *
 * @param certificate the certificate
 * @param password the password
 * @return the http client
 */
public static CloseableHttpClient getPKCSKeyHttpClient(final String certificate, final String password) {

    try {
        final KeyStore keystore = KeyStore.getInstance("pkcs12");
        keystore.load(HTTPSClient.class.getClassLoader().getResourceAsStream(certificate),
                password.toCharArray());
        final SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadKeyMaterial(keystore, password.toCharArray());
        final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

        final CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                .setHostnameVerifier(new AllowAllHostnameVerifier()).build();
        return httpClient;
    } catch (UnrecoverableKeyException | KeyManagementException | KeyStoreException | NoSuchAlgorithmException
            | CertificateException | IOException e) {
        LOGGER.error("Error processing SSL certificates in HTTPS method. Reason ::: " + e);
        return null;
    }
}

From source file:test.SAMLAttributeQueryExample.java

/**
 * Build the HTTP client.//w  w  w . j  av  a2  s.com
 * 
 * @param idpCertificateFile path to idp certificate file
 * @param clientPrivateKeyFile path to client private key file
 * @param clientCertificateFile path to client certificate file
 * @return the HTTP client
 * @throws Exception if an error occurs
 */
@Nonnull
public static HttpClient buildHttpClient(@Nonnull final String idpCertificateFile,
        @Nonnull final String clientPrivateKeyFile, @Nonnull final String clientCertificateFile)
        throws Exception {

    X509Certificate idpCert = CertUtil.readCertificate(idpCertificateFile);
    KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null, null);
    trustStore.setCertificateEntry("idp", idpCert);

    PrivateKey clientPrivateKey = KeyPairUtil.readPrivateKey(clientPrivateKeyFile);
    X509Certificate clientCert = CertUtil.readCertificate(clientCertificateFile);
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setKeyEntry("me", clientPrivateKey, "secret".toCharArray(), new Certificate[] { clientCert });

    SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadTrustMaterial(trustStore);
    sslContextBuilder.loadKeyMaterial(keyStore, "secret".toCharArray());
    SSLContext sslcontext = sslContextBuilder.build();

    CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslcontext).build();

    return httpClient;
}

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/*  w ww .  j  a  v a2 s .  c o  m*/
 *
 * @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.apache.metron.dataloads.taxii.TaxiiHandler.java

private static HttpClient buildClient(URL proxy, String username, String password) throws Exception {
    HttpClient client = new HttpClient(); // Start with a default TAXII HTTP client.

    // Create an Apache HttpClientBuilder to be customized by the command line arguments.
    HttpClientBuilder builder = HttpClientBuilder.create().useSystemProperties();

    // Proxy/*from   w ww.j  a  va2s  . c  o m*/
    if (proxy != null) {
        HttpHost proxyHost = new HttpHost(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setProxy(proxyHost);
    }

    // Basic authentication. User & Password
    if (username != null ^ password != null) {
        throw new Exception("'username' and 'password' arguments are required to appear together.");
    }

    // from:  http://stackoverflow.com/questions/19517538/ignoring-ssl-certificate-in-apache-httpclient-4-3
    SSLContextBuilder ssbldr = new SSLContextBuilder();
    ssbldr.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(ssbldr.build(),
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

    Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", new PlainConnectionSocketFactory()).register("https", sslsf).build();

    PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
    cm.setMaxTotal(20);//max connection

    System.setProperty("jsse.enableSNIExtension", "false"); //""
    CloseableHttpClient httpClient = builder.setSSLSocketFactory(sslsf).setConnectionManager(cm).build();

    client.setHttpclient(httpClient);
    return client;
}