Example usage for org.apache.http.impl.client HttpClientBuilder setHostnameVerifier

List of usage examples for org.apache.http.impl.client HttpClientBuilder setHostnameVerifier

Introduction

In this page you can find the example usage for org.apache.http.impl.client HttpClientBuilder setHostnameVerifier.

Prototype

public final HttpClientBuilder setHostnameVerifier(final X509HostnameVerifier hostnameVerifier) 

Source Link

Document

Assigns X509HostnameVerifier instance.

Usage

From source file:org.eclipse.cft.server.core.internal.client.RestUtils.java

public static ClientHttpRequestFactory createRequestFactory(HttpProxyConfiguration httpProxyConfiguration,
        boolean trustSelfSignedCerts, boolean disableRedirectHandling) {
    HttpClientBuilder httpClientBuilder = HttpClients.custom().useSystemProperties();

    if (trustSelfSignedCerts) {
        httpClientBuilder.setSslcontext(buildSslContext());
        httpClientBuilder.setHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    }//from   ww w . j a v a2 s  . c  om

    if (disableRedirectHandling) {
        httpClientBuilder.disableRedirectHandling();
    }

    if (httpProxyConfiguration != null) {
        HttpHost proxy = new HttpHost(httpProxyConfiguration.getProxyHost(),
                httpProxyConfiguration.getProxyPort());
        httpClientBuilder.setProxy(proxy);

        if (httpProxyConfiguration.isAuthRequired()) {
            BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(
                    new AuthScope(httpProxyConfiguration.getProxyHost(), httpProxyConfiguration.getProxyPort()),
                    new UsernamePasswordCredentials(httpProxyConfiguration.getUsername(),
                            httpProxyConfiguration.getPassword()));
            httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }

        HttpRoutePlanner routePlanner = new DefaultProxyRoutePlanner(proxy);
        httpClientBuilder.setRoutePlanner(routePlanner);
    }

    HttpClient httpClient = httpClientBuilder.build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
            httpClient);

    return requestFactory;
}

From source file:photosharing.api.ExecutorUtil.java

/**
 * helper method that returns an HTTPClient executor with credentials
 * available./*from   w  w  w  .  j av  a 2 s  .  com*/
 * 
 * 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:org.metaeffekt.dcc.shell.RemoteAgentTest.java

private HttpClient newHttpClient() throws GeneralSecurityException, IOException {
    final char[] password = "DYKK8T8m9nKqBRPZ".toCharArray();

    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(getClass().getResourceAsStream("/dcc-shell.keystore"), password);

    final KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(getClass().getResourceAsStream("/dcc-shell.truststore"), password);

    final SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadKeyMaterial(keyStore, password);
    sslContextBuilder.loadTrustMaterial(trustStore);

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(sslContextBuilder.build());
    builder.setHostnameVerifier(new AllowAllHostnameVerifier());

    final HttpClient client = builder.build();
    return client;
}

From source file:org.metaeffekt.dcc.agent.DccAgentTest.java

private HttpClient newHttpClient() throws GeneralSecurityException, IOException {
    final char[] password = "changeit".toCharArray();

    final KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(DccAgentTest.class.getResourceAsStream("/client.keystore"), password);

    final KeyStore trustStore = KeyStore.getInstance("JKS");
    trustStore.load(DccAgentTest.class.getResourceAsStream("/client.truststore"), password);

    final SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadKeyMaterial(keyStore, password);
    sslContextBuilder.loadTrustMaterial(trustStore);

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(sslContextBuilder.build());
    builder.setHostnameVerifier(new AllowAllHostnameVerifier());

    final HttpClient client = builder.build();
    return client;
}

From source file:org.metaeffekt.dcc.controller.execution.RemoteExecutor.java

private CloseableHttpClient instantiateHttpClientWithTimeout() throws IOException, GeneralSecurityException {
    final KeyStore keyStore = loadKeyStore(sslConfiguration.getKeyStoreLocation(),
            sslConfiguration.getKeyStorePassword());

    final KeyStore trustStore = loadKeyStore(sslConfiguration.getTrustStoreLocation(),
            sslConfiguration.getTrustStorePassword());

    final SSLContextBuilder sslContextBuilder = SSLContexts.custom();
    sslContextBuilder.loadKeyMaterial(keyStore, sslConfiguration.getKeyStorePassword());
    sslContextBuilder.loadTrustMaterial(trustStore);

    final HttpClientBuilder builder = HttpClientBuilder.create();
    builder.setSslcontext(sslContextBuilder.build());
    builder.setHostnameVerifier(new AllowAllHostnameVerifier());

    final CloseableHttpClient client = builder.build();
    return client;
}

From source file:com.adobe.acs.commons.http.impl.HttpClientFactoryImpl.java

@Activate
protected void activate(Map<String, Object> config) throws Exception {
    boolean useSSL = PropertiesUtil.toBoolean(config.get(PROP_USE_SSL), DEFAULT_USE_SSL);

    String scheme = useSSL ? "https" : "http";
    String hostname = PropertiesUtil.toString(config.get(PROP_HOST_DOMAIN), null);
    int port = PropertiesUtil.toInteger(config.get(PROP_GATEWAY_PORT), 0);

    if (hostname == null || port == 0) {
        throw new IllegalArgumentException("Configuration not valid. Both host and port must be provided.");
    }/* w  w  w.ja v  a  2  s . co  m*/

    baseUrl = String.format("%s://%s:%s", scheme, hostname, port);

    int connectTimeout = PropertiesUtil.toInteger(config.get(PROP_CONNECT_TIMEOUT), DEFAULT_CONNECT_TIMEOUT);
    int soTimeout = PropertiesUtil.toInteger(config.get(PROP_SO_TIMEOUT), DEFAULT_SOCKET_TIMEOUT);

    HttpClientBuilder builder = httpClientBuilderFactory.newBuilder();

    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout)
            .setSocketTimeout(soTimeout).build();
    builder.setDefaultRequestConfig(requestConfig);

    boolean disableCertCheck = PropertiesUtil.toBoolean(config.get(PROP_DISABLE_CERT_CHECK),
            DEFAULT_DISABLE_CERT_CHECK);

    if (useSSL && disableCertCheck) {
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
        builder.setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext(sslContext);
    }
    httpClient = builder.build();
    executor = Executor.newInstance(httpClient);

    String username = PropertiesUtil.toString(config.get(PROP_USERNAME), null);
    String password = PropertiesUtil.toString(config.get(PROP_PASSWORD), null);
    if (username != null && password != null) {
        HttpHost httpHost = new HttpHost(hostname, port, useSSL ? "https" : "http");
        executor.auth(httpHost, username, password).authPreemptive(httpHost);
    }
}

From source file:org.ow2.proactive.http.CommonHttpClientBuilder.java

public CloseableHttpClient build() {
    org.apache.http.impl.client.HttpClientBuilder internalHttpClientBuilder = createInternalHttpClientBuilder();

    if (useSystemProperties) {
        internalHttpClientBuilder.useSystemProperties();
    }/*from  w  ww.  j a  va2  s .com*/

    if (overrideAllowAnyHostname != null) {
        if (overrideAllowAnyHostname) {
            acceptAnyHostname = true;
        } else {
            acceptAnyHostname = false;
        }
    }

    if (overrideAllowAnyCertificate != null) {
        if (overrideAllowAnyCertificate) {
            acceptAnyCertificate = true;
        } else {
            acceptAnyCertificate = false;
        }
    }

    if (acceptAnyCertificate) {
        internalHttpClientBuilder.setSslcontext(createSslContext());
    }

    if (acceptAnyHostname) {
        internalHttpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }

    if (maxConnections > 0) {
        internalHttpClientBuilder.setMaxConnPerRoute(maxConnections);
        internalHttpClientBuilder.setMaxConnTotal(maxConnections);
    }

    if (requestConfig != null) {
        internalHttpClientBuilder.setDefaultRequestConfig(requestConfig);
    }

    if (!useContentCompression) {
        internalHttpClientBuilder.disableContentCompression();
    }

    return internalHttpClientBuilder.build();
}

From source file:org.rundeck.api.ApiCall.java

/**
 * Instantiate a new {@link HttpClient} instance, configured to accept all SSL certificates
 *
 * @return an {@link HttpClient} instance - won't be null
 *//*www  .  j a  v a2s.  c om*/
private CloseableHttpClient instantiateHttpClient() {
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().useSystemProperties();

    // configure user-agent
    httpClientBuilder.setUserAgent("Rundeck API Java Client " + client.getApiVersion());

    if (client.isSslHostnameVerifyAllowAll()) {
        httpClientBuilder.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    if (client.isSslCertificateTrustAllowSelfSigned()) {
        // configure SSL
        try {
            httpClientBuilder.setSslcontext(
                    new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build());
        } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }

    }
    if (client.isSystemProxyEnabled()) {
        // configure proxy (use system env : http.proxyHost / http.proxyPort)
        httpClientBuilder.setRoutePlanner(new SystemDefaultRoutePlanner(ProxySelector.getDefault()));
    }
    // in case of token-based authentication, add the correct HTTP header to all requests via an interceptor
    httpClientBuilder.addInterceptorFirst(new HttpRequestInterceptor() {

        @Override
        public void process(HttpRequest request, HttpContext context) throws HttpException, IOException {
            if (client.getToken() != null) {
                request.addHeader(AUTH_TOKEN_HEADER, client.getToken());
                //System.out.println("httpClient adding token header");
            } else if (client.getSessionID() != null) {
                request.addHeader(COOKIE_HEADER, "JSESSIONID=" + client.getSessionID());
                //System.out.println("httpClient adding session header, sessionID="+client.getSessionID());
            }
        }
    });

    return httpClientBuilder.build();
}