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

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

Introduction

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

Prototype

public SSLContext build() throws NoSuchAlgorithmException, KeyManagementException 

Source Link

Usage

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

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {//ww w. j av  a  2  s  . co  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:org.elasticsearch.client.documentation.RestClientDocumentation.java

@SuppressWarnings("unused")
public void testCommonConfiguration() throws Exception {
    {/*from   w  ww  .j a  v  a  2s .c o m*/
        //tag::rest-client-config-timeouts
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200))
                .setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
                    @Override
                    public RequestConfig.Builder customizeRequestConfig(
                            RequestConfig.Builder requestConfigBuilder) {
                        return requestConfigBuilder.setConnectTimeout(5000).setSocketTimeout(60000);
                    }
                }).setMaxRetryTimeoutMillis(60000);
        //end::rest-client-config-timeouts
    }
    {
        //tag::rest-client-config-threads
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(
                            HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultIOReactorConfig(
                                IOReactorConfig.custom().setIoThreadCount(1).build());
                    }
                });
        //end::rest-client-config-threads
    }
    {
        //tag::rest-client-config-basic-auth
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password"));

        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(
                            HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
        //end::rest-client-config-basic-auth
    }
    {
        //tag::rest-client-config-disable-preemptive-auth
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("user", "password"));

        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(
                            HttpAsyncClientBuilder httpClientBuilder) {
                        httpClientBuilder.disableAuthCaching(); // <1>
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });
        //end::rest-client-config-disable-preemptive-auth
    }
    {
        Path keyStorePath = Paths.get("");
        String keyStorePass = "";
        //tag::rest-client-config-encrypted-communication
        KeyStore truststore = KeyStore.getInstance("jks");
        try (InputStream is = Files.newInputStream(keyStorePath)) {
            truststore.load(is, keyStorePass.toCharArray());
        }
        SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null);
        final SSLContext sslContext = sslBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(
                            HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext);
                    }
                });
        //end::rest-client-config-encrypted-communication
    }
}

From source file:org.jodconverter.office.OnlineOfficeManagerPoolEntry.java

private SSLConnectionSocketFactory configureSsl() throws OfficeException {

    if (sslConfig == null || !sslConfig.isEnabled()) {
        return null;
    }//w ww  . j  ava 2s .  c  o  m

    try {
        final SSLContextBuilder sslBuilder = SSLContexts.custom();
        sslBuilder.setProtocol(sslConfig.getProtocol());
        configureKeyMaterial(sslBuilder);
        configureTrustMaterial(sslBuilder);

        final SSLContext sslcontext = sslBuilder.build();

        return new SSLConnectionSocketFactory(sslcontext, sslConfig.getEnabledProtocols(),
                sslConfig.getCiphers(),
                sslConfig.isVerifyHostname() ? SSLConnectionSocketFactory.getDefaultHostnameVerifier()
                        : NoopHostnameVerifier.INSTANCE);

    } catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException
            | CertificateException | UnrecoverableKeyException | NoSuchProviderException ex) {
        throw new OfficeException("Unable to create SSL context.", ex);
    }
}

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

/**
 * Sends get request to the specified url.
 * /*from  w  w w .  ja v a  2  s .co  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());
    }
}

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

/**
 * Send post request to the specified url.
 * /*from ww w  .  j  a  va 2  s  .c o  m*/
 * @return CloseableHttpResponse
 * @throws HttpRequestException http request exception
 */
public CloseableHttpResponse sendPost() 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
        HttpPost post = new HttpPost(this.url);

        // set default user agent
        post.setHeader("User-Agent", this.USER_AGENT);
        // set default content type
        post.setHeader("Content-Type", this.CONTENT_TYPE);

        // convert data to json string
        JSONObject data = new JSONObject(this.data);

        try {
            // set the string entity
            StringEntity entity = new StringEntity(data.toString());

            // set post data
            post.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            // throw exception
            throw new HttpRequestException(e.getMessage());
        }

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

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

From source file:org.drugis.addis.config.MainConfig.java

@Bean
public HttpClient httpClient(RequestConfig requestConfig) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(KEYSTORE_PATH), KEYSTORE_PASSWORD.toCharArray());
    String ADDIS_LOCAL = System.getenv("ADDIS_LOCAL");

    SSLContextBuilder sslContextBuilder = SSLContexts.custom().loadKeyMaterial(keyStore,
            KEYSTORE_PASSWORD.toCharArray());
    if (ADDIS_LOCAL != null) {
        String TRUSTSTORE_PATH = WebConstants.loadSystemEnv("TRUSTSTORE_PATH");
        sslContextBuilder.loadTrustMaterial(new File(TRUSTSTORE_PATH));
    }/*from w ww . j a  v  a2  s. c o  m*/
    sslContextBuilder.build();
    SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build());

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

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    return httpClientBuilder.setConnectionManager(clientConnectionManager).setMaxConnTotal(20)
            .setMaxConnPerRoute(2).setDefaultRequestConfig(requestConfig).build();
}

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

public CloseableHttpClient build() throws Exception {
    HttpClientBuilder builder = HttpClients.custom();
    builder.useSystemProperties();//from ww  w  .ja v  a2s . 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:com.intuit.tank.httpclient4.TankHttpClient4.java

/**
 * no-arg constructor for client// www .j a  va 2  s.  c o  m
 */
public TankHttpClient4() {
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) {
        LOG.error("Error setting accept all: " + e, e);
    }

    httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
    requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000)
            .setCircularRedirectsAllowed(true).setAuthenticationEnabled(true).setRedirectsEnabled(true)
            .setMaxRedirects(100).build();

    // Make sure the same context is used to execute logically related
    // requests
    context = HttpClientContext.create();
    context.setCredentialsProvider(new BasicCredentialsProvider());
    context.setCookieStore(new BasicCookieStore());
    context.setRequestConfig(requestConfig);
}

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;//  ww w  .  ja  va  2s  . c o  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.hawkular.client.RestFactory.java

public HttpClient getHttpClient() {
    SSLContextBuilder builder = new SSLContextBuilder();
    try {/*from   w w w .j  a  v a2 s. co  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;
    }
}