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

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

Introduction

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

Prototype

public SSLContextBuilder loadTrustMaterial(final URL url, final char[] storePassword)
            throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException 

Source Link

Usage

From source file:org.hawkular.client.core.jaxrs.RestFactory.java

private HttpClient getHttpClient() {
    CloseableHttpClient httpclient = null;

    try {/*  w  w  w.  j  av a  2s  .c  o m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(keyStore, (TrustStrategy) (trustedCert, nameConstraints) -> true);

        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        _logger.error("Failed to create HTTPClient: {}", e);
    }

    return httpclient;
}

From source file:org.syslog_ng.elasticsearch_v2.client.http.ESHttpsClient.java

private void loadTrustMaterial(SSLContextBuilder sslContextBuilder, KeyStore trustStore) {
    try {//from  w ww  . j  a  v a 2  s .c o m
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    } catch (NoSuchAlgorithmException | KeyStoreException e) {
        throw new ESHttpClient.HttpClientBuilderException("Error loading truststore material", e);
    }
}

From source file:com.zextras.zimbradrive.CreateTempAttachmentFileHttpHandler.java

private void doInternalPost(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    Account account = mBackendUtils.assertAccountFromAuthToken(httpServletRequest);
    ZimbraLog.addAccountNameToContext(account.getName());
    String path;//from   w ww . ja  v  a2s.co  m
    BufferedReader reader = httpServletRequest.getReader();
    while ((path = reader.readLine()) != null) {
        HttpResponse fileRequestResponse = mCloudHttpRequestUtils.queryCloudServerService(account, path);

        int responseCode = fileRequestResponse.getStatusLine().getStatusCode();
        if (responseCode < HTTP_LOWEST_ERROR_STATUS) {
            HttpPost post = new HttpPost(mBackendUtils.getServerServiceUrl("/service/upload?fmt=extended,raw"));
            post.setHeader(CONTENT_DISPOSITION_HTTP_HEADER, "attachment; filename=\" "
                    + convertToUnicode(path.substring(path.lastIndexOf("/") + 1)) + " \"");
            post.setHeader("Cache-Control", "no-cache");
            post.setHeader("Cookie", httpServletRequest.getHeader("Cookie"));
            post.setHeader("X-Zimbra-Csrf-Token", httpServletRequest.getHeader("X-Zimbra-Csrf-Token"));
            post.setEntity(fileRequestResponse.getEntity());

            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustStrategy() {
                @Override
                public boolean isTrusted(X509Certificate[] x509Certificates, String s)
                        throws CertificateException {
                    return true;
                }
            });
            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());
            CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

            HttpResponse response = client.execute(post);

            response.getEntity().writeTo(httpServletResponse.getOutputStream());
        } else {
            httpServletResponse.setStatus(responseCode);
            PrintWriter respWriter = httpServletResponse.getWriter();
            respWriter.println("Error");
            respWriter.close();
            break;
        }
    }
}

From source file:org.wso2.carbon.buzzword.tag.cloud.sample.BuzzwordDAO.java

private HttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    // create a post request to addAPI.
    HttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    return httpclient;
}

From source file:org.wso2.carbon.customer_portal.tag.cloud.sample.CustomerService.java

private HttpClient getHttpClient() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = new SSLContextBuilder();
    builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());

    // create a post request to addAPI.
    return HttpClients.custom().setSSLSocketFactory(sslsf).build();
}

From source file:org.thingsboard.server.msa.AbstractContainerTest.java

protected WsClient subscribeToWebSocket(DeviceId deviceId, String scope, CmdsType property) throws Exception {
    WsClient wsClient = new WsClient(
            new URI(WSS_URL + "/api/ws/plugins/telemetry?token=" + restClient.getToken()));
    SSLContextBuilder builder = SSLContexts.custom();
    builder.loadTrustMaterial(null, (TrustStrategy) (chain, authType) -> true);
    wsClient.setSocket(builder.build().getSocketFactory().createSocket());
    wsClient.connectBlocking();/*from w  w w .j  a  v a 2 s  .  c  o  m*/

    JsonObject cmdsObject = new JsonObject();
    cmdsObject.addProperty("entityType", EntityType.DEVICE.name());
    cmdsObject.addProperty("entityId", deviceId.toString());
    cmdsObject.addProperty("scope", scope);
    cmdsObject.addProperty("cmdId", new Random().nextInt(100));

    JsonArray cmd = new JsonArray();
    cmd.add(cmdsObject);
    JsonObject wsRequest = new JsonObject();
    wsRequest.add(property.toString(), cmd);
    wsClient.send(wsRequest.toString());
    wsClient.waitForFirstReply();
    return wsClient;
}

From source file:org.hawkular.client.RestFactory.java

public HttpClient getHttpClient() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {/*from  ww w .  j a v a 2s.c o m*/
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        builder.loadTrustMaterial(keyStore, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] trustedCert, String nameConstraints)
                    throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
        CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpclient;

    } catch (Exception ex) {
        _logger.error("Exception, ", ex);
        return null;
    }
}

From source file:org.flowable.ui.modeler.service.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {//from   w  ww.  j a  v  a 2  s.c o  m
    String deployApiUrl = modelerAppProperties.getDeploymentApiUrl();
    Assert.hasText(deployApiUrl, "flowable.modeler.app.deployment-api-url must be set");
    String basicAuthUser = properties.getIdmAdmin().getUser();
    String basicAuthPassword = properties.getIdmAdmin().getPassword();

    String tenantId = tenantProvider.getTenantId();
    if (!deployApiUrl.endsWith("/")) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("app-repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    if (tenantId != null) {
        StringBuilder sb = new StringBuilder(deployApiUrl);
        sb.append("&tenantId=").append(encode(tenantId));
        deployApiUrl = sb.toString();
    }

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(Base64.getEncoder()
            .encode((basicAuthUser + ":" + basicAuthPassword).getBytes(Charset.forName("UTF-8")))));

    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    entityBuilder.addBinaryBody("artifact", zipArtifact, ContentType.DEFAULT_BINARY, artifactName);

    HttpEntity entity = entityBuilder.build();
    httpPost.setEntity(entity);

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        clientBuilder
                .setSSLSocketFactory(new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }));

    } catch (Exception e) {
        LOGGER.error("Could not configure SSL for http client", e);
        throw new InternalServerErrorException("Could not configure SSL for http client", e);
    }

    CloseableHttpClient client = clientBuilder.build();

    try {
        HttpResponse response = client.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            return;
        } else {
            LOGGER.error("Invalid deploy result code: {} for url",
                    response.getStatusLine() + httpPost.getURI().toString());
            throw new InternalServerErrorException("Invalid deploy result code: " + response.getStatusLine());
        }

    } catch (IOException ioe) {
        LOGGER.error("Error calling deploy endpoint", ioe);
        throw new InternalServerErrorException("Error calling deploy endpoint: " + ioe.getMessage());
    } finally {
        if (client != null) {
            try {
                client.close();
            } catch (IOException e) {
                LOGGER.warn("Exception while closing http client", e);
            }
        }
    }
}

From source file:com.thoughtworks.go.agent.common.ssl.GoAgentServerHttpClientBuilder.java

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();//from   w  w  w  . ja v a  2 s .c  o m
    builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build())
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);

    HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
    TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
    KeyStore trustStore = agentTruststore();

    SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(
            systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));

    if (trustStore != null || trustStrategy != null) {
        sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
    }

    sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    builder.setSSLSocketFactory(sslConnectionSocketFactory);
    return builder.build();
}

From source file:ph.com.globe.connect.HttpRequest.java

/**
 * Sends get request to the specified url.
 * //from  w  w  w.  j  a v a 2s.  c o  m
 * @return CloseableHttpResponse
 * @throws HttpRequestException http request exception
 */
public CloseableHttpResponse sendGet() throws HttpRequestException {

    // try building up
    try {
        // initialize ssl context builder
        SSLContextBuilder builder = new SSLContextBuilder();

        // set trust self signed strategy
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());

        // initialize ssl socket connection factory
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build());

        // default http client
        CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();

        // create request method
        HttpGet request = new HttpGet(this.url);

        // set default header
        request.setHeader("User-Agent", this.USER_AGENT);

        // try request
        try {
            // execute request and get response
            CloseableHttpResponse response = client.execute(request);

            return response;
        } catch (IOException e) {
            throw new HttpRequestException(e.getMessage());
        }
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new HttpRequestException(e.getMessage());
    }
}