Search in sources :

Example 11 with KeyManagementException

use of java.security.KeyManagementException in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method getMediaIds.

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";
    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();
            // generate authorization header
            String get_or_post = "POST";
            String oauth_signature_method = "HMAC-SHA1";
            String uuid_string = UUID.randomUUID().toString();
            uuid_string = uuid_string.replaceAll("-", "");
            // any relatively random alphanumeric string will work here
            String oauth_nonce = uuid_string;
            // get the timestamp
            Calendar tempcal = Calendar.getInstance();
            // get current time in milliseconds
            long ts = tempcal.getTimeInMillis();
            // then divide by 1000 to get seconds
            String oauth_timestamp = (new Long(ts / 1000)).toString();
            // the parameter string must be in alphabetical order, "text" parameter added at end
            String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);
            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.json";
            String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
            String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));
            String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
            new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
            new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext(null);
            HttpHost host = new HttpHost(twitter_endpoint_host, 443);
            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
            try {
                try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket, params);
                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();
                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);
                    request2.setEntity(reqEntity);
                    request2.setParams(params);
                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println("Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message", jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code", jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }
                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }
                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message", "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message", "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message", "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }
    }
    return ids;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) FileBody(org.apache.http.entity.mime.content.FileBody) Calendar(java.util.Calendar) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) JSONObject(org.json.JSONObject) File(java.io.File) Socket(java.net.Socket)

Example 12 with KeyManagementException

use of java.security.KeyManagementException in project k-9 by k9mail.

the class WebDavStore method getHttpClient.

public WebDavHttpClient getHttpClient() throws MessagingException {
    if (httpClient == null) {
        httpClient = httpClientFactory.create();
        // Disable automatic redirects on the http client.
        httpClient.getParams().setBooleanParameter("http.protocol.handle-redirects", false);
        // Setup a cookie store for forms-based authentication.
        httpContext = new BasicHttpContext();
        authCookies = new BasicCookieStore();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, authCookies);
        SchemeRegistry reg = httpClient.getConnectionManager().getSchemeRegistry();
        try {
            Scheme s = new Scheme("https", new WebDavSocketFactory(hostname, 443), 443);
            reg.register(s);
        } catch (NoSuchAlgorithmException nsa) {
            Log.e(LOG_TAG, "NoSuchAlgorithmException in getHttpClient: " + nsa);
            throw new MessagingException("NoSuchAlgorithmException in getHttpClient: " + nsa);
        } catch (KeyManagementException kme) {
            Log.e(LOG_TAG, "KeyManagementException in getHttpClient: " + kme);
            throw new MessagingException("KeyManagementException in getHttpClient: " + kme);
        }
    }
    return httpClient;
}
Also used : BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Scheme(org.apache.http.conn.scheme.Scheme) MessagingException(com.fsck.k9.mail.MessagingException) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) SchemeRegistry(org.apache.http.conn.scheme.SchemeRegistry) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException)

Example 13 with KeyManagementException

use of java.security.KeyManagementException in project scdl by passy.

the class HttpRequest method applyTrustManager.

/**
	 * Set up one or multiple trust managers for this connection. Does nothing
	 * if the current request is no SSL connection.
	 * 
	 * @param manager
	 * @return this instance.
	 */
public HttpRequest applyTrustManager(final TrustManager[] trustManagers) {
    if (!(connection instanceof HttpsURLConnection)) {
        return this;
    }
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
    } catch (final NoSuchAlgorithmException e) {
        // Again, should not happen if I didn't type it wrong.
        throw new IllegalArgumentException(e);
    }
    try {
        sslContext.init(null, trustManagers, null);
    } catch (final KeyManagementException e) {
        throw new IllegalStateException(e);
    }
    ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
    return this;
}
Also used : SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpsURLConnection(javax.net.ssl.HttpsURLConnection) KeyManagementException(java.security.KeyManagementException)

Example 14 with KeyManagementException

use of java.security.KeyManagementException in project robovm by robovm.

the class IdentityTest method testAddCertificate1.

/**
     * verify addCertificate(Certificate certificate) adds a certificate for this identity.
     * If the identity has a public key, the public key in the certificate must be the same
     *
     */
public void testAddCertificate1() throws Exception {
    Identity i = new IdentityStub("iii");
    PublicKeyStub pk1 = new PublicKeyStub("kkk", "fff", new byte[] { 1, 2, 3, 4, 5 });
    i.setPublicKey(pk1);
    // try with the same key
    CertificateStub c1 = new CertificateStub("fff", null, null, pk1);
    i.addCertificate(c1);
    assertSame(c1, i.certificates()[0]);
    // try Certificate with different key
    try {
        i.addCertificate(new CertificateStub("ccc", null, null, new PublicKeyStub("k2", "fff", new byte[] { 6, 7, 8, 9, 0 })));
        fail("KeyManagementException should be thrown");
    } catch (KeyManagementException ok) {
    }
}
Also used : IdentityStub(org.apache.harmony.security.tests.support.IdentityStub) CertificateStub(org.apache.harmony.security.tests.support.CertificateStub) PublicKeyStub(org.apache.harmony.security.tests.support.PublicKeyStub) Identity(java.security.Identity) KeyManagementException(java.security.KeyManagementException)

Example 15 with KeyManagementException

use of java.security.KeyManagementException in project robovm by robovm.

the class IdentityTest method testAddCertificate4.

/**
     * verify addCertificate(Certificate certificate) throws KeyManagementException if certificate is null
     */
public void testAddCertificate4() throws Exception {
    try {
        new IdentityStub("aaa").addCertificate(null);
        fail("KeyManagementException should be thrown");
    } catch (KeyManagementException ok) {
    } catch (NullPointerException ok) {
    }
}
Also used : IdentityStub(org.apache.harmony.security.tests.support.IdentityStub) KeyManagementException(java.security.KeyManagementException)

Aggregations

KeyManagementException (java.security.KeyManagementException)132 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)86 SSLContext (javax.net.ssl.SSLContext)65 KeyStoreException (java.security.KeyStoreException)43 TrustManager (javax.net.ssl.TrustManager)39 IOException (java.io.IOException)38 CertificateException (java.security.cert.CertificateException)23 X509TrustManager (javax.net.ssl.X509TrustManager)22 SecureRandom (java.security.SecureRandom)21 X509Certificate (java.security.cert.X509Certificate)19 UnrecoverableKeyException (java.security.UnrecoverableKeyException)18 KeyManager (javax.net.ssl.KeyManager)18 TrustManagerFactory (javax.net.ssl.TrustManagerFactory)16 KeyStore (java.security.KeyStore)13 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)13 KeyManagerFactory (javax.net.ssl.KeyManagerFactory)10 HostnameVerifier (javax.net.ssl.HostnameVerifier)9 NoSuchProviderException (java.security.NoSuchProviderException)7 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)7 SSLSocket (javax.net.ssl.SSLSocket)7