Example usage for java.security GeneralSecurityException printStackTrace

List of usage examples for java.security GeneralSecurityException printStackTrace

Introduction

In this page you can find the example usage for java.security GeneralSecurityException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:com.android.volley.toolbox.https.SslHttpClient.java

@Override
protected ClientConnectionManager createClientConnectionManager() {
    SchemeRegistry registry = new SchemeRegistry();

    PlainSocketFactory pfs = PlainSocketFactory.getSocketFactory();
    Scheme s = new Scheme(HTTP_SCHEME, pfs, HTTP_DEFAULT_PORT);
    registry.register(s);//w w  w . ja  v  a 2 s.com

    ThreadSafeClientConnManager ret = null;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        registry.register(new Scheme(HTTP_SSL_SCHEME, sf, mHttpsPort));

        ret = new ThreadSafeClientConnManager(new BasicHttpParams(), registry);
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return ret;
}

From source file:com.mytwitter.retrofit.RetrofitRequestInterceptor2.java

License:asdf

@Override
public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();

    TwitterSession session = Twitter.getSessionManager().getActiveSession();
    TwitterAuthToken authToken = session.getAuthToken();

    String oauth_signature_method = "HMAC-SHA1";
    String oauth_consumer_key = "TMr0RTusaWKrhnsTjRHpKqfBA";
    String oauth_token = authToken.token;
    String uuid_string = UUID.randomUUID().toString();
    uuid_string = uuid_string.replaceAll("-", "");
    String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here. I used UUID minus "-" signs
    Date now = Calendar.getInstance().getTime();
    String oauth_timestamp = (new Long(now.getTime() / 1000)).toString(); // get current time in milliseconds, then divide by 1000 to get seconds
    // I'm not using a callback value. Otherwise, you'd need to include it in the parameter string like the example above
    // the parameter string must be in alphabetical order
    String parameter_string = "oauth_consumer_key=" + oauth_consumer_key + "&oauth_nonce=" + oauth_nonce
            + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp
            + "&oauth_version=1.0";
    System.out.println("parameter_string=" + parameter_string);
    String signature_base_string = "GET&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fhome_timeline.json&"
            + URLEncoder.encode(parameter_string, "UTF-8");
    System.out.println("signature_base_string=" + signature_base_string);
    String oauth_signature = "";

    try {// w  ww  .  j  a v a 2  s .  co m
        oauth_signature = computeSignature(signature_base_string, "3yasdfasmyconsumersecretfasd53&"); // note the & at the end. Normally the user access_token would go here, but we don't know it yet for request_token
        System.out.println("oauth_signature=" + URLEncoder.encode(oauth_signature, "UTF-8"));
    } catch (GeneralSecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    /*String authorization_header_string =
        " oauth_consumer_key=\"" + oauth_consumer_key+
        "\", oauth_nonce=\"" + oauth_nonce +
        "\", oauth_signature=\""+URLEncoder.encode(oauth_signature, "UTF-8")+ "\""+
        " oauth_signature_method=\"HMAC-SHA1\""+
        "\", oauth_timestamp=\""+ oauth_timestamp +
        "\", oauth_token=\""+oauth_token+
                "\" OAuth oauth_version=\"1.0\"";*/

    String authorization_header_string = "OAuth oauth_version=\"1.0\","
            + " oauth_signature_method=\"HMAC-SHA1\"" + ", oauth_nonce=\"" + oauth_nonce
            + "\", oauth_timestamp=\"" + oauth_timestamp + "\", oauth_consumer_key=\"" + oauth_consumer_key
            + "\", oauth_token=\"" + oauth_token + "\", oauth_signature=\""
            + URLEncoder.encode(oauth_signature, "UTF-8") + "\"";

    /*String authorization_header_string="OAuth oauth_version=\"1.0\","+
        " oauth_signature_method=\"HMAC-SHA1\""+
        ", oauth_nonce=\"" + oauth_nonce +
        "\", oauth_timestamp=\""+ oauth_timestamp +
        "\", oauth_consumer_key=\"" + oauth_consumer_key+
        "\", oauth_token=\""+oauth_token+
        "\", oauth_signature=\""+URLEncoder.encode(oauth_signature, "UTF-8")+ "\"";*/

    //String authorization_header_string = "OAuth oauth_consumer_key=\"" + oauth_consumer_key + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" +
    //oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + URLEncoder.encode(oauth_signature, "UTF-8") + "\"";

    System.out.println("authorization_header_string=" + authorization_header_string);

    // Customize the request
    Request request = original.newBuilder().header("Accept", "application/json")
            .header("Authorization", authorization_header_string).method(original.method(), original.body())
            .build();

    Response response = chain.proceed(request);

    // Customize or return the response
    return response;
}

From source file:org.iso.mpeg.dash.crypto.ContentProtectionMpegDashSea.java

/**
 * Helper to encrypt/decrypt the input segment (URL) to output segment (file)
 *  //from  www .  j  a va 2s . c o m
 * @param inputSegment
 * @param outputSegment
 * @param segmentNum
 * @param encrypt
 * @throws DashCryptoException
 * @throws IOException
 */
private void baselineCryptSegmentHelper(InputStream inputSegment, File outputSegment, long segmentNum,
        boolean encrypt) throws DashCryptoException, IOException {
    // determine which CryptoPeriod owns this segment (if any)
    CryptoPeriod relevantCryptoPeriod = cryptoPeriodForSegmentNumber(segmentNum);
    if (relevantCryptoPeriod != null) { // got info to encrypt/decrypt segment
        // fetch key via any KeySystem
        byte[] key = null;
        String keyUri = relevantCryptoPeriod.getKeyUri(segmentNum);
        for (Iterator<KeySystem> it = keySystems.iterator(); it.hasNext() && key == null;) {
            KeySystem keySys = it.next();
            try {
                key = keySys.retrieveKey(keyUri);
            } catch (DashCryptoException dce) { // print a warning and skip to the next key system   
                System.out.println("WARNING: KeySystem \"" + keySys.getKeySystemUri()
                        + "\" cannot retrieve key at URI \"" + keyUri + "\": " + dce.getMessage());
            }
        }
        if (key == null)
            throw new DashCryptoException("Error: none of the available key systems could retrieve the key");

        // fetch or calculate iv
        byte[] iv = null;
        String ivUri = null;
        if (relevantCryptoPeriod.getIV() != null) // IV explicitly provided
            iv = relevantCryptoPeriod.getIV();
        else if ((ivUri = relevantCryptoPeriod.getIvUri(segmentNum)) != null) { // fetch IV
            InputSource ivInputSource = Util.inputSourceFromPath(ivUri);
            iv = IOUtils.toByteArray(ivInputSource.getInputStream());
        } else // derive IV from the segment number
            iv = segmentEncryption.deriveIvFromSegmentNumber(key, segmentNum);

        try {
            segmentEncryption.Crypt(inputSegment, outputSegment, key, iv, encrypt);
        } catch (GeneralSecurityException gse) {
            gse.printStackTrace();
            throw new DashCryptoException(gse);
        }
    } else { // just copy clear-text segments in pass-thru mode
        FileUtils.copyInputStreamToFile(inputSegment, outputSegment);
        System.out.println("INFO: Segment #" + segmentNum + " has no corresponding cryptoperiod, so passed "
                + "through to \"" + outputSegment.getAbsolutePath() + "\" verbatim"
                + (encrypt ? " (unencrypted)" : ""));
    }
}

From source file:org.mitre.jwt.signer.impl.RsaSigner.java

/**
 * Load the public and private keys from the keystore, identified with the configured alias and accessed with the configured password.
 * @throws GeneralSecurityException//from  w  w w  .ja v  a  2  s. c o m
 */
private void loadKeysFromKeystore() {
    Assert.notNull(keystore, "An keystore must be supplied");
    Assert.notNull(alias, "A alias must be supplied");
    Assert.notNull(password, "A password must be supplied");

    KeyPair keyPair = null;
    try {
        keyPair = keystore.getKeyPairForAlias(alias, password);
    } catch (GeneralSecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    Assert.notNull(keyPair, "Either alias and/or password is not correct for keystore");

    publicKey = keyPair.getPublic();
    privateKey = keyPair.getPrivate();
}

From source file:org.getobjects.appserver.core.WOHTTPConnection.java

/**
 * (GETobjects extension):// ww  w.j  a va  2 s. co m
 * Called, whenever a new urlConnection is setup and only if it's a
 * HttpsURLConnection.
 *
 * This method is called in addition to
 * setupHttpURLConnection() and should contain refinement necessary for
 * SSL purposes, only.
 *
 * Subclasses may override or extend the steps taken.
 */
protected void setupHttpsURLConnection(HttpsURLConnection _conn) {
    _conn.setHostnameVerifier(this);

    if (this.allowInsecureSSL) {
        try {
            _conn.setSSLSocketFactory(new GullibleSSLSocketFactory(null));
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }
}

From source file:org.jvnet.hudson.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *///from   ww w  .j  av  a  2s  .  c o  m
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        X509Certificate c = loadCertificate(cf, f);
        c.checkValidity(new Date(System.currentTimeMillis() + TimeUnit.DAYS.toMillis(30)));
        certs.add(c);
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    rootCAs.add(new TrustAnchor(
            (X509Certificate) cf.generateCertificate(getClass().getResourceAsStream("/hudson-community.cert")),
            null));
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:org.jenkins_ci.update_center.Main.java

/**
 * Loads a certificate chain and makes sure it's valid.
 *///from   w w w  .j av a 2  s  . c om
protected List<X509Certificate> getCertificateChain() throws IOException, GeneralSecurityException {
    CertificateFactory cf = CertificateFactory.getInstance("X509");
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    for (File f : certificates) {
        certs.add(loadCertificate(cf, f));
    }

    Set<TrustAnchor> rootCAs = CertificateUtil.getDefaultRootCAs();
    InputStream stream = getClass().getResourceAsStream("/hudson-community.cert");
    try {
        rootCAs.add(new TrustAnchor((X509Certificate) cf.generateCertificate(stream), null));
    } finally {
        IOUtils.closeQuietly(stream);
    }
    for (File f : rootCA) {
        rootCAs.add(new TrustAnchor(loadCertificate(cf, f), null));
    }

    try {
        CertificateUtil.validatePath(certs, rootCAs);
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
    }
    return certs;
}

From source file:com.truebanana.http.HTTPRequest.java

/**
 * Executes this {@link HTTPRequest} asynchronously. To hook to events or listen to the server response, you must provide an {@link HTTPResponseListener} using {@link HTTPRequest#setHTTPResponseListener(HTTPResponseListener)}.
 *
 * @return This {@link HTTPRequest}/*from ww w  . j  av a  2s. com*/
 */
public HTTPRequest executeAsync() {
    Async.executeAsync(new Runnable() {
        @Override
        public void run() {
            HttpURLConnection urlConnection = buildURLConnection();

            // Get request body now if there's a provider
            if (bodyProvider != null) {
                body = bodyProvider.getRequestBody();
            }

            // Update socket factory as needed
            if (urlConnection instanceof HttpsURLConnection) {
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection) urlConnection;

                try {
                    httpsURLConnection.setSSLSocketFactory(new FlexibleSSLSocketFactory(trustStore,
                            trustStorePassword, keyStore, keyStorePassword, !verifySSL));
                } catch (GeneralSecurityException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.SECURITY_EXCEPTION);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.KEYSTORE_INVALID);
                    onRequestTerminated();
                    return; // Terminate now
                }

                if (!verifySSL) {
                    httpsURLConnection.setHostnameVerifier(new NoVerifyHostnameVerifier());
                    log("SSL Verification Disabled", "**********");
                }
            }

            log("Endpoint", urlConnection.getURL().toString());
            Iterator<Map.Entry<String, String>> iterator = headers.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> pair = (Map.Entry) iterator.next();
                urlConnection.addRequestProperty(pair.getKey(), pair.getValue());
                log("Request Header", pair.getKey() + ": " + pair.getValue());
            }
            if (multiPartContent != null) {
                log("Multipart Request Boundary", multiPartContent.getBoundary());
                int counter = 1;
                for (MultiPartContent.Part part : multiPartContent.getParts()) {
                    log("Request Body Part " + counter,
                            "Name: " + part.getName() + "; File Name: " + part.getFileName());

                    Iterator<Map.Entry<String, String>> it = part.getHeaders().entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> pair = (Map.Entry) it.next();
                        log("Request Body Part " + counter + " Header", pair.getKey() + ": " + pair.getValue());
                    }
                }
            } else {
                log("Request Body", body);
            }

            if (mockResponse == null) {
                // Trigger pre-execute since preparations are complete
                onPreExecute();

                // Write our request body
                try {
                    if (multiPartContent != null) {
                        multiPartContent.write(urlConnection.getOutputStream());
                    } else if (body != null) {
                        OutputStream os = urlConnection.getOutputStream();
                        OutputStreamWriter writer = new OutputStreamWriter(os);
                        writer.write(body);
                        writer.flush();
                        writer.close();
                        os.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Get the response
                InputStream content;
                try {
                    content = urlConnection.getInputStream();
                    onPostExecute();
                } catch (SocketTimeoutException e) { // Timeout
                    e.printStackTrace();
                    onPostExecute();
                    onRequestError(HTTPRequestError.TIMEOUT);
                    onRequestTerminated();
                    return; // Terminate now
                } catch (IOException e) { // All other exceptions
                    e.printStackTrace();
                    content = urlConnection.getErrorStream();
                    onPostExecute();
                }

                // Pre-process the response
                final HTTPResponse response = HTTPResponse.from(HTTPRequest.this, urlConnection, content);

                if (response.isConnectionError()) {
                    onRequestError(HTTPRequestError.OTHER);
                    onRequestTerminated();
                    return; // Terminate now
                }

                // Log response
                log("Response Message", response.getResponseMessage());
                log("Response Content", response.getStringContent());

                // Trigger request completed and return the response
                onRequestCompleted(response);

                // Terminate the connection
                urlConnection.disconnect();

                onRequestTerminated();
            } else {
                onPreExecute();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                onPostExecute();
                log("Response Message", mockResponse.getResponseMessage());
                log("Response Content", mockResponse.getStringContent());
                onRequestCompleted(mockResponse);
                urlConnection.disconnect();
                onRequestTerminated();
            }
        }
    });
    return this;
}

From source file:org.opennms.netmgt.alarmd.northbounder.http.HttpNorthbounder.java

@Override
public void forwardAlarms(List<NorthboundAlarm> alarms) throws NorthbounderException {
    LOG.info("Forwarding {} alarms", alarms.size());

    //Need a configuration bean for these

    int connectionTimeout = 3000;
    int socketTimeout = 3000;
    Integer retryCount = Integer.valueOf(3);

    URI uri = m_config.getURI();/*from  w w  w  .j av a  2 s  .  com*/

    final HttpClientWrapper clientWrapper = HttpClientWrapper.create().setConnectionTimeout(connectionTimeout)
            .setSocketTimeout(socketTimeout).setRetries(retryCount).useBrowserCompatibleCookies();

    if (m_config.getVirtualHost() != null && !m_config.getVirtualHost().trim().isEmpty()) {
        clientWrapper.setVirtualHost(m_config.getVirtualHost());
    }
    if (m_config.getUserAgent() != null && !m_config.getUserAgent().trim().isEmpty()) {
        clientWrapper.setUserAgent(m_config.getUserAgent());
    }

    if ("https".equals(uri.getScheme())) {
        try {
            clientWrapper.useRelaxedSSL("https");
        } catch (final GeneralSecurityException e) {
            throw new NorthbounderException("Failed to configure HTTP northbounder for relaxed SSL.", e);
        }
    }

    HttpUriRequest method = null;

    if (HttpMethod.POST == (m_config.getMethod())) {
        HttpPost postMethod = new HttpPost(uri);

        //TODO: need to configure these
        List<NameValuePair> postParms = new ArrayList<NameValuePair>();

        //FIXME:do this for now
        NameValuePair p = new BasicNameValuePair("foo", "bar");
        postParms.add(p);

        try {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postParms, "UTF-8");
            postMethod.setEntity(entity);
        } catch (UnsupportedEncodingException e) {
            throw new NorthbounderException(e);
        }

        HttpEntity entity = null;
        try {
            //I have no idea what I'm doing here ;)
            entity = new StringEntity("XML HERE");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        postMethod.setEntity(entity);

        method = postMethod;
    } else if (HttpMethod.GET == m_config.getMethod()) {

        //TODO: need to configure these
        //List<NameValuePair> getParms = null;
        method = new HttpGet(uri);
    }
    HttpVersion httpVersion = determineHttpVersion(m_config.getHttpVersion());
    clientWrapper.setVersion(httpVersion);

    HttpResponse response = null;
    try {
        response = clientWrapper.execute(method);

        int code = response.getStatusLine().getStatusCode();
        HttpResponseRange range = new HttpResponseRange("200-399");
        if (!range.contains(code)) {
            LOG.debug("response code out of range for uri:{}.  Expected {} but received {}", uri, range, code);
            throw new NorthbounderException("response code out of range for uri:" + uri + ".  Expected " + range
                    + " but received " + code);
        }
        LOG.debug("HTTP Northbounder received response: {}", response.getStatusLine().getReasonPhrase());
    } catch (final ClientProtocolException e) {
        throw new NorthbounderException(e);
    } catch (final IOException e) {
        throw new NorthbounderException(e);
    } finally {
        IOUtils.closeQuietly(clientWrapper);
    }
}

From source file:com.mario22gmail.license.nfc_project.NavigationDrawerActivity.java

public void CreateApplicationButton(View view) {
    if (card != null) {
        try {/*w  w w  .ja v a  2  s.com*/
            DesFireCreateApplication(card, 2);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            Log.i(nfcDebugTag, "Create app security error" + e.getMessage());
        } catch (IOException e) {
            e.printStackTrace();
            Log.i(nfcDebugTag, "Create app io error" + e.getMessage());

        } catch (SmartCardException e) {
            e.printStackTrace();
            Log.i(nfcDebugTag, "Create app smart card error" + e.getMessage());

        }
    }
}