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

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

Introduction

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

Prototype

AllowAllHostnameVerifier

Source Link

Usage

From source file:org.springframework.ide.eclipse.boot.dash.cloudfoundry.CloudAppDashElement.java

@Override
protected RestTemplate getRestTemplate() {
    CloudFoundryTargetProperties props = getTarget().getTargetProperties();
    boolean skipSsl = props.isSelfsigned() || props.skipSslValidation();
    if (skipSsl) {
        HttpClient httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
                .setSslcontext(buildSslContext()).build();
        ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
        return new RestTemplate(requestFactory);
    } else {// w w w. ja  va2 s .  com
        //This worked before so lets not try to fix that case.
        return super.getRestTemplate();
    }
}

From source file:org.niord.core.keycloak.KeycloakIntegrationService.java

/**
 * Executes a Keycloak admin request and returns the result.
 *
 * @param request the Keycloak request to execute
 * @param auth whether to add a Bearer authorization header or not
 * @param responseHandler the response handler
 * @return the result/*  ww w.jav  a 2  s .  c  o m*/
 */
private <R> R executeAdminRequest(HttpRequestBase request, boolean auth,
        KeycloakResponseHandler<R> responseHandler) throws Exception {

    if (auth) {
        KeycloakPrincipal keycloakPrincipal = userService.getCallerPrincipal();
        if (keycloakPrincipal == null) {
            throw new Exception("Unable to execute request " + request.getURI() + ". User not authenticated");
        }
        request.addHeader("Authorization",
                "Bearer " + keycloakPrincipal.getKeycloakSecurityContext().getTokenString());
    }

    // TODO: Check if this works with https based on self-signed certificates
    HttpClient client = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()).build();

    HttpResponse response = client.execute(request);

    int status = response.getStatusLine().getStatusCode();
    if (status < 200 || status > 299) {
        try {
            response.getEntity().getContent().close();
        } catch (Exception ignored) {
        }
        throw new Exception("Unable to execute request " + request.getURI() + ", status = " + status);
    }

    HttpEntity entity = response.getEntity();
    if (entity == null) {
        return responseHandler.execute(null);
    }

    try (InputStream is = entity.getContent()) {
        return responseHandler.execute(is);
    }
}

From source file:org.archive.modules.fetcher.FetchHTTPRequest.java

protected HttpClientConnectionManager buildConnectionManager() {
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE).register("https",
                    new SSLConnectionSocketFactory(fetcher.sslContext(), new AllowAllHostnameVerifier()) {

                        @Override
                        public Socket createLayeredSocket(final Socket socket, final String target,
                                final int port, final HttpContext context) throws IOException {

                            return super.createLayeredSocket(socket, isDisableSNI() ? "" : target, port,
                                    context);
                        }/* ww w. jav a 2 s.com*/
                    })
            .build();

    DnsResolver dnsResolver = new ServerCacheResolver(fetcher.getServerCache());

    ManagedHttpClientConnectionFactory connFactory = new ManagedHttpClientConnectionFactory() {
        private static final int DEFAULT_BUFSIZE = 8 * 1024;

        @Override
        public ManagedHttpClientConnection create(HttpRoute route, ConnectionConfig config) {
            final ConnectionConfig cconfig = config != null ? config : ConnectionConfig.DEFAULT;
            CharsetDecoder chardecoder = null;
            CharsetEncoder charencoder = null;
            final Charset charset = cconfig.getCharset();
            final CodingErrorAction malformedInputAction = cconfig.getMalformedInputAction() != null
                    ? cconfig.getMalformedInputAction()
                    : CodingErrorAction.REPORT;
            final CodingErrorAction unmappableInputAction = cconfig.getUnmappableInputAction() != null
                    ? cconfig.getUnmappableInputAction()
                    : CodingErrorAction.REPORT;
            if (charset != null) {
                chardecoder = charset.newDecoder();
                chardecoder.onMalformedInput(malformedInputAction);
                chardecoder.onUnmappableCharacter(unmappableInputAction);
                charencoder = charset.newEncoder();
                charencoder.onMalformedInput(malformedInputAction);
                charencoder.onUnmappableCharacter(unmappableInputAction);
            }
            return new RecordingHttpClientConnection(DEFAULT_BUFSIZE, DEFAULT_BUFSIZE, chardecoder, charencoder,
                    cconfig.getMessageConstraints(), null, null, DefaultHttpRequestWriterFactory.INSTANCE,
                    DefaultHttpResponseParserFactory.INSTANCE);
        }
    };
    BasicHttpClientConnectionManager connMan = new BasicHttpClientConnectionManager(socketFactoryRegistry,
            connFactory, null, dnsResolver);

    SocketConfig.Builder socketConfigBuilder = SocketConfig.custom();
    socketConfigBuilder.setSoTimeout(fetcher.getSoTimeoutMs());
    connMan.setSocketConfig(socketConfigBuilder.build());

    return connMan;
}

From source file:com.cloud.network.resource.NccHttpCode.java

public static HttpClient getHttpClient() {

    HttpClient httpClient = null;// w  w w  . ja v a 2  s. c  om
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };

    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }
    return httpClient;
}

From source file:com.cloud.network.resource.NccHttpCode.java

public static String postHttpRequest(final String jsonCmd, final URI agentUri, String sessionID)
        throws ExecutionException {
    // Using Apache's HttpClient for HTTP POST
    // Java-only approach discussed at on StackOverflow concludes with
    // comment to use Apache HttpClient
    // http://stackoverflow.com/a/2793153/939250, but final comment is to
    // use Apache.
    String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
    logMessage = cleanPassword(logMessage);
    s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);

    // Create request
    HttpClient httpClient = getHttpClient();
    TrustStrategy easyStrategy = new TrustStrategy() {
        @Override/*from www  .  j  av  a  2  s .c  o m*/
        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }
    };

    try {
        SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_PORT, sf));
        ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }

    String result = null;

    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        HttpPost request = new HttpPost(agentUri);

        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.addHeader("Cookie", "SessId=" + sessionID);
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage + "SEssion id: "
                + sessionID);
        HttpResponse response = httpClient.execute(request);

        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            String errMsg = "Failed : HTTP error code : " + response.getStatusLine().getStatusCode();
            throw new ExecutionException(NccHttpCode.NOT_FOUND);
        } else if ((response.getStatusLine().getStatusCode() != HttpStatus.SC_OK)
                && (response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)) {
            String errMsg = "Command Not Success " + agentUri.toString() + " : HTTP error code : "
                    + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            throw new ExecutionException(NccHttpCode.INTERNAL_ERROR + " " + errMsg);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            //Successfully created the resource in the NCC, Now get the Job ID and send to the response
            // make login request and store new session id
            throw new ExecutionException(NccHttpCode.UNAUTHORIZED);
        } else if (response.getStatusLine().getStatusCode() == HttpStatus.SC_CREATED) {
            //Successfully created the resource in the NCC, Now get the Job ID and send to the response
            result = response.getFirstHeader(NccHttpCode.JOB_ID).getValue();
        } else {
            result = EntityUtils.toString(response.getEntity());
            String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }

    } catch (ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:com.magnet.mmx.client.MMXClient.java

private synchronized HostnameVerifier getNaiveHostnameVerifier() {
    if (mNaiveHostnameVerifier == null) {
        mNaiveHostnameVerifier = new AllowAllHostnameVerifier();
    }/*  w  w  w  . j a v  a 2s  . co m*/
    return mNaiveHostnameVerifier;
}

From source file:com.cloud.hypervisor.hyperv.resource.HypervDirectConnectResource.java

public static String postHttpRequest(final String jsonCmd, final URI agentUri) {
    // Using Apache's HttpClient for HTTP POST
    // Java-only approach discussed at on StackOverflow concludes with
    // comment to use Apache HttpClient
    // http://stackoverflow.com/a/2793153/939250, but final comment is to
    // use Apache.
    String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
    logMessage = cleanPassword(logMessage);
    s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);

    // Create request
    HttpClient httpClient = null;/*  ww w  .  j  ava  2s  . c  o m*/
    final TrustStrategy easyStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(final X509Certificate[] chain, final String authType)
                throws CertificateException {
            return true;
        }
    };

    try {
        final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
        final ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
        httpClient = new DefaultHttpClient(ccm);
    } catch (final KeyManagementException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final UnrecoverableKeyException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final NoSuchAlgorithmException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    } catch (final KeyStoreException e) {
        s_logger.error("failed to initialize http client " + e.getMessage());
    }

    String result = null;

    // TODO: are there timeout settings and worker thread settings to tweak?
    try {
        final HttpPost request = new HttpPost(agentUri);

        // JSON encode command
        // Assumes command sits comfortably in a string, i.e. not used for
        // large data transfers
        final StringEntity cmdJson = new StringEntity(jsonCmd);
        request.addHeader("content-type", "application/json");
        request.setEntity(cmdJson);
        s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage);
        final HttpResponse response = httpClient.execute(request);

        // Unsupported commands will not route.
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            final String errMsg = "Failed to send : HTTP error code : "
                    + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            final String unsupportMsg = "Unsupported command " + agentUri.getPath()
                    + ".  Are you sure you got the right type of" + " server?";
            final Answer ans = new UnsupportedAnswer(null, unsupportMsg);
            s_logger.error(ans);
            result = s_gson.toJson(new Answer[] { ans });
        } else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : "
                    + response.getStatusLine().getStatusCode();
            s_logger.error(errMsg);
            return null;
        } else {
            result = EntityUtils.toString(response.getEntity());
            final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
            s_logger.debug("POST response is " + logResult);
        }
    } catch (final ClientProtocolException protocolEx) {
        // Problem with HTTP message exchange
        s_logger.error(protocolEx);
    } catch (final IOException connEx) {
        // Problem with underlying communications
        s_logger.error(connEx);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    return result;
}

From source file:nl.opengeogroep.safetymaps.routing.service.OpenRouteService.java

private static CloseableHttpClient getClient()
        throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
    return HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier())
            .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                @Override// w  ww .j  a  v  a  2s . c  o  m
                public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                    return true;
                }
            }).build())
            .setDefaultRequestConfig(
                    RequestConfig.custom().setConnectTimeout(5 * 1000).setSocketTimeout(10 * 1000).build())
            .build();
}

From source file:org.apache.hadoop.gateway.hdfs.web.KnoxUrlConnectionFactory.java

private void configureConnectionHostnameVerifier(URLConnection connection) {
    if (!config.getBoolean("knox.webhdfs.verify.hostname", true)) {
        if (connection instanceof HttpsURLConnection) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(new AllowAllHostnameVerifier());
        }//from  w w  w. ja  v a  2s. c  o m
    }
}

From source file:org.hyperic.util.security.DatabaseSSLProviderImpl.java

private X509HostnameVerifier getHostnameVerifier() {
    return new X509HostnameVerifier() {
        private AllowAllHostnameVerifier internalVerifier = new AllowAllHostnameVerifier();

        public boolean verify(String host, SSLSession session) {
            return internalVerifier.verify(host, session);
        }/*  w  w w.  ja  v  a 2 s. c  o  m*/

        public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {
            internalVerifier.verify(host, cns, subjectAlts);
        }

        public void verify(String host, X509Certificate cert) throws SSLException {
            internalVerifier.verify(host, cert);
        }

        public void verify(String host, SSLSocket ssl) throws IOException {
            try {
                internalVerifier.verify(host, ssl);
            } catch (SSLPeerUnverifiedException e) {
                throw new SSLPeerUnverifiedException(
                        "The authenticity of host '" + host + "' can't be established.");
            }
        }
    };
}