Example usage for javax.net.ssl HostnameVerifier HostnameVerifier

List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier

Introduction

In this page you can find the example usage for javax.net.ssl HostnameVerifier HostnameVerifier.

Prototype

HostnameVerifier

Source Link

Usage

From source file:com.sun.socialsite.pojos.App.java

public static App readFromURL(URL url) throws Exception {
    HttpURLConnection con = (HttpURLConnection) (url.openConnection());
    con.setDoOutput(false);/*from  w ww.  j  a  v  a  2s. c om*/
    // TODO: figure out why this is necessary for HTTPS URLs
    if (con instanceof HttpsURLConnection) {
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if ("localhost".equals(urlHostName) && "127.0.0.1".equals(session.getPeerHost())) {
                    return true;
                } else {
                    log.warn("URL Host: " + urlHostName + " vs. " + session.getPeerHost());
                    return false;
                }
            }
        };
        ((HttpsURLConnection) con).setDefaultHostnameVerifier(hv);
    }
    con.connect();
    if (con.getResponseCode() != HttpURLConnection.HTTP_OK) {
        throw new RuntimeException(con.getResponseMessage());
    }
    InputStream in = con.getInputStream();
    return readFromStream(in, url);
}

From source file:org.flowable.http.cmmn.impl.CmmnHttpActivityBehaviorImpl.java

public CmmnHttpActivityBehaviorImpl() {
    org.flowable.cmmn.engine.HttpClientConfig config = CommandContextUtil.getCmmnEngineConfiguration()
            .getHttpClientConfig();/*from www.jav  a 2s.  co  m*/
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();

    // https settings
    if (config.isDisableCertVerify()) {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            httpClientBuilder.setSSLSocketFactory(
                    new SSLConnectionSocketFactory(builder.build(), new HostnameVerifier() {
                        @Override
                        public boolean verify(String s, SSLSession sslSession) {
                            return true;
                        }
                    }));

        } catch (Exception e) {
            LOGGER.error("Could not configure HTTP client SSL self signed strategy", e);
        }
    }

    // request retry settings
    int retryCount = 0;
    if (config.getRequestRetryLimit() > 0) {
        retryCount = config.getRequestRetryLimit();
    }
    httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(retryCount, false));

    this.httpActivityExecutor = new HttpActivityExecutor(httpClientBuilder, new NopErrorPropagator());
}

From source file:com.nextdoor.bender.ipc.http.AbstractHttpTransportFactory.java

protected HttpClientBuilder getClientBuilder(boolean useSSL, String url, Map<String, String> stringHeaders,
        int socketTimeout) {

    HttpClientBuilder cb = HttpClientBuilder.create();

    /*/*from w  w  w .java2 s.  co  m*/
     * Setup SSL
     */
    if (useSSL) {
        /*
         * All trusting SSL context
         */
        try {
            cb.setSSLContext(getSSLContext());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        /*
         * All trusting hostname verifier
         */
        cb.setSSLHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String s, SSLSession sslSession) {
                return true;
            }
        });
    }

    /*
     * Add default headers
     */
    ArrayList<BasicHeader> headers = new ArrayList<BasicHeader>(stringHeaders.size());
    stringHeaders.forEach((k, v) -> headers.add(new BasicHeader(k, v)));
    cb.setDefaultHeaders(headers);

    /*
     * Set socket timeout and transport threads
     */
    SocketConfig sc = SocketConfig.custom().setSoTimeout(socketTimeout).build();
    cb.setDefaultSocketConfig(sc);
    cb.setMaxConnPerRoute(this.config.getThreads());
    cb.setMaxConnTotal(this.config.getThreads());

    return cb;
}

From source file:org.openhab.binding.unifi.internal.UnifiBinding.java

/**
 * Called by the SCR to activate the component with its configuration read from CAS
 *
 * @param bundleContext BundleContext of the Bundle that defines this component
 * @param configuration Configuration properties for this component obtained from the ConfigAdmin service
 *///from   ww w . jav  a2  s. com
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) {
    this.bundleContext = bundleContext;

    // the configuration is guaranteed not to be null, because the component definition has the
    // configuration-policy set to require. If set to 'optional' then the configuration may be null

    // to override the default refresh interval one has to add a
    // parameter to openhab.cfg like <bindingName>:refresh=<intervalInMs>
    readConfiguration(configuration);

    try {
        sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
    } catch (Exception e) {
        logger.error("Cannot initialize SSL Context!" + e.toString());
        setProperlyConfigured(false);
        return;
    }

    setProperlyConfigured(true);
}

From source file:org.apache.jmeter.util.JsseSSLManager.java

/**
 * Create the SSLContext, and wrap all the X509KeyManagers with
 * our X509KeyManager so that we can choose our alias.
 *
 * @param provider/*from  www  .  j  a va  2 s  .com*/
 *            Description of Parameter
 */
public JsseSSLManager(Provider provider) {
    log.debug("ssl Provider =  " + provider);
    setProvider(provider);
    if (null == this.rand) { // Surely this is always null in the constructor?
        this.rand = new SecureRandom();
    }
    try {
        if (SHARED_SESSION_CONTEXT) {
            log.debug("Creating shared context");
            this.defaultContext = createContext();
        } else {
            this.threadlocal = new ThreadLocal<>();
        }

        HttpsURLConnection.setDefaultSSLSocketFactory(new HttpSSLProtocolSocketFactory(this, CPS));
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });

        /*
         * Also set up HttpClient defaults
         */
        Protocol protocol = new Protocol(JsseSSLManager.HTTPS,
                (ProtocolSocketFactory) new HttpSSLProtocolSocketFactory(this, CPS), 443);
        Protocol.registerProtocol(JsseSSLManager.HTTPS, protocol);
        log.debug("SSL stuff all set");
    } catch (GeneralSecurityException ex) {
        log.error("Could not set up SSLContext", ex);
    }
    log.debug("JsseSSLManager installed");
}

From source file:org.parosproxy.paros.core.proxy.WithBasicInfrastructureIntegrationTest.java

/**
 * Use custom TrustManager that trusts everything.
 * Moreover setup custom ProtocolSocketFactory as done in ZAP.
 * //www  . j  a  v  a 2 s  .c  o m
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
protected static void initializeLocalSecurity() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext sslContext = SSLContext.getInstance("SSL");

    // set up a TrustManager that trusts everything
    sslContext.init(null, new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // everything is trusted
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // everything is trusted
        }

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

    // this doesn't seem to apply to connections through a proxy
    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());

    // setup a hostname verifier that verifies everything
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {

        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) new SSLConnector(), 443));
}

From source file:ezbake.deployer.publishers.SecurityServiceClient.java

protected HttpsURLConnection openUrlConnection(URL endpoint) throws IOException, SSLContextException {

    SSLContext sslContext = EzSSL.getSSLContext(config.getEzConfiguration());

    HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        @Override/*  ww w  .  j a va2 s  .c o m*/
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
    return (HttpsURLConnection) endpoint.openConnection();
}

From source file:org.openmrs.module.rheapocadapter.handler.ConnectionHandler.java

public String[] callGet(String stringUrl) {
    try {//from   w w w  . j  a  v  a 2  s.  c om

        // Setup connection
        URL url = new URL(stringUrl);

        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        // This is important to get the connection to use our trusted
        // certificate
        conn.setSSLSocketFactory(sslFactory);

        addHTTPBasicAuthProperty(conn);
        //conn.setConnectTimeout(timeOut);
        // bug fixing for SSL error, this is a temporary fix, need to find a
        // long term one
        conn.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        // printHttpsCert(conn);
        conn.connect();
        int code = conn.getResponseCode();

        if (code >= 200 && code < 300) {
            String result = IOUtils.toString(conn.getInputStream());
            conn.disconnect();
            return new String[] { code + "", result };
        } else {
            conn.disconnect();
            return new String[] { code + "", "Server returned " + code + " response code" };
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
        log.error("MalformedURLException while callGet " + e.getMessage());
        return new String[] { 400 + "", e.getMessage() };
    } catch (IOException e) {
        e.printStackTrace();
        log.error("IOException while callGet " + e.getMessage());
        return new String[] { 600 + "", e.getMessage() };
    }
}

From source file:org.apache.hadoop.io.crypto.bee.RestClient.java

private InputStream httpsIgnoreCertificate(final URL url) throws IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }/* www .  j  ava  2  s . c  om*/

        public void checkClientTrusted(X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {
        }
    } };

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        ;
    }

    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    return urlConnection.getInputStream();

}