Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:com.leanplum.internal.WebSocketClient.java

private SSLSocketFactory getSSLSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, sTrustManagers, null);
    return context.getSocketFactory();
}

From source file:jp.primecloud.auto.sdk.Requester.java

protected HttpURLConnection createConnection(String url, PccOptions options)
        throws IOException, GeneralSecurityException {
    HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
    connection.setRequestMethod("GET");

    if (options != null) {
        // HTTPS?
        if (connection instanceof HttpsURLConnection && Boolean.TRUE.equals(options.getIgnoreCerts())) {
            HttpsURLConnection connection2 = (HttpsURLConnection) connection;

            // ?// www .j  ava2s  .  c  om
            X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }

                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType)
                        throws CertificateException {
                }
            };
            SSLContext sslcontext = SSLContext.getInstance("SSL");
            sslcontext.init(null, new TrustManager[] { trustManager }, null);
            connection2.setSSLSocketFactory(sslcontext.getSocketFactory());

            // ???
            connection2.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
        }
    }

    return connection;
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterDMPicHelper.java

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {/*from www . j  a  v a 2  s  .  c om*/
        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("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // 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;
}

From source file:com.adito.boot.CustomSSLSocketFactory.java

private SSLSocketFactory getSocketFactory() throws IOException {
    try {/*from   w w w .ja  v  a 2s. c  om*/
        SSLContext sslCtx = SSLContext.getInstance("SSL");
        KeyManager[] aKM = SSLKeyManager.getKeyManagerArray();
        TrustManager[] aTM = SSLTrustManager.getTrustManagerArray();
        sslCtx.init(aKM, aTM, null);
        SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
        return socketFactory;
    } catch (KeyManagementException e) {
        log.error("Cannot create SSL socket", e);
        throw new IOException("Cannot create SSL socket: " + e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        log.error("Cannot create SSL socket", e);
        throw new IOException("Cannot create SSL socket: " + e.getMessage());
    }
}

From source file:com.alvexcore.share.ShareExtensionRegistry.java

@Override
public void afterPropertiesSet() throws Exception {
    // disable SSL certs validation
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override//from ww  w  .  ja  va2 s .co  m
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        @Override
        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        @Override
        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
}

From source file:it.publisys.liferay.hook.shibboleth.ShibbolethPostLogoutAction.java

/**
 * Effettua una {@link HttpURLConnection} inviando anche i cookies
 *
 * @param url     url/*from   www . j a v  a 2 s.  co m*/
 * @param cookies cookies
 * @return response code
 */
private int _connect(String url, String cookies) {
    int responseCode = -1;
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public void checkClientTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

            public void checkServerTrusted(java.security.cert.X509Certificate[] xcs, String string)
                    throws CertificateException {
            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        } };

        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
    }

    HttpURLConnection connection = null;
    try {
        URL _url = new URL(url);
        connection = (HttpURLConnection) _url.openConnection(Proxy.NO_PROXY);
        connection.setRequestProperty("Cookie", cookies);
        connection.setReadTimeout(5000);
        connection.setRequestMethod("GET");

        responseCode = connection.getResponseCode();
        _log.info("Logout Shibb response code: " + responseCode);

        if (responseCode == 200 && _log.isDebugEnabled()) {
            BufferedReader br = null;
            try {
                br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                StringBuilder _buffer = new StringBuilder();
                String line = null;
                while ((line = br.readLine()) != null) {
                    _buffer.append(line);
                }
                _log.debug(_buffer.toString());
            } finally {
                if (br != null) {
                    br.close();
                }
            }

        }

    } catch (MalformedURLException mue) {
        mue.printStackTrace(System.err);
    } catch (IOException ioe) {
        ioe.printStackTrace(System.err);
    } finally {
        try {
            if (connection != null) {
                connection.disconnect();
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }
    }
    return responseCode;
}

From source file:immf.MyWiser.java

private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) {
    InputStream keyis = null;/*from w  ww . jav a  2 s .c o m*/
    try {
        keyis = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance(keyType);
        keyStore.load(keyis, keypasswd.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, keypasswd.toCharArray());

        SSLContext context = SSLContext.getInstance("TLS");

        context.init(kmf.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    } finally {
        try {
            keyis.close();
        } catch (Exception e) {
        }
    }
}

From source file:com.subgraph.vega.internal.http.proxy.VegaHttpService.java

private SSLSocket createSSLSocketForHost(HttpHost host, Socket socket) throws IOException {
    final SSLContext ctx = sslContextRepository.getContextForName(host.getHostName());
    if (ctx == null) {
        throw new IOException("Failed to create SSLContext for host " + host.getHostName());
    }/*from   ww w  . j a va 2s. com*/
    SSLSocketFactory sslSocketFactory = ctx.getSocketFactory();
    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(socket, host.getHostName(), host.getPort(),
            true);
    sslSocket.setUseClientMode(false);
    return sslSocket;
}

From source file:com.tune.reporting.base.service.TuneServiceProxy.java

/**
 * Post request to TUNE Service API Service
 *
 * @return Boolean True if successful posting request, else False.
 * @throws TuneSdkException If error within SDK.
 *///from  w  w w.j av  a 2  s. c  o m
protected boolean postRequest() throws TuneSdkException {
    URL url = null;
    HttpsURLConnection conn = null;

    try {
        url = new URL(this.uri);
    } catch (MalformedURLException ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: %s: '%s'", this.uri,
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    try {
        // connect to the server over HTTPS and submit the payload
        conn = (HttpsURLConnection) url.openConnection();

        // Create the SSL connection
        SSLContext sc;
        sc = SSLContext.getInstance("TLS");
        sc.init(null, null, new java.security.SecureRandom());
        conn.setSSLSocketFactory(sc.getSocketFactory());

        conn.setRequestMethod("GET");
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.connect();

        // Gets the status code from an HTTP response message.
        final int responseHttpCode = conn.getResponseCode();

        // Returns an unmodifiable Map of the header fields.
        // The Map keys are Strings that represent the response-header
        // field names. Each Map value is an unmodifiable List of Strings
        // that represents the corresponding field values.
        final Map<String, List<String>> responseHeaders = conn.getHeaderFields();

        final String requestUrl = url.toString();

        // Gets the HTTP response message, if any, returned along
        // with the response code from a server.
        String responseRaw = conn.getResponseMessage();

        // Pull entire JSON raw response
        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();

        responseRaw = sb.toString();

        // decode to JSON
        JSONObject responseJson = new JSONObject(responseRaw);

        this.response = new TuneServiceResponse(responseRaw, responseJson, responseHttpCode, responseHeaders,
                requestUrl.toString());
    } catch (Exception ex) {
        throw new TuneSdkException(String.format("Problems executing request: %s: '%s'",
                ex.getClass().toString(), ex.getMessage()), ex);
    }

    return true;
}

From source file:com.sitewhere.groovy.device.communication.rest.RestHelper.java

/**
 * Create SSL context that allows bad certificates.
 * //ww w.  j a  v  a  2  s.  c  o  m
 * @return
 */
protected SSLContext createContext() {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) {
        }
    } };

    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, null);
        SSLContext.setDefault(sc);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return sc;

    } catch (Exception e) {
    }
    return null;
}