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

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

Introduction

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

Prototype

NoopHostnameVerifier INSTANCE

To view the source code for org.apache.http.conn.ssl NoopHostnameVerifier INSTANCE.

Click Source Link

Usage

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyController.java

private void populateSSLCertificates(String domainControllerFQDN, int domainControllerPort) throws Exception {
    AfdClient afdClient = new AfdClient(domainControllerFQDN, domainControllerPort,
            NoopHostnameVerifier.INSTANCE, new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override/*from   w  ww  .  j  a  v  a 2  s  .  c om*/
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build());

    List<CertificateDTO> certs = afdClient.vecs().getSSLCertificates();
    int index = 1;
    for (CertificateDTO cert : certs) {
        this.keyStore.setCertificateEntry(String.format("VecsSSLCert%d", index), cert.getX509Certificate());
        index++;
    }
}

From source file:com.github.parisoft.resty.client.Client.java

private HttpClient newHttpClient() throws IOException {
    final SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build();

    final RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(timeout)
            .setConnectTimeout(timeout).setSocketTimeout(timeout).setCookieSpec(CookieSpecs.DEFAULT).build();

    final SSLContext sslContext;
    final HostnameVerifier hostnameVerifier;

    if (bypassSSL) {
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;

        try {//from  w w  w.  jav  a  2  s.  c om
            sslContext = SSLContexts.custom().loadTrustMaterial(new BypassTrustStrategy())
                    .useProtocol(SSLConnectionSocketFactory.TLS).build();
        } catch (Exception e) {
            throw new IOException("Cannot create bypassed SSL context", e);
        }
    } else {
        sslContext = SSLContexts.createSystemDefault();
        hostnameVerifier = null;
    }

    final HttpRequestRetryHandler retryHandler = new RequestRetryHandler(retries);
    final HttpClientConnectionManager connectionManager = getConnectionManager();

    return HttpClientBuilder.create().setConnectionManager(connectionManager).setConnectionManagerShared(true)
            .setRetryHandler(retryHandler).setDefaultSocketConfig(socketConfig)
            .setDefaultRequestConfig(requestConfig).setSSLContext(sslContext)
            .setSSLHostnameVerifier(hostnameVerifier).build();
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.ri.i2b2.I2B2XMLResourceImplementation.java

private HttpClientBuilder ignoreCertificate() throws NoSuchAlgorithmException, KeyManagementException {
    System.setProperty("jsse.enableSNIExtension", "false");

    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }/*from ww w. j a  va2 s  .c o m*/

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sslContext;

    sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
            NoopHostnameVerifier.INSTANCE);

    Registry<ConnectionSocketFactory> r = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("https", sslsf).build();

    HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(r);

    return HttpClients.custom().setConnectionManager(cm);
}

From source file:crawlercommons.fetcher.http.SimpleHttpFetcher.java

private SSLConnectionSocketFactory createSSLConnectionSocketFactory() {
    SSLConnectionSocketFactory sf = null;
    for (String contextName : SSL_CONTEXT_NAMES) {
        try {// w ww.  j ava  2  s  .c  o m
            SSLContext sslContext = SSLContext.getInstance(contextName);
            sslContext.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null);
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            break;
        } catch (NoSuchAlgorithmException e) {
            LOGGER.debug("SSLContext algorithm not available: " + contextName);
        } catch (Exception e) {
            LOGGER.debug("SSLContext can't be initialized: " + contextName, e);
        }
    }
    return sf;
}

From source file:org.apache.ofbiz.base.util.UtilHttp.java

public static CloseableHttpClient getAllowAllHttpClient(String jksStoreFileName, String jksStorePassword) {
    try {//from  w ww.  jav a  2  s  .c  om
        // Trust own CA and all self-signed certs
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(FileUtil.getFile(jksStoreFileName),
                jksStorePassword.toCharArray(), new TrustSelfSignedStrategy()).build();
        // No host name verifier
        SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,
                NoopHostnameVerifier.INSTANCE);
        CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
        return httpClient;
    } catch (Exception e) {
        return HttpClients.createDefault();
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.security.TestHopsworksRMAppSecurityActions.java

private Pair<String, String[]> loginAndGetJWT() throws Exception {
    CloseableHttpClient client = null;/*  w  w  w  .j  a v a 2  s  .  c  o m*/
    try {
        SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
        sslContextBuilder.loadTrustMaterial(new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        });
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
                NoopHostnameVerifier.INSTANCE);

        client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build();
        URL loginURL = new URL(new URL(HOPSWORKS_ENDPOINT), HOPSWORKS_LOGIN_PATH);
        HttpUriRequest login = RequestBuilder.post().setUri(loginURL.toURI())
                .addParameter("email", HOPSWORKS_USER).addParameter("password", HOPSWORKS_PASSWORD).build();
        CloseableHttpResponse response = client.execute(login);
        Assert.assertNotNull(response);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
        Header[] authHeaders = response.getHeaders(HttpHeaders.AUTHORIZATION);

        String masterJWT = null;
        for (Header h : authHeaders) {
            Matcher matcher = HopsworksRMAppSecurityActions.JWT_PATTERN.matcher(h.getValue());
            if (matcher.matches()) {
                masterJWT = matcher.group(1);
            }
        }
        JsonParser jsonParser = new JsonParser();
        JsonObject json = jsonParser.parse(EntityUtils.toString(response.getEntity())).getAsJsonObject();
        JsonArray array = json.getAsJsonArray("renewTokens");
        String[] renewTokens = new String[array.size()];
        boolean renewalTokensFound = false;
        for (int i = 0; i < renewTokens.length; i++) {
            renewTokens[i] = array.get(i).getAsString();
            renewalTokensFound = true;
        }
        if (masterJWT != null && renewalTokensFound) {
            return new Pair<>(masterJWT, renewTokens);
        }

        throw new IOException("Could not get JWT from Hopsworks");
    } finally {
        if (client != null) {
            client.close();
        }
    }
}

From source file:org.apache.nutch.indexwriter.elasticrest.ElasticRestIndexWriter.java

@Override
public void open(IndexWriterParams parameters) throws IOException {
    host = parameters.get(ElasticRestConstants.HOST);
    if (StringUtils.isBlank(host)) {
        String message = "Missing host. It should be set in index-writers.xml";
        message += "\n" + describe();
        LOG.error(message);//from  w  w w .j av a 2  s.  co m
        throw new RuntimeException(message);
    }

    port = parameters.getInt(ElasticRestConstants.PORT, 9200);
    user = parameters.get(ElasticRestConstants.USER);
    password = parameters.get(ElasticRestConstants.PASSWORD);
    https = parameters.getBoolean(ElasticRestConstants.HTTPS, false);
    trustAllHostnames = parameters.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);

    languages = parameters.getStrings(ElasticRestConstants.LANGUAGES);
    separator = parameters.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
    sink = parameters.get(ElasticRestConstants.SINK, DEFAULT_SINK);

    // trust ALL certificates
    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        LOG.error("Failed to instantiate sslcontext object: \n{}", ExceptionUtils.getStackTrace(e));
        throw new SecurityException();
    }

    // skip hostname checks
    HostnameVerifier hostnameVerifier = null;
    if (trustAllHostnames) {
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    } else {
        hostnameVerifier = new DefaultHostnameVerifier();
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
    SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

    JestClientFactory jestClientFactory = new JestClientFactory();
    URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");

    if (host != null && port > 1) {
        HttpClientConfig.Builder builder = new HttpClientConfig.Builder(urlOfElasticsearchNode.toString())
                .multiThreaded(true).connTimeout(300000).readTimeout(300000);
        if (https) {
            if (user != null && password != null) {
                builder.defaultCredentials(user, password);
            }
            builder.defaultSchemeForDiscoveredNodes("https").sslSocketFactory(sslSocketFactory) // this only affects sync calls
                    .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
        }
        jestClientFactory.setHttpClientConfig(builder.build());
    } else {
        throw new IllegalStateException(
                "No host or port specified. Please set the host and port in nutch-site.xml");
    }

    client = jestClientFactory.getObject();

    defaultIndex = parameters.get(ElasticRestConstants.INDEX, "nutch");
    defaultType = parameters.get(ElasticRestConstants.TYPE, "doc");

    maxBulkDocs = parameters.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
    maxBulkLength = parameters.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);

    bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
}

From source file:org.apache.pulsar.client.admin.PulsarAdmin.java

public PulsarAdmin(String serviceUrl, ClientConfigurationData clientConfigData, int connectTimeout,
        TimeUnit connectTimeoutUnit, int readTimeout, TimeUnit readTimeoutUnit) throws PulsarClientException {
    this.connectTimeout = connectTimeout;
    this.connectTimeoutUnit = connectTimeoutUnit;
    this.readTimeout = readTimeout;
    this.readTimeoutUnit = readTimeoutUnit;
    this.clientConfigData = clientConfigData;
    this.auth = clientConfigData != null ? clientConfigData.getAuthentication() : new AuthenticationDisabled();
    LOG.debug("created: serviceUrl={}, authMethodName={}", serviceUrl,
            auth != null ? auth.getAuthMethodName() : null);

    if (auth != null) {
        auth.start();/*from   w  ww. j a v  a2 s .co  m*/
    }

    ClientConfig httpConfig = new ClientConfig();
    httpConfig.property(ClientProperties.FOLLOW_REDIRECTS, true);
    httpConfig.property(ClientProperties.ASYNC_THREADPOOL_SIZE, 8);
    httpConfig.register(MultiPartFeature.class);

    ClientBuilder clientBuilder = ClientBuilder.newBuilder().withConfig(httpConfig)
            .connectTimeout(this.connectTimeout, this.connectTimeoutUnit)
            .readTimeout(this.readTimeout, this.readTimeoutUnit).register(JacksonConfigurator.class)
            .register(JacksonFeature.class);

    boolean useTls = false;

    if (clientConfigData != null && StringUtils.isNotBlank(clientConfigData.getServiceUrl())
            && clientConfigData.getServiceUrl().startsWith("https://")) {
        useTls = true;
        try {
            SSLContext sslCtx = null;

            X509Certificate trustCertificates[] = SecurityUtility
                    .loadCertificatesFromPemFile(clientConfigData.getTlsTrustCertsFilePath());

            // Set private key and certificate if available
            AuthenticationDataProvider authData = auth.getAuthData();
            if (authData.hasDataForTls()) {
                sslCtx = SecurityUtility.createSslContext(clientConfigData.isTlsAllowInsecureConnection(),
                        trustCertificates, authData.getTlsCertificates(), authData.getTlsPrivateKey());
            } else {
                sslCtx = SecurityUtility.createSslContext(clientConfigData.isTlsAllowInsecureConnection(),
                        trustCertificates);
            }

            clientBuilder.sslContext(sslCtx);
            if (clientConfigData.isTlsHostnameVerificationEnable()) {
                clientBuilder.hostnameVerifier(new DefaultHostnameVerifier());
            } else {
                // Disable hostname verification
                clientBuilder.hostnameVerifier(NoopHostnameVerifier.INSTANCE);
            }
        } catch (Exception e) {
            try {
                if (auth != null) {
                    auth.close();
                }
            } catch (IOException ioe) {
                LOG.error("Failed to close the authentication service", ioe);
            }
            throw new PulsarClientException.InvalidConfigurationException(e.getMessage());
        }
    }

    this.client = clientBuilder.build();

    this.serviceUrl = serviceUrl;
    root = client.target(serviceUrl);

    this.clusters = new ClustersImpl(root, auth);
    this.brokers = new BrokersImpl(root, auth);
    this.brokerStats = new BrokerStatsImpl(root, auth);
    this.tenants = new TenantsImpl(root, auth);
    this.properties = new TenantsImpl(root, auth);
    ;
    this.namespaces = new NamespacesImpl(root, auth);
    this.topics = new TopicsImpl(root, auth);
    this.nonPersistentTopics = new NonPersistentTopicsImpl(root, auth);
    this.resourceQuotas = new ResourceQuotasImpl(root, auth);
    this.lookups = new LookupImpl(root, auth, useTls);
    this.functions = new FunctionsImpl(root, auth);
    this.source = new SourceImpl(root, auth);
    this.sink = new SinkImpl(root, auth);
    this.worker = new WorkerImpl(root, auth);
    this.schemas = new SchemasImpl(root, auth);
    this.bookies = new BookiesImpl(root, auth);
}

From source file:org.apache.syncope.installer.utilities.HttpUtils.java

private static CloseableHttpClient createHttpsClient() {
    CloseableHttpClient chc = null;//from  w ww  .  j  av  a2s  .c  om
    try {
        final SSLContextBuilder builder = new SSLContextBuilder();
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
        chc = HttpClients.custom().setSSLSocketFactory(
                new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE)).build();
    } catch (Exception ex) {
        // ignore
    }

    return chc;
}

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;
                }//from   w w  w.j a v a  2  s .  co  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));
    }
}