Search in sources :

Example 16 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project sonarqube by SonarSource.

the class OkHttpClientBuilder method build.

public OkHttpClient build() {
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.proxy(proxy);
    if (connectTimeoutMs >= 0) {
        builder.connectTimeout(connectTimeoutMs, TimeUnit.MILLISECONDS);
    }
    if (readTimeoutMs >= 0) {
        builder.readTimeout(readTimeoutMs, TimeUnit.MILLISECONDS);
    }
    builder.addInterceptor(this::completeHeaders);
    ConnectionSpec tls = new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS).allEnabledTlsVersions().allEnabledCipherSuites().supportsTlsExtensions(true).build();
    builder.connectionSpecs(asList(tls, ConnectionSpec.CLEARTEXT));
    X509TrustManager trustManager = sslTrustManager != null ? sslTrustManager : systemDefaultTrustManager();
    SSLSocketFactory sslFactory = sslSocketFactory != null ? sslSocketFactory : systemDefaultSslSocketFactory(trustManager);
    builder.sslSocketFactory(sslFactory, trustManager);
    return builder.build();
}
Also used : OkHttpClient(okhttp3.OkHttpClient) ConnectionSpec(okhttp3.ConnectionSpec) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 17 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project sonarqube by SonarSource.

the class OkHttpClientBuilderTest method build_with_custom_sslSocketFactory.

@Test
public void build_with_custom_sslSocketFactory() {
    SSLSocketFactory sslSocketFactory = mock(SSLSocketFactory.class);
    OkHttpClient okHttpClient = underTest.setSSLSocketFactory(sslSocketFactory).build();
    assertThat(okHttpClient.sslSocketFactory()).isEqualTo(sslSocketFactory);
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) Test(org.junit.Test)

Example 18 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project quickstarts by jboss-switchyard.

the class CamelNettyBindingTest method sendTextMessageThroughTcp.

@Test
public void sendTextMessageThroughTcp() throws Exception {
    // replace existing implementation for testing purposes
    _testKit.removeService("SecuredGreetingService");
    final MockHandler greetingService = _testKit.registerInOnlyService("SecuredGreetingService");
    greetingService.forwardInToOut();
    KeyStore keystore = KeyStore.getInstance("JKS");
    keystore.load(new FileInputStream("users.jks"), "changeit".toCharArray());
    TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(keystore);
    SSLContext context = SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keystore, "changeit".toCharArray());
    context.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
    SSLSocketFactory sf = context.getSocketFactory();
    Socket clientSocket = sf.createSocket("localhost", 3939);
    DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
    // lets write payload directly as bytes to avoid encoding mismatches
    outputStream.write(PAYLOAD.getBytes());
    outputStream.flush();
    // sleep a bit to receive message on camel side
    Thread.sleep(50);
    clientSocket.close();
    greetingService.waitForOKMessage();
    final LinkedBlockingQueue<Exchange> recievedMessages = greetingService.getMessages();
    assertThat(recievedMessages, is(notNullValue()));
    final Exchange recievedExchange = recievedMessages.iterator().next();
    assertThat(PAYLOAD, is(equalTo(recievedExchange.getMessage().getContent(String.class))));
}
Also used : Exchange(org.switchyard.Exchange) DataOutputStream(java.io.DataOutputStream) TrustManagerFactory(javax.net.ssl.TrustManagerFactory) MockHandler(org.switchyard.test.MockHandler) SSLContext(javax.net.ssl.SSLContext) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) Socket(java.net.Socket) MulticastSocket(java.net.MulticastSocket) KeyManagerFactory(javax.net.ssl.KeyManagerFactory) Test(org.junit.Test)

Example 19 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project Talon-for-Twitter by klinker24.

the class TwitterDMPicHelper method getDMPicture.

public Bitmap getDMPicture(String picUrl, Twitter twitter) {
    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();
        // generate authorization header
        String get_or_post = "GET";
        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";
        String twitter_endpoint = picUrl;
        String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "").replace("/", "");
        String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", "");
        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));
        Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host);
        Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path);
        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);
        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("GET", twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);
        StatusLine statusLine = response2.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200 || statusCode == 302) {
            HttpEntity entity = response2.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            Log.v("talon_dm_image", statusCode + "");
        }
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) Bitmap(android.graphics.Bitmap) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Calendar(java.util.Calendar) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) GeneralSecurityException(java.security.GeneralSecurityException) IOException(java.io.IOException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) Socket(java.net.Socket)

Example 20 with SSLSocketFactory

use of javax.net.ssl.SSLSocketFactory in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method getImageURLs.

public ArrayList<String> getImageURLs(Status status, Twitter twitter) {
    ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();
        // generate authorization header
        String get_or_post = "GET";
        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";
        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/show/" + status.getId() + ".json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/show/" + status.getId() + ".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);
        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("GET", twitter_endpoint_path);
        request2.setParams(params);
        request2.addHeader("Authorization", authorization_header_string);
        httpexecutor.preProcess(request2, httpproc, context);
        HttpResponse response2 = httpexecutor.execute(request2, conn, context);
        response2.setParams(params);
        httpexecutor.postProcess(response2, httpproc, context);
        String responseBody = EntityUtils.toString(response2.getEntity());
        conn.close();
        JSONObject fullJson = new JSONObject(responseBody);
        JSONObject extendedEntities = fullJson.getJSONObject("extended_entities");
        JSONArray media = extendedEntities.getJSONArray("media");
        Log.v("talon_images", media.toString());
        for (int i = 0; i < media.length(); i++) {
            JSONObject entity = media.getJSONObject(i);
            try {
                // parse through the objects and get the media_url
                String url = entity.getString("media_url");
                String type = entity.getString("type");
                // this also checks to confirm that the entity is in fact a photo
                if (!images.contains(url) && type.equals("photo")) {
                    images.add(url);
                }
            } catch (Exception e) {
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return images;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) 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) Calendar(java.util.Calendar) JSONArray(org.json.JSONArray) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) 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) Socket(java.net.Socket)

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