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:hudson.remoting.Launcher.java

/**
 * Bypass HTTPS security check by using free-for-all trust manager.
 *
 * @param _//w w  w .j  a  va 2  s . com
 *      This is ignored.
 */
@Option(name = "-noCertificateCheck")
public void setNoCertificateCheck(boolean _) throws NoSuchAlgorithmException, KeyManagementException {
    System.out.println("Skipping HTTPS certificate checks altoghether. Note that this is not secure at all.");
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
    // bypass host name check, too.
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }
    });
}

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

public String[] callPostAndPut(String stringUrl, String body, String method) {
    try {//from  ww w . j a  v  a2 s.co  m
        // Setup connection
        URL url = new URL(stringUrl);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(method.toUpperCase());
        conn.setDoInput(true);
        // 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;
            }
        });

        OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        log.error("body" + body);
        out.write(body);
        out.close();
        conn.connect();
        String result = "";
        int code = conn.getResponseCode();

        if (code == 201) {
            result = "Saved succefully";
        } else {
            result = "Not Saved";
        }
        conn.disconnect();

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

From source file:org.apache.falcon.resource.TestContext.java

public void configure() throws Exception {
    try {/*from  ww w .  j  av  a  2s .c o  m*/
        StartupProperties.get().setProperty("application.services",
                StartupProperties.get().getProperty("application.services")
                        .replace("org.apache.falcon.service.ProcessSubscriberService", ""));
        String store = StartupProperties.get().getProperty("config.store.uri");
        StartupProperties.get().setProperty("config.store.uri", store + System.currentTimeMillis());
        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null,
                new TrustManager[] { TrustManagerUtils.getValidateServerCertificateTrustManager() },
                new SecureRandom());
        DefaultClientConfig config = new DefaultClientConfig();
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession sslSession) {
                        return true;
                    }
                }, sslContext));
        Client client = Client.create(config);
        this.service = client.resource(UriBuilder.fromUri(BASE_URL).build());
    } catch (Exception e) {
        throw new FalconRuntimException(e);
    }

    try {
        String baseUrl = BASE_URL;
        if (!baseUrl.endsWith("/")) {
            baseUrl += "/";
        }
        this.authenticationToken = FalconClient.getToken(baseUrl);
    } catch (FalconCLIException e) {
        throw new AuthenticationException(e);
    }

    ClientConfig config = new DefaultClientConfig();
    Client client = Client.create(config);
    client.setReadTimeout(500000);
    client.setConnectTimeout(500000);
    this.service = client.resource(UriBuilder.fromUri(BASE_URL).build());
}

From source file:org.hyperic.plugin.vrealize.automation.VRAUtils.java

public static String getWGet(String path) {
    String retValue = null;//www .j a  v a2  s .c om
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

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

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };
        // Install the all-trusting trust manager
        SSLContext 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);
        URL url = new URL(path);
        URLConnection con;
        try {
            con = url.openConnection();
        } catch (Exception e) {
            log.debug("Couldnt connect to vRa API");
            return "";
        }

        Reader reader = new InputStreamReader(con.getInputStream());
        while (true) {
            int ch = reader.read();
            if (ch == -1) {
                break;
            }
            retValue += (char) ch;
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }

    return retValue;
}

From source file:org.apache.ranger.plugin.util.RangerRESTClient.java

private Client buildClient() {
    Client client = null;/*w  ww  . ja v a  2s .  c om*/

    if (mIsSSL) {
        KeyManager[] kmList = getKeyManagers();
        TrustManager[] tmList = getTrustManagers();
        SSLContext sslContext = getSSLContext(kmList, tmList);
        ClientConfig config = new DefaultClientConfig();

        config.getClasses().add(JacksonJsonProvider.class); // to handle List<> unmarshalling

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return session.getPeerHost().equals(urlHostName);
            }
        };

        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(hv, sslContext));

        client = Client.create(config);
    }

    if (client == null) {
        ClientConfig config = new DefaultClientConfig();

        config.getClasses().add(JacksonJsonProvider.class); // to handle List<> unmarshalling

        client = Client.create(config);
    }

    if (!StringUtils.isEmpty(mUsername) && !StringUtils.isEmpty(mPassword)) {
        client.addFilter(new HTTPBasicAuthFilter(mUsername, mPassword));
    }

    // Set Connection Timeout and ReadTime for the PolicyRefresh
    client.setConnectTimeout(mRestClientConnTimeOutMs);
    client.setReadTimeout(mRestClientReadTimeOutMs);

    return client;
}

From source file:org.apache.ambari.server.scheduler.ExecutionScheduleManager.java

protected void buildApiClient() throws NoSuchAlgorithmException, KeyManagementException {

    Client client;//from  w  ww  .j  a va  2  s  .  c om

    String pattern;
    String url;

    if (configuration.getApiSSLAuthentication()) {
        pattern = "https://localhost:%s/";
        url = String.format(pattern, configuration.getClientSSLApiPort());

        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {

            }

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

            }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

        } };

        //Create SSL context
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());

        //Install all trusting cert SSL context for jersey client
        ClientConfig config = new DefaultClientConfig();
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(new HostnameVerifier() {
                    @Override
                    public boolean verify(String s, SSLSession sslSession) {
                        return true;
                    }
                }, sc));

        client = Client.create(config);

    } else {
        client = Client.create();
        pattern = "http://localhost:%s/";
        url = String.format(pattern, configuration.getClientApiPort());
    }

    this.ambariClient = client;
    this.ambariWebResource = client.resource(url);

    //Install auth filters
    ClientFilter csrfFilter = new CsrfProtectionFilter("RequestSchedule");
    ClientFilter tokenFilter = new InternalTokenClientFilter(tokenStorage);
    ambariClient.addFilter(csrfFilter);
    ambariClient.addFilter(tokenFilter);

}

From source file:net.es.enos.esnet.OSCARSTopologyPublisher.java

/**
 * Loads the topology from the ESnet URL. The result is in JSON format.
 * @return a single string that contains the whole topology in its wire format.
 */// www .  ja  v a2 s  . c  om
private String loadFromUrl() {

    try {
        ClientConfig clientConfig = new DefaultClientConfig();

        SSLContext sslcontext = null;
        TrustManager[] trustAllCerts = new TrustManager[] { new TopologyTrustManager() };

        HTTPSProperties httpsProperties = new HTTPSProperties(new HostnameVerifier() {
            @Override
            public boolean verify(String s, SSLSession sslSession) {
                // whatever your matching policy states
                logger.info("Verifying SSL Session");
                return true;
            }
        });

        clientConfig.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, httpsProperties);
        sslcontext = httpsProperties.getSSLContext();
        sslcontext.init(null, trustAllCerts, null);
        Client client = Client.create(clientConfig);
        clientConfig.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);

        WebResource webResource = client.resource(OSCARSTopologyPublisher.ESNET_DEFAULT_URL);
        ClientResponse response = webResource.accept("application/json").get(ClientResponse.class);
        if (response.getStatus() != 200) {
            throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
        }
        String txt = IOUtils.toString(response.getEntityInputStream());
        String output = this.normalize(txt);
        return output;

    } catch (Exception e) {
        logger.warn("Cannot retrieve the topology");
        return null;
    }
}

From source file:org.talend.librariesmanager.utils.nexus.NexusDownloader.java

private HttpURLConnection getHttpURLConnection(String nexusUrl, String repositoryId, String relativePath,
        String userName, String password) throws Exception {
    String path = nexusUrl;/*from  w ww . j av a  2s .  c  om*/
    if (path.endsWith(NexusConstants.SLASH)) {
        path = path.substring(0, path.length() - 1);
    }
    path = path + NexusConstants.CONTENT_REPOSITORIES;
    path = path + repositoryId + NexusConstants.SLASH;
    URL url = new URL(path + relativePath);
    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
    if (userName != null && !"".equals(userName)) {
        urlConnection.setRequestProperty("Authorization", //$NON-NLS-1$
                "Basic " + Base64.encodeBase64((userName + ":" + password).getBytes()));//$NON-NLS-1$
    }
    if (urlConnection instanceof HttpsURLConnection) {
        String userDir = Platform.getInstallLocation().getURL().getPath();
        final SSLSocketFactory socketFactory = SSLUtils.getSSLContext(userDir).getSocketFactory();
        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setSSLSocketFactory(socketFactory);
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {

            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }

        });
    }
    urlConnection.setConnectTimeout(10000);
    urlConnection.setReadTimeout(10000);
    return urlConnection;
}

From source file:com.zlk.bigdemo.android.volley.toolbox.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 * @param url/* www  . j  av a2  s  .c  o m*/
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);

    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }

    return connection;
}

From source file:com.tc.util.io.ServerURL.java

private static void tweakSecureConnectionSettings(URLConnection urlConnection) {
    HttpsURLConnection sslUrlConnection;

    try {//  w  w w  .j  av a 2s . c  o  m
        sslUrlConnection = (HttpsURLConnection) urlConnection;
    } catch (ClassCastException e) {
        throw new IllegalStateException("Unable to cast " + urlConnection
                + " to javax.net.ssl.HttpsURLConnection. "
                + "Options tc.ssl.trustAllCerts and tc.ssl.disableHostnameVerifier are causing this issue.", e);
    }

    if (DISABLE_HOSTNAME_VERIFIER) {
        // don't verify hostname
        sslUrlConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
    }

    TrustManager[] trustManagers = null;
    if (TRUST_ALL_CERTS) {
        // trust all certs
        trustManagers = new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
                //
            }

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

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

    try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagers, null);
        sslUrlConnection.setSSLSocketFactory(sslContext.getSocketFactory());
    } catch (Exception e) {
        throw new RuntimeException("unable to create SSL connection from " + urlConnection.getURL(), e);
    }
}