Example usage for javax.net.ssl SSLHandshakeException printStackTrace

List of usage examples for javax.net.ssl SSLHandshakeException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.framework.testcase.testrail.APIClient.java

private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException {
    URL url = new URL(this.m_url + uri);

    // Create the connection object and set the required HTTP method
    // (GET/POST) and headers (content type and basic auth).
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.addRequestProperty("Content-Type", "application/json");

    String auth = getAuthorization(this.m_user, this.m_password);
    conn.addRequestProperty("Authorization", "Basic " + auth);

    if (method.equalsIgnoreCase("POST")) {
        // Add the POST arguments, if any. We just serialize the passed
        // data object (i.e. a dictionary) and then add it to the
        // request body.
        if (data != null) {
            byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8");

            conn.setDoOutput(true);//  w  w w.  j ava  2  s. co m
            OutputStream ostream = conn.getOutputStream();
            ostream.write(block);
            ostream.flush();
        }
    }

    // Execute the actual web request (if it wasn't already initiated
    // by getOutputStream above) and record any occurred errors (we use
    // the error stream in this case).
    int status = 0;
    try {
        status = conn.getResponseCode();
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        System.err.println("the request is timeout from the server ,we quite the test");

    } catch (SSLHandshakeException ex) {
        ex.printStackTrace();
        System.err.println("the request is  Remote host closed connection during handshake");
    }

    InputStream istream;
    if (status != 200) {
        istream = conn.getErrorStream();
        if (istream == null) {

            new Exception("TestRail API return HTTP " + status + " (No additional error message received)");

        }
    } else {
        istream = conn.getInputStream();
    }

    // Read the response body, if any, and deserialize it from JSON.
    String text = "";
    if (istream != null) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8"));

        String line;
        while ((line = reader.readLine()) != null) {
            text += line;
            text += System.getProperty("line.separator");
        }

        reader.close();
    }

    Object result;
    if (text != "") {
        result = JSONValue.parse(text);
    } else {
        result = new JSONObject();
    }

    // Check for any occurred errors and add additional details to
    // the exception message, if any (e.g. the error message returned
    // by TestRail).
    if (status != 200) {
        String error = "No additional error message received";
        if (result != null && result instanceof JSONObject) {
            JSONObject obj = (JSONObject) result;
            if (obj.containsKey("error")) {
                error = '"' + (String) obj.get("error") + '"';
            }
        }

        new Exception("TestRail API returned HTTP " + status + "(" + error + ")");
    }

    return result;
}

From source file:com.rastating.droidbeard.net.SickbeardAsyncTask.java

protected String getJson(String cmd, List<Pair<String, Object>> params) {
    String uri = null;//from w  w  w .j av a2 s.  co m
    String body = null;
    String format = "%sapi/%s/?cmd=%s";
    Preferences preferences = new Preferences(mContext);
    HttpClient client = HttpClientManager.INSTANCE.getClient();

    uri = String.format(format, preferences.getSickbeardUrl(), preferences.getApiKey(), cmd);
    if (params != null) {
        for (Pair<String, Object> pair : params) {
            uri += "&" + pair.first + "=" + pair.second.toString();
        }
    }

    try {
        HttpGet request = new HttpGet(uri);
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();

        if (status.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            HttpEntity entity = response.getEntity();
            entity.writeTo(stream);
            stream.close();
            entity.consumeContent();
            body = stream.toString();
            stream.close();
        } else {
            HttpEntity entity = response.getEntity();
            entity.getContent().close();
            entity.consumeContent();
            throw new IOException(status.getReasonPhrase());
        }
    } catch (SSLHandshakeException e) {
        setLastException("", e);
        return null;
    } catch (Exception e) {
        setLastException("", e);
        e.printStackTrace();
        return null;
    }

    return body;
}

From source file:com.foundstone.certinstaller.CertInstallerActivity.java

/**
 * Tests the certificate chain by making a connection with or without the
 * proxy to the specified URL//  www.j a  va  2 s  .  c  o  m
 * 
 * @param urlString
 * @param proxyIP
 * @param proxyPort
 */
private void testCertChain(final String urlString, final String proxyIP, final String proxyPort) {

    mCaCertInstalled = false;
    mSiteCertInstalled = false;

    if (TextUtils.isEmpty(urlString)) {
        Toast.makeText(getApplicationContext(), "URL is not set", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "URL is not set");
        return;
    }
    pd = ProgressDialog.show(CertInstallerActivity.this, "Testing the cert chain", "", true, false, null);

    new AsyncTask<Void, Void, Void>() {
        @Override
        protected Void doInBackground(Void... params) {

            Log.d(TAG, "[+] Starting HTTPS request...");

            HttpsURLConnection urlConnection = null;

            try {
                Log.d(TAG, "[+] Set URL...");
                URL url = new URL("https://" + urlString);

                Log.d(TAG, "[+] Open Connection...");

                // The user could have ProxyDroid running
                if (!TextUtils.isEmpty(proxyIP) && !TextUtils.isEmpty(proxyPort)) {
                    Log.d(TAG, "[+] Using proxy " + proxyIP + ":" + proxyPort);
                    Proxy proxy = new Proxy(Type.HTTP,
                            new InetSocketAddress(proxyIP, Integer.parseInt(proxyPort)));
                    urlConnection = (HttpsURLConnection) url.openConnection(proxy);
                } else {
                    urlConnection = (HttpsURLConnection) url.openConnection();
                }
                urlConnection.setReadTimeout(15000);

                Log.d(TAG, "[+] Get the input stream...");
                InputStream in = urlConnection.getInputStream();
                Log.d(TAG, "[+] Create a buffered reader to read the response...");
                BufferedReader reader = new BufferedReader(new InputStreamReader(in));

                final StringBuilder builder = new StringBuilder();

                String line = null;
                Log.d(TAG, "[+] Read all of the return....");
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                mResult = builder.toString();

                Log.d(TAG, mResult);

                // If everything passed we set these both to true
                mCaCertInstalled = true;
                mSiteCertInstalled = true;

                // Catch when the CA doesn't exist
                // Error: javax.net.ssl.SSLHandshakeException:
                // java.security.cert.CertPathValidatorException: Trust
                // anchor for certification path not found
            } catch (SSLHandshakeException e) {

                e.printStackTrace();

                // Catch when the hostname does not verify
                // Line 224ish
                // http://source-android.frandroid.com/libcore/luni/src/main/java/libcore/net/http/HttpConnection.java
                // http://docs.oracle.com/javase/1.4.2/docs/api/javax/net/ssl/HostnameVerifier.html#method_detail
            } catch (IOException e) {

                // Found the CA cert installed but not the site cert
                mCaCertInstalled = true;
                e.printStackTrace();
            } catch (Exception e) {
                Log.d(TAG, "[-] Some other exception: " + e.getMessage());
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {

            pd.dismiss();
            if (mCaCertInstalled && !mSiteCertInstalled) {
                Log.d(TAG, Boolean.toString(mCaCertInstalled));
                Toast.makeText(getApplicationContext(), "Found the CA cert installed", Toast.LENGTH_SHORT)
                        .show();
                setCaTextInstalled();
                setSiteTextNotInstalled();
                setFullTextNotInstalled();
            } else if (mCaCertInstalled && mSiteCertInstalled) {
                Toast.makeText(getApplicationContext(), "Found the CA and Site certs installed",
                        Toast.LENGTH_SHORT).show();
                setCaTextInstalled();
                setSiteTextInstalled();
                setFullTextInstalled();
            } else {
                Toast.makeText(getApplicationContext(), "No Certificates were found installed",
                        Toast.LENGTH_SHORT).show();
                setCaTextNotInstalled();
                setSiteTextNotInstalled();
                setFullTextNotInstalled();
            }
            super.onPostExecute(result);

        }

    }.execute();

}

From source file:com.floragunn.searchguard.ssl.SSLTest.java

@Test
public void testHttpsEnforceFail() throws Exception {

    enableHTTPClientSSL = true;//  www .  j a  v a2s.c o  m
    trustHTTPServerCertificate = true;
    sendHTTPClientCertificate = false;

    final Settings settings = Settings.settingsBuilder().put("searchguard.ssl.transport.enabled", false)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_TRANSPORT_ENABLE_OPENSSL_IF_AVAILABLE, allowOpenSSL)
            .put(SSLConfigConstants.SEARCHGUARD_SSL_HTTP_KEYSTORE_ALIAS, "node-0")
            .put("searchguard.ssl.http.enabled", true).put("searchguard.ssl.http.clientauth_mode", "REQUIRE")
            .put("searchguard.ssl.http.keystore_filepath",
                    getAbsoluteFilePathFromClassPath("node-0-keystore.jks"))
            .put("searchguard.ssl.http.truststore_filepath", getAbsoluteFilePathFromClassPath("truststore.jks"))
            .build();

    startES(settings);
    try {
        executeSimpleRequest("");
        Assert.fail();
    } catch (SSLHandshakeException e) {
        //expected
        System.out.println("Expected SSLHandshakeException " + e.toString());
    } catch (SocketException e) {
        //expected
        System.out.println("Expected SocketException " + e.toString());
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail("Unexpected exception " + e.toString());
    }
}