Search in sources :

Example 21 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory 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 22 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project k-9 by k9mail.

the class TestTrustedSocketFactory method createSocket.

@Override
public Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException {
    TrustManager[] trustManagers = new TrustManager[] { new VeryTrustingTrustManager() };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, trustManagers, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
    return sslSocketFactory.createSocket(socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
}
Also used : SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) TrustManager(javax.net.ssl.TrustManager)

Example 23 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project k-9 by k9mail.

the class DefaultTrustedSocketFactory method createSocket.

public Socket createSocket(Socket socket, String host, int port, String clientCertificateAlias) throws NoSuchAlgorithmException, KeyManagementException, MessagingException, IOException {
    TrustManager[] trustManagers = new TrustManager[] { TrustManagerFactory.get(host, port) };
    KeyManager[] keyManagers = null;
    if (!TextUtils.isEmpty(clientCertificateAlias)) {
        keyManagers = new KeyManager[] { new KeyChainKeyManager(context, clientCertificateAlias) };
    }
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagers, trustManagers, null);
    SSLSocketFactory socketFactory = sslContext.getSocketFactory();
    Socket trustedSocket;
    if (socket == null) {
        trustedSocket = socketFactory.createSocket();
    } else {
        trustedSocket = socketFactory.createSocket(socket, host, port, true);
    }
    SSLSocket sslSocket = (SSLSocket) trustedSocket;
    hardenSocket(sslSocket);
    setSniHost(socketFactory, sslSocket, host);
    return trustedSocket;
}
Also used : SSLSocket(javax.net.ssl.SSLSocket) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) KeyManager(javax.net.ssl.KeyManager) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) TrustManager(javax.net.ssl.TrustManager)

Example 24 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project java-apns by notnoop.

the class ApnsServiceBuilder method build.

/**
     * Returns a fully initialized instance of {@link ApnsService},
     * according to the requested settings.
     *
     * @return  a new instance of ApnsService
     */
public ApnsService build() {
    checkInitialization();
    ApnsService service;
    SSLSocketFactory sslFactory = sslContext.getSocketFactory();
    ApnsFeedbackConnection feedback = new ApnsFeedbackConnection(sslFactory, feedbackHost, feedbackPort, proxy, readTimeout, connectTimeout, proxyUsername, proxyPassword);
    ApnsConnection conn = new ApnsConnectionImpl(sslFactory, gatewayHost, gatewayPort, proxy, proxyUsername, proxyPassword, reconnectPolicy, delegate, errorDetection, errorDetectionThreadFactory, cacheLength, autoAdjustCacheLength, readTimeout, connectTimeout);
    if (pooledMax != 1) {
        conn = new ApnsPooledConnection(conn, pooledMax, executor);
    }
    service = new ApnsServiceImpl(conn, feedback);
    if (isQueued) {
        service = new QueuedApnsService(service, queueThreadFactory);
    }
    if (isBatched) {
        service = new BatchApnsService(conn, feedback, batchWaitTimeInSec, batchMaxWaitTimeInSec, batchThreadPoolExecutor);
    }
    service.start();
    return service;
}
Also used : ApnsPooledConnection(com.notnoop.apns.internal.ApnsPooledConnection) ApnsConnectionImpl(com.notnoop.apns.internal.ApnsConnectionImpl) QueuedApnsService(com.notnoop.apns.internal.QueuedApnsService) BatchApnsService(com.notnoop.apns.internal.BatchApnsService) ApnsConnection(com.notnoop.apns.internal.ApnsConnection) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) ApnsFeedbackConnection(com.notnoop.apns.internal.ApnsFeedbackConnection) ApnsServiceImpl(com.notnoop.apns.internal.ApnsServiceImpl) QueuedApnsService(com.notnoop.apns.internal.QueuedApnsService) BatchApnsService(com.notnoop.apns.internal.BatchApnsService)

Example 25 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project java-apns by notnoop.

the class ApnsConnectionImpl method getOrCreateSocket.

private synchronized Socket getOrCreateSocket(boolean resend) throws NetworkIOException {
    if (reconnectPolicy.shouldReconnect()) {
        logger.debug("Reconnecting due to reconnectPolicy dictating it");
        Utilities.close(socket);
        socket = null;
    }
    if (socket == null || socket.isClosed()) {
        try {
            if (proxy == null) {
                socket = factory.createSocket(host, port);
                logger.debug("Connected new socket {}", socket);
            } else if (proxy.type() == Proxy.Type.HTTP) {
                TlsTunnelBuilder tunnelBuilder = new TlsTunnelBuilder();
                socket = tunnelBuilder.build((SSLSocketFactory) factory, proxy, proxyUsername, proxyPassword, host, port);
                logger.debug("Connected new socket through http tunnel {}", socket);
            } else {
                boolean success = false;
                Socket proxySocket = null;
                try {
                    proxySocket = new Socket(proxy);
                    proxySocket.connect(new InetSocketAddress(host, port), connectTimeout);
                    socket = ((SSLSocketFactory) factory).createSocket(proxySocket, host, port, false);
                    success = true;
                } finally {
                    if (!success) {
                        Utilities.close(proxySocket);
                    }
                }
                logger.debug("Connected new socket through socks tunnel {}", socket);
            }
            socket.setSoTimeout(readTimeout);
            socket.setKeepAlive(true);
            if (errorDetection) {
                monitorSocket(socket);
            }
            reconnectPolicy.reconnected();
            logger.debug("Made a new connection to APNS");
        } catch (IOException e) {
            logger.error("Couldn't connect to APNS server", e);
            // indicate to clients whether this is a resend or initial send
            throw new NetworkIOException(e, resend);
        }
    }
    return socket;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NetworkIOException(com.notnoop.exceptions.NetworkIOException) IOException(java.io.IOException) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Socket(java.net.Socket) NetworkIOException(com.notnoop.exceptions.NetworkIOException)

Aggregations

SSLSocketFactory (javax.net.ssl.SSLSocketFactory)191 SSLSocket (javax.net.ssl.SSLSocket)69 SSLContext (javax.net.ssl.SSLContext)57 IOException (java.io.IOException)45 Socket (java.net.Socket)37 Test (org.junit.Test)33 HttpsURLConnection (javax.net.ssl.HttpsURLConnection)29 HostnameVerifier (javax.net.ssl.HostnameVerifier)27 URL (java.net.URL)23 KeyManagementException (java.security.KeyManagementException)20 OutputStream (java.io.OutputStream)19 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)19 InputStream (java.io.InputStream)18 CertificateException (java.security.cert.CertificateException)17 HttpURLConnection (java.net.HttpURLConnection)15 InetSocketAddress (java.net.InetSocketAddress)15 X509TrustManager (javax.net.ssl.X509TrustManager)15 OkHttpClient (okhttp3.OkHttpClient)14 SSLParameters (javax.net.ssl.SSLParameters)13 TrustManager (javax.net.ssl.TrustManager)13