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

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

Introduction

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

Prototype

NoopHostnameVerifier

Source Link

Usage

From source file:org.springframework.cloud.dataflow.server.service.impl.validation.DefaultAppValidationServiceTests.java

private static boolean dockerCheck() {
    boolean result = true;
    try {/*  w  ww  . j a  v a  2s.c o m*/
        CloseableHttpClient httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier())
                .build();
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setHttpClient(httpClient);
        requestFactory.setConnectTimeout(10000);
        requestFactory.setReadTimeout(10000);

        RestTemplate restTemplate = new RestTemplate(requestFactory);
        System.out.println("Testing access to " + DockerValidatorProperties.DOCKER_REGISTRY_URL
                + "springcloudstream/log-sink-rabbit/tags");
        restTemplate.getForObject(
                DockerValidatorProperties.DOCKER_REGISTRY_URL + "/springcloudstream/log-sink-rabbit/tags",
                String.class);
    } catch (Exception ex) {
        System.out.println("dockerCheck() failed. " + ex.getMessage());
        result = false;
    }
    return result;
}

From source file:com.spectralogic.ds3client.networking.NetworkClientImpl.java

private static CloseableHttpClient createInsecureSslHttpClient()
        throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
    final SSLContext sslContext = new SSLContextBuilder().useProtocol(INSECURE_SSL_PROTOCOL)
            .loadTrustMaterial(null, new TrustStrategy() {
                @Override//from   w  w w.  j  ava 2  s.c  o m
                public boolean isTrusted(final X509Certificate[] chain, final String authType)
                        throws CertificateException {
                    return true;
                }
            }).build();
    final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            new NoopHostnameVerifier());

    final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
            .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslsf).build();
    final HttpClientConnectionManager connectionManager = createConnectionManager(socketFactoryRegistry);

    return HttpClients.custom().setConnectionManager(connectionManager).setSSLSocketFactory(sslsf).build();
}

From source file:org.opentravel.otm.forum2016.am.APIOperationFactory.java

/**
 * Returns a new HTTP client instance for use with API Manager REST API invocations.
 * //  www .java  2s .c o m
 * @return CloseableHttpClient
 * @throws IOException  thrown if an error occurs while constructing the HTTP client
 */
public static CloseableHttpClient newHttpClient() throws IOException {
    try {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .build();
        SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());

        return HttpClientBuilder.create().useSystemProperties().setSSLSocketFactory(connectionFactory).build();

    } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new IOException("Error constructing SSL context for HTTP client.", e);
    }

}

From source file:org.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java

@Bean(name = "sharedSecureHttpClient")
public CloseableHttpClient secureHttpClient() {
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    try {//from  ww w . j  a v  a 2 s .co  m
        /*
        TODO: Modify to accept only specific certificates, test implementation is as below,
        TODO: need to find a way of determining if server url is https or not
        TODO: Whether we have imported the certificate or not
        */
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        Resource resource = loaderService.getResource(properties.getSharedKeystorePath());
        keyStore.load(resource.getInputStream(),
                hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray());
        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy())
                .loadKeyMaterial(keyStore,
                        hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray())
                .build();
        //            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();

        RequestConfig config = RequestConfig.custom()
                .setConnectTimeout(properties.getSharedTransportConnectionTimeout())
                .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout())
                .setSocketTimeout(properties.getSharedTransportReadTimeout()).build();
        CredentialsProvider provider = new BasicCredentialsProvider();
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(
                sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword());
        provider.setCredentials(AuthScope.ANY, credentials);

        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
        connManager.setMaxTotal(properties.getSharedPoolMaxHost());
        connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost());
        connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity());
        httpClient = HttpClientBuilder.create().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config)
                .setDefaultCredentialsProvider(provider).setConnectionManager(connManager)
                .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build();
    } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException
            | IOException | UnrecoverableKeyException e) {
        Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e);
    }
    return httpClient;

}

From source file:org.jboss.tools.jmx.jolokia.JolokiaConnectionWrapper.java

protected J4pClient createJ4pClient() {
    CustomClientBuilder jb = new CustomClientBuilder() {
        @Override/*from  w w w .  ja  va2s .  co  m*/
        public void clientBuilderAdditions(HttpClientBuilder builder) {
            Set<Header> defaultHeaders = headers.entrySet().stream()
                    .map(entry -> new BasicHeader(entry.getKey(), entry.getValue()))
                    .collect(Collectors.toSet());
            builder.setDefaultHeaders(defaultHeaders);
        }

        @Override
        protected SSLConnectionSocketFactory createDefaultSSLConnectionSocketFactory() {
            if (ignoreSSLErrors) {
                try {
                    final SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, new TrustManager[] { new AcceptAllTrustManager() }, null);
                    return new JolokiaSSLConnectionSocketFactory(sslcontext, new NoopHostnameVerifier());
                } catch (NoSuchAlgorithmException e1) {
                    Activator.pluginLog().logWarning(e1);
                } catch (KeyManagementException e) {
                    Activator.pluginLog().logWarning(e);
                }
            }
            SSLContext sslcontext = SSLContexts.createSystemDefault();
            X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();
            return new SSLConnectionSocketFactory(sslcontext, hostnameVerifier);
        }
    };
    jb.url(url);
    return jb.build();
}

From source file:org.apache.geode.rest.internal.web.GeodeRestClient.java

public HttpResponse doRequest(HttpRequestBase request, String username, String password) throws Exception {
    HttpHost targetHost = new HttpHost(bindAddress, restPort, protocol);

    HttpClientBuilder clientBuilder = HttpClients.custom();
    HttpClientContext clientContext = HttpClientContext.create();

    // configures the clientBuilder and clientContext
    if (username != null) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials(username, password));
        clientBuilder.setDefaultCredentialsProvider(credsProvider);
    }/*from   w  w w .j a  v a2 s  .  c om*/

    if (useHttps) {
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom());
        clientBuilder.setSSLContext(ctx);
        clientBuilder.setSSLHostnameVerifier(new NoopHostnameVerifier());
    }

    return clientBuilder.build().execute(targetHost, request, clientContext);
}

From source file:io.wcm.maven.plugins.contentpackage.AbstractContentPackageMojo.java

/**
 * Set up http client with credentials/*  w  ww . j  av a2 s  .c  om*/
 * @return Http client
 * @throws MojoExecutionException Mojo execution exception
 */
protected final CloseableHttpClient getHttpClient() throws MojoExecutionException {
    try {
        URI crxUri = new URI(getCrxPackageManagerUrl());

        final AuthScope authScope = new AuthScope(crxUri.getHost(), crxUri.getPort());
        final Credentials credentials = new UsernamePasswordCredentials(this.userId, this.password);
        final CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(authScope, credentials);

        HttpClientBuilder httpClientBuilder = HttpClients.custom().setDefaultCredentialsProvider(credsProvider)
                .addInterceptorFirst(new HttpRequestInterceptor() {
                    @Override
                    public void process(HttpRequest request, HttpContext context)
                            throws HttpException, IOException {
                        // enable preemptive authentication
                        AuthState authState = (AuthState) context
                                .getAttribute(HttpClientContext.TARGET_AUTH_STATE);
                        authState.update(new BasicScheme(), credentials);
                    }
                });

        if (this.relaxedSSLCheck) {
            SSLContext sslContext = new SSLContextBuilder()
                    .loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                    new NoopHostnameVerifier());
            httpClientBuilder.setSSLSocketFactory(sslsf);
        }

        return httpClientBuilder.build();
    } catch (URISyntaxException ex) {
        throw new MojoExecutionException("Invalid url: " + getCrxPackageManagerUrl(), ex);
    } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex) {
        throw new MojoExecutionException("Could not set relaxedSSLCheck", ex);
    }
}

From source file:portal.api.osm.client.OSMClient.java

private CloseableHttpClient returnHttpClient() {
    try {//  w  w w.  j a v  a 2 s.c  o  m
        HttpClientBuilder h = HttpClientBuilder.create();

        SSLContext sslContext;
        sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build();
        CloseableHttpClient httpclient = HttpClients.custom().setSSLContext(sslContext)
                .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();

        return httpclient;
    } catch (KeyManagementException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (KeyStoreException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:com.vsct.dt.hesperides.feedback.FeedbacksAggregate.java

private CloseableHttpClient getHttpClient() {

    CloseableHttpClient httpClient;/* ww  w  .ja v a 2 s . c o m*/

    try {

        SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true)
                .build();

        if (!this.proxyConfiguration.getProxyUrl().isEmpty()) {
            String proxyUrl = this.proxyConfiguration.getProxyUrl().split(":")[0];
            Integer proxyPort = Integer.valueOf(this.proxyConfiguration.getProxyUrl().split(":")[1]);

            HttpHost proxy = new HttpHost(proxyUrl, proxyPort);

            LOGGER.debug("Access with proxy : " + proxyUrl + ":" + proxyPort);
            httpClient = HttpClients.custom().setSSLContext(sslContext)
                    .setSSLHostnameVerifier(new NoopHostnameVerifier()).setProxy(proxy).build();
        } else {
            LOGGER.debug("Access without proxy");
            httpClient = HttpClients.custom().setSSLContext(sslContext)
                    .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        }

    } catch (KeyManagementException e) {
        throw new RuntimeException("KeyManagementException :" + e.toString());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("NoSuchAlgorithmException :" + e.toString());
    } catch (KeyStoreException e) {
        throw new RuntimeException("KeyStoreException :" + e.toString());
    }
    return httpClient;
}

From source file:org.glowroot.central.SyntheticMonitorService.java

SyntheticMonitorService(ActiveAgentDao activeAgentDao, ConfigRepositoryImpl configRepository,
        AlertingDisabledDao alertingDisabledDao, IncidentDao incidentDao, AlertingService alertingService,
        SyntheticResultDao syntheticResponseDao, ClusterManager clusterManager, Ticker ticker, Clock clock,
        String version) throws Exception {
    this.activeAgentDao = activeAgentDao;
    this.configRepository = configRepository;
    this.alertingDisabledDao = alertingDisabledDao;
    this.incidentDao = incidentDao;
    this.alertingService = alertingService;
    this.syntheticResponseDao = syntheticResponseDao;
    this.ticker = ticker;
    this.clock = clock;
    executionRateLimiter = clusterManager.createReplicatedMap("syntheticMonitorExecutionRateLimiter", 30,
            SECONDS);/*from w  w  w.  ja  va  2 s. c o  m*/
    if (version.equals(Version.UNKNOWN_VERSION)) {
        shortVersion = "";
    } else {
        int index = version.indexOf(", built ");
        if (index == -1) {
            shortVersion = "/" + version;
        } else {
            shortVersion = "/" + version.substring(0, index);
        }
    }
    // asyncHttpClient is only used for pings, so safe to ignore cert errors
    asyncHttpClient = HttpAsyncClients.custom().setUserAgent("GlowrootCentral" + shortVersion)
            .setDefaultHeaders(Arrays.asList(new BasicHeader("Glowroot-Transaction-Type", "Synthetic")))
            .setMaxConnPerRoute(10) // increasing from default 2
            .setMaxConnTotal(1000) // increasing from default 20
            .setSSLContext(SSLContextBuilder.create().loadTrustMaterial(new TrustSelfSignedStrategy()).build())
            .setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
    asyncHttpClient.start();
    syncHttpClientHolder = createSyncHttpClientHolder(shortVersion, configRepository.getHttpProxyConfig());
    // these parameters are from com.machinepublishers.jbrowserdriver.UserAgent.CHROME
    // with added GlowrootCentral/<version> for identification purposes
    userAgent = new UserAgent(Family.WEBKIT, "Google Inc.", "Win32", "Windows NT 6.1",
            "5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                    + " Chrome/45.0.2454.85 Safari/537.36 GlowrootCentral" + shortVersion,
            "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"
                    + " Chrome/45.0.2454.85 Safari/537.36 GlowrootCentral" + shortVersion);
    // there is one subworker per worker, so using same max
    subWorkerExecutor = MoreExecutors
            .listeningDecorator(MoreExecutors2.newCachedThreadPool("Synthetic-Monitor-Sub-Worker-%d"));
    workerExecutor = MoreExecutors2.newCachedThreadPool("Synthetic-Monitor-Worker-%d");
    mainLoopExecutor = MoreExecutors2.newSingleThreadExecutor("Synthetic-Monitor-Main-Loop");
    mainLoopExecutor.execute(castInitialized(this));
}