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

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

Introduction

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

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:org.fao.geonet.es.EsClient.java

@Override
public void afterPropertiesSet() throws Exception {
    if (StringUtils.isNotEmpty(serverUrl)) {
        JestClientFactory factory = new JestClientFactory();

        if (serverUrl.startsWith("https://")) {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }/*  w  w  w . j  a  v  a 2s  .c o  m*/
            }).build();
            // skip hostname checks
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;

            SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    hostnameVerifier);
            SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext,
                    hostnameVerifier);
            factory.setHttpClientConfig(
                    new HttpClientConfig.Builder(this.serverUrl).defaultCredentials(username, password)
                            .multiThreaded(true).sslSocketFactory(sslSocketFactory) // this only affects sync calls
                            .httpsIOSessionStrategy(httpsIOSessionStrategy) // this only affects async calls
                            .readTimeout(-1).build());
        } else {
            factory.setHttpClientConfig(
                    new HttpClientConfig.Builder(this.serverUrl).multiThreaded(true).readTimeout(-1).build());
        }
        client = factory.getObject();
        //            Depends on java.lang.NoSuchFieldError: LUCENE_5_2_1
        //            client = new PreBuiltTransportClient(Settings.EMPTY)
        //                .addTransportAddress(new InetSocketTransportAddress(
        //                    InetAddress.getByName("127.0.0.1"), 9300));

        synchronized (EsClient.class) {
            instance = this;
        }
        activated = true;
    } else {
        Log.debug("geonetwork.index",
                String.format(
                        "No Elasticsearch URL defined '%s'. "
                                + "Check bean configuration. Statistics and dasboard will not be available.",
                        this.serverUrl));
    }
}

From source file:org.finra.herd.dao.helper.HttpClientHelper.java

/**
 * Creates a new HTTP client./*from w ww. jav  a 2  s.co m*/
 *
 * @param trustSelfSignedCertificate specifies whether to trust a self-signed certificate
 * @param disableHostnameVerification specifies whether to turn off hostname verification
 *
 * @return the HTTP client
 * @throws KeyStoreException if a key store exception occurs
 * @throws NoSuchAlgorithmException if a no such algorithm exception occurs
 * @throws KeyManagementException if key management exception
 */
public CloseableHttpClient createHttpClient(Boolean trustSelfSignedCertificate,
        Boolean disableHostnameVerification)
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    // Create an HTTP client builder.
    HttpClientBuilder httpClientBuilder = HttpClients.custom();

    // Create an SSL context builder.
    SSLContextBuilder sslContextBuilder = SSLContexts.custom();

    // If specified, setup a trust strategy that allows all certificates.
    if (BooleanUtils.isTrue(trustSelfSignedCertificate)) {
        sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    }

    // If specified, turn hostname verification off.
    HostnameVerifier hostnameVerifier = BooleanUtils.isTrue(disableHostnameVerification)
            ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER
            : SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER;

    // Create and assign an SSL connection socket factory.
    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(
            sslContextBuilder.build(), hostnameVerifier);
    httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory);

    // Build and return an HTTP client.
    return httpClientBuilder.build();
}

From source file:org.finra.herd.dao.JestClientFactory.java

/**
 * Builds and returns a JEST client.//from  w w  w  . j a v  a  2  s  .  com
 *
 * @return the configured JEST client
 */
public JestClient getJestClient() {
    // Retrieve the configuration values used for setting up an Elasticsearch JEST client.
    final String esRegionName = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_AWS_REGION_NAME);
    final String hostname = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_HOSTNAME);
    final int port = configurationHelper.getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_PORT,
            Integer.class);
    final String scheme = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_DOMAIN_REST_CLIENT_SCHEME);
    final String serverUri = String.format("%s://%s:%d", scheme, hostname, port);
    final int connectionTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_CONNECTION_TIMEOUT, Integer.class);
    final int readTimeout = configurationHelper
            .getProperty(ConfigurationValue.ELASTICSEARCH_REST_CLIENT_READ_TIMEOUT, Integer.class);

    LOGGER.info("Elasticsearch REST Client Settings:  scheme={}, hostname={}, port={}, serverUri={}", scheme,
            hostname, port, serverUri);

    DefaultAWSCredentialsProviderChain awsCredentialsProvider = new DefaultAWSCredentialsProviderChain();
    final AWSSigner awsSigner = new AWSSigner(awsCredentialsProvider, esRegionName, "es",
            () -> LocalDateTime.now(ZoneOffset.UTC));

    final AWSSigningRequestInterceptor requestInterceptor = new AWSSigningRequestInterceptor(awsSigner);

    JestClientFactoryStaticInner jestClientFactory = new JestClientFactoryStaticInner(requestInterceptor);

    if (StringUtils.equalsIgnoreCase(scheme, "https")) {
        SSLConnectionSocketFactory sslSocketFactory;
        try {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContext.getDefault(),
                    NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }

        jestClientFactory.setHttpClientConfig(
                new HttpClientConfig.Builder(serverUri).connTimeout(connectionTimeout).readTimeout(readTimeout)
                        .sslSocketFactory(sslSocketFactory).multiThreaded(true).build());
    } else {
        jestClientFactory.setHttpClientConfig(new HttpClientConfig.Builder(serverUri)
                .connTimeout(connectionTimeout).readTimeout(readTimeout).multiThreaded(true).build());
    }

    return jestClientFactory.getObject();
}

From source file:org.flowable.app.service.editor.AppDefinitionPublishService.java

protected void deployZipArtifact(String artifactName, byte[] zipArtifact, String deploymentKey,
        String deploymentName) {/*from  w  ww  . ja  va 2s. c o  m*/
    String deployApiUrl = environment.getRequiredProperty("deployment.api.url");
    String basicAuthUser = environment.getRequiredProperty("idm.admin.user");
    String basicAuthPassword = environment.getRequiredProperty("idm.admin.password");

    if (deployApiUrl.endsWith("/") == false) {
        deployApiUrl = deployApiUrl.concat("/");
    }
    deployApiUrl = deployApiUrl
            .concat(String.format("repository/deployments?deploymentKey=%s&deploymentName=%s",
                    encode(deploymentKey), encode(deploymentName)));

    HttpPost httpPost = new HttpPost(deployApiUrl);
    httpPost.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + new String(
            Base64.encodeBase64((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();
    SSLConnectionSocketFactory sslsf = null;
    try {
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        clientBuilder.setSSLSocketFactory(sslsf);
    } 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: {}", response.getStatusLine());
            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.flowable.http.bpmn.impl.HttpActivityBehaviorImpl.java

public HttpActivityBehaviorImpl() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {/*  ww  w.j  a va2 s  .  c  om*/
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.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 HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new ProcessErrorPropagator());
}

From source file:org.flowable.http.cmmn.impl.CmmnHttpActivityBehaviorImpl.java

public CmmnHttpActivityBehaviorImpl() {
    org.flowable.cmmn.engine.HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration()
            .getHttpClientConfig();/*from  ww  w  .  j  av a2  s  .com*/
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.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 HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator());
}

From source file:org.flowable.http.impl.HttpActivityBehaviorImpl.java

public HttpActivityBehaviorImpl() {
    HttpClientConfig config = CommandContextUtil.getProcessEngineConfiguration().getHttpClientConfig();
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {/*  w  ww .  jav  a2s.  co m*/
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    // Build http client
    client = httpClientBuilder.build();
    LOGGER.info("HTTP client is initialized");

    // Shutdown hook to close the http client
    Runtime.getRuntime().addShutdownHook(new Thread() {
        @Override
        public void run() {
            if (client != null) {
                try {
                    client.close();
                    LOGGER.info("HTTP client is closed");
                } catch (Throwable e) {
                    LOGGER.error("Could not close http client", e);
                }
            }
        }
    });
}

From source file:org.flowable.ui.admin.service.engine.FlowableClientService.java

public CloseableHttpClient getHttpClient(String userName, String password) {

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));

    SSLConnectionSocketFactory sslsf = null;
    try {/*from   w w  w  .  ja v a 2 s .c om*/
        SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        sslsf = new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    } catch (Exception e) {
        LOGGER.warn("Could not configure HTTP client to use SSL", e);
    }

    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    if (preemptiveBasicAuthentication) {
        String auth = userName + ":" + password;
        httpClientBuilder.setDefaultHeaders(Collections.singletonList(new BasicHeader(AUTH.WWW_AUTH_RESP,
                "Basic " + Base64.getEncoder().encodeToString(auth.getBytes(StandardCharsets.UTF_8)))));
    }

    if (sslsf != null) {
        httpClientBuilder.setSSLSocketFactory(sslsf);
    }

    return httpClientBuilder.build();
}

From source file:org.jboss.as.test.integration.security.common.SSLTruststoreUtil.java

public static HttpClient getHttpClientWithSSL(File keyStoreFile, String keyStorePassword, File trustStoreFile,
        String trustStorePassword) {

    try {/*from  ww  w.  j  av  a 2s  .co  m*/
        final KeyStore truststore = loadKeyStore(trustStoreFile, trustStorePassword.toCharArray());
        final KeyStore keystore = keyStoreFile != null
                ? loadKeyStore(keyStoreFile, keyStorePassword.toCharArray())
                : null;
        SSLContextBuilder sslContextBuilder = SSLContexts.custom().useTLS().loadTrustMaterial(truststore);
        if (keyStoreFile != null) {
            sslContextBuilder.loadKeyMaterial(keystore, keyStorePassword.toCharArray());
        }
        SSLContext sslContext = sslContextBuilder.build();
        SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext,
                new AllowAllHostnameVerifier());

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

        return HttpClientBuilder.create().setSSLSocketFactory(socketFactory)
                .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)
                .setConnectionManager(new PoolingHttpClientConnectionManager(registry))
                .setSchemePortResolver(new DefaultSchemePortResolver()).build();

    } catch (Exception e) {
        LOGGER.error(
                "Creating HttpClient with customized SSL failed. We are returning the default one instead.", e);
        return HttpClients.createDefault();
    }
}

From source file:org.opennms.core.web.HttpClientWrapper.java

protected void configureSSLContext(final HttpClientBuilder builder) {
    final RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
            .<ConnectionSocketFactory>create();
    for (final Map.Entry<String, SSLContext> entry : m_sslContext.entrySet()) {
        final SSLConnectionSocketFactory sslConnectionFactory = new SSLConnectionSocketFactory(entry.getValue(),
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registryBuilder.register(entry.getKey(), sslConnectionFactory);
    }//from  w w w . ja  v a  2s. co m
    if (!m_sslContext.containsKey("http")) {
        registryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE);
    }
    if (!m_sslContext.containsKey("https")) {
        registryBuilder.register("https", SSLConnectionSocketFactory.getSystemSocketFactory());
    }

    final HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registryBuilder.build());
    builder.setConnectionManager(ccm);
}