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:org.elasticsearch.xpack.security.transport.ssl.SslIntegrationTests.java

public void testThatHttpUsingSSLv3IsRejected() throws Exception {
    SSLContext sslContext = SSLContext.getInstance("SSL");
    TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    factory.init((KeyStore) null);

    sslContext.init(null, factory.getTrustManagers(), new SecureRandom());
    SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, new String[] { "SSLv3" }, null,
            NoopHostnameVerifier.INSTANCE);
    try (CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sf).build()) {
        CloseableHttpResponse result = SocketAccess
                .doPrivileged(() -> client.execute(new HttpGet(getNodeUrl())));
        fail("Expected a connection error due to SSLv3 not being supported by default");
    } catch (Exception e) {
        assertThat(e, is(instanceOf(SSLHandshakeException.class)));
    }/*from www  .  ja  v a 2 s.  com*/
}

From source file:net.wasdev.gameon.concierge.PlayerClient.java

/**
 * Obtain apiKey for player id./*from  w w w . java2s  . c  o  m*/
 *
 * @param playerId
 *            The player id
 * @return The apiKey for the player
 */
public String getApiKey(String playerId) throws IOException {
    String jwt = getClientJwtForId(playerId);

    HttpClient client = null;
    if ("development".equals(System.getenv("CONCIERGE_PLAYER_MODE"))) {
        System.out.println("Using development mode player connection. (DefaultSSL,NoHostNameValidation)");
        try {
            HttpClientBuilder b = HttpClientBuilder.create();

            //use the default ssl context, we have a trust store configured for player cert.
            SSLContext sslContext = SSLContext.getDefault();

            //use a very trusting truststore.. (not needed..)
            //SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build();

            b.setSSLContext(sslContext);

            //disable hostname validation, because we'll need to access the cert via a different hostname.
            b.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);

            client = b.build();
        } catch (Exception e) {
            throw new IOException(e);
        }
    } else {
        client = HttpClientBuilder.create().build();
    }
    HttpGet hg = new HttpGet(playerLocation + "/" + playerId + "?jwt=" + jwt);

    System.out.println("Building web target " + hg.getURI().toString());

    try {
        // Make GET request using the specified target, get result as a
        // string containing JSON
        HttpResponse r = client.execute(hg);
        String result = new BasicResponseHandler().handleResponse(r);

        // Parse the JSON response, and retrieve the apiKey field value.
        ObjectMapper om = new ObjectMapper();
        JsonNode jn = om.readValue(result, JsonNode.class);

        return jn.get("apiKey").textValue();
    } catch (HttpResponseException hre) {
        System.out.println(
                "Error communicating with player service: " + hre.getStatusCode() + " " + hre.getMessage());
        throw hre;
    } catch (ResponseProcessingException rpe) {
        System.out.println("Error processing response " + rpe.getResponse().toString());
        throw new IOException(rpe);
    } catch (ProcessingException | WebApplicationException ex) {
        //bad stuff.
        System.out.println("Hmm.. " + ex.getMessage());
        throw new IOException(ex);
    } catch (IOException io) {
        System.out.println("Utoh.. " + io.getMessage());
        throw new IOException(io);
    }

}

From source file:com.bosch.cr.integration.hello_world_ui.ProxyServlet.java

/**
 * Create http client/*from   ww w. j  a v  a  2 s . c o  m*/
 */
private synchronized CloseableHttpClient getHttpClient() {
    if (httpClient == null) {
        try {
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

            // #### ONLY FOR TEST: Trust ANY certificate (self certified, any chain, ...)
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (chain, authType) -> true)
                    .build();
            httpClientBuilder.setSSLContext(sslContext);

            // #### ONLY FOR TEST: Do NOT verify hostname
            SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                    NoopHostnameVerifier.INSTANCE);

            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory>create()
                    .register("http", PlainConnectionSocketFactory.getSocketFactory())
                    .register("https", sslConnectionSocketFactory).build();
            PoolingHttpClientConnectionManager httpClientConnectionManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            httpClientBuilder.setConnectionManager(httpClientConnectionManager);

            if (props.getProperty("http.proxyHost") != null) {
                httpClientBuilder.setProxy(new HttpHost(props.getProperty("http.proxyHost"),
                        Integer.parseInt(props.getProperty("http.proxyPort"))));
            }

            if (props.getProperty("http.proxyUser") != null) {
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(new AuthScope(targetHost), new UsernamePasswordCredentials(
                        props.getProperty("http.proxyUser"), props.getProperty("http.proxyPwd")));
                httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
            }

            httpClient = httpClientBuilder.build();
        } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException ex) {
            throw new RuntimeException(ex);
        }
    }

    return httpClient;
}

From source file:org.wso2.appcloud.integration.test.utils.clients.ApplicationClient.java

public void createNewApplication(String applicationName, String runtime, String appTypeName,
        String applicationRevision, String applicationDescription, String uploadedFileName,
        String runtimeProperties, String tags, File uploadArtifact, boolean isNewVersion,
        String applicationContext, String conSpec, boolean setDefaultVersion, String appCreationMethod,
        String gitRepoUrl, String gitRepoBranch, String projectRoot) throws AppCloudIntegrationTestException {

    HttpClient httpclient = null;//from www. j av a  2 s .  c o m
    org.apache.http.HttpResponse response = null;
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpPost httppost = new HttpPost(this.endpoint);
        httppost.setConfig(requestConfig);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        builder.addPart(PARAM_NAME_ACTION, new StringBody(CREATE_APPLICATION_ACTION, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CREATION_METHOD,
                new StringBody(appCreationMethod, ContentType.TEXT_PLAIN));
        if (GITHUB.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_GIT_REPO_URL, new StringBody(gitRepoUrl, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_GIT_REPO_BRANCH, new StringBody(gitRepoBranch, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_PROJECT_ROOT, new StringBody(projectRoot, ContentType.TEXT_PLAIN));
        } else if (DEFAULT.equals(appCreationMethod)) {
            builder.addPart(PARAM_NAME_FILE_UPLOAD, new FileBody(uploadArtifact));
            builder.addPart(PARAM_NAME_UPLOADED_FILE_NAME,
                    new StringBody(uploadedFileName, ContentType.TEXT_PLAIN));
            builder.addPart(PARAM_NAME_IS_FILE_ATTACHED,
                    new StringBody(Boolean.TRUE.toString(), ContentType.TEXT_PLAIN));//Setting true to send the file in request
        }
        builder.addPart(PARAM_NAME_CONTAINER_SPEC, new StringBody(conSpec, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_NAME, new StringBody(applicationName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_DESCRIPTION,
                new StringBody(applicationDescription, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_RUNTIME, new StringBody(runtime, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_TYPE_NAME, new StringBody(appTypeName, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APP_CONTEXT, new StringBody(applicationContext, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_APPLICATION_REVISION,
                new StringBody(applicationRevision, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_PROPERTIES, new StringBody(runtimeProperties, ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_TAGS, new StringBody(tags, ContentType.TEXT_PLAIN));

        builder.addPart(PARAM_NAME_IS_NEW_VERSION,
                new StringBody(Boolean.toString(isNewVersion), ContentType.TEXT_PLAIN));
        builder.addPart(PARAM_NAME_SET_DEFAULT_VERSION,
                new StringBody(Boolean.toString(setDefaultVersion), ContentType.TEXT_PLAIN));

        httppost.setEntity(builder.build());
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        response = httpclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            String result = EntityUtils.toString(response.getEntity());
            throw new AppCloudIntegrationTestException("CreateNewApplication failed " + result);
        }

    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        // If application is not created, in next test case, it will be identified.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
    } catch (IOException e) {
        log.error("Failed to invoke application creation API.", e);
        throw new AppCloudIntegrationTestException("Failed to invoke application creation API.", e);
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(httpclient);
    }
}

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

private SSLConnectionSocketFactory configureSsl() throws OfficeException {

    if (sslConfig == null || !sslConfig.isEnabled()) {
        return null;
    }/*from  w  w  w. j a  v  a 2  s.  c  om*/

    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:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

protected PoolingHttpClientConnectionManager newConnectionManager() {
    try {/*from   w ww  .  j  av  a  2  s  .  c om*/
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } }, new SecureRandom());

        RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder
                .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE);
        if (this.sslHostnameValidationEnabled) {
            registryBuilder.register("https", new SSLConnectionSocketFactory(sslContext));
        } else {
            registryBuilder.register("https",
                    new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE));
        }
        final Registry<ConnectionSocketFactory> registry = registryBuilder.build();

        this.connectionManager = new PoolingHttpClientConnectionManager(registry);
        this.connectionManager.setMaxTotal(this.hostProperties.getMaxTotalConnections());
        this.connectionManager.setDefaultMaxPerRoute(this.hostProperties.getMaxPerRouteConnections());
        return this.connectionManager;
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.wso2.appcloud.integration.test.utils.clients.BaseClient.java

public HttpResponse doPostRequest(String endpoint, List<NameValuePair> nameValuePairs)
        throws AppCloudIntegrationTestException {
    HttpClient httpclient = null;//from   www  . j a  v a2 s .com
    int timeout = (int) AppCloudIntegrationTestUtils.getTimeOutPeriod();
    try {
        httpclient = HttpClients.custom().setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE).build();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout)
                .setConnectTimeout(timeout).build();
        HttpPost httppost = new HttpPost(endpoint);
        httppost.setConfig(requestConfig);

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        httppost.setHeader(HEADER_COOKIE, getRequestHeaders().get(HEADER_COOKIE));
        org.apache.http.HttpResponse httpResponse = (httpclient.execute(httppost));
        return new HttpResponse(EntityUtils.toString(httpResponse.getEntity(), "UTF-8").replaceAll("\\s+", ""),
                httpResponse.getStatusLine().getStatusCode());
    } catch (ConnectTimeoutException | java.net.SocketTimeoutException e1) {
        // In most of the cases, even though connection is timed out, actual activity is completed.
        log.warn("Failed to get 200 ok response from endpoint:" + endpoint, e1);
        return new HttpResponse(e1.getMessage(), HttpStatus.SC_REQUEST_TIMEOUT);
    } catch (IOException e) {
        log.error("Failed to invoke API endpoint:" + endpoint, e);
        throw new AppCloudIntegrationTestException("Failed to invoke API endpoint:" + endpoint, e);
    } finally {
        HttpClientUtils.closeQuietly(httpclient);
    }
}

From source file:com.vmware.identity.openidconnect.client.TestUtils.java

static void populateSSLCertificates(String domainControllerFQDN, int domainControllerPort, KeyStore keyStore)
        throws Exception {
    AfdClient afdClient = new AfdClient(domainControllerFQDN, domainControllerPort,
            NoopHostnameVerifier.INSTANCE, new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override/*from w w  w .j a v  a2 s . c  o m*/
                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) {
        keyStore.setCertificateEntry(String.format("VecsSSLCert%d", index), cert.getX509Certificate());
        index++;
    }
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

protected CloseableHttpClient newClient() {
    final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT.get())
            .setConnectTimeout(CONNECTION_TIMEOUT.get()).setCookieSpec(CookieSpecs.IGNORE_COOKIES).build();

    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    if (!this.sslHostnameValidationEnabled) {
        httpClientBuilder.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE);
    }//from  w ww. j  ava 2  s . com
    return httpClientBuilder.setConnectionManager(newConnectionManager()).useSystemProperties()
            .setDefaultRequestConfig(requestConfig)
            .setRetryHandler(new DefaultHttpRequestRetryHandler(0, false))
            .setRedirectStrategy(new RedirectStrategy() {
                @Override
                public boolean isRedirected(HttpRequest request, HttpResponse response, HttpContext context)
                        throws ProtocolException {
                    return false;
                }

                @Override
                public HttpUriRequest getRedirect(HttpRequest request, HttpResponse response,
                        HttpContext context) throws ProtocolException {
                    return null;
                }
            }).build();
}