Example usage for javax.net.ssl SSLSocketFactory createSocket

List of usage examples for javax.net.ssl SSLSocketFactory createSocket

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocketFactory createSocket.

Prototype

@Override
    public Socket createSocket() throws IOException 

Source Link

Usage

From source file:com.cyberway.issue.crawler.fetcher.HeritrixSSLProtocolSocketFactory.java

public synchronized Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException {
    // Below code is from the DefaultSSLProtocolSocketFactory#createSocket
    // method only it has workarounds to deal with pre-1.4 JVMs.  I've
    // cut these out.
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }// w w w.j a v  a  2  s  . co m
    Socket socket = null;
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        socket = createSocket(host, port, localAddress, localPort);
    } else {
        SSLSocketFactory factory = (SSLSocketFactory) params.getParameter(FetchHTTP.SSL_FACTORY_KEY);
        SSLSocketFactory f = (factory != null) ? factory : this.sslDefaultFactory;
        socket = f.createSocket();
        ServerCache cache = (ServerCache) params.getParameter(FetchHTTP.SERVER_CACHE_KEY);
        InetAddress hostAddress = (cache != null) ? HeritrixProtocolSocketFactory.getHostAddress(cache, host)
                : null;
        InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port)
                : new InetSocketAddress(host, port);
        socket.bind(new InetSocketAddress(localAddress, localPort));
        try {
            socket.connect(address, timeout);
        } catch (SocketTimeoutException e) {
            // Add timeout info. to the exception.
            throw new SocketTimeoutException(
                    e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms.");
        }
        assert socket.isConnected() : "Socket not connected " + host;
    }
    return socket;
}

From source file:org.archive.modules.fetcher.HeritrixSSLProtocolSocketFactory.java

public synchronized Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException {
    // Below code is from the DefaultSSLProtocolSocketFactory#createSocket
    // method only it has workarounds to deal with pre-1.4 JVMs.  I've
    // cut these out.
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }// w  ww  .  j  ava2 s .  co m
    Socket socket = null;
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        socket = createSocket(host, port, localAddress, localPort);
    } else {
        SSLSocketFactory factory = (SSLSocketFactory) params.getParameter(FetchHTTP.SSL_FACTORY_KEY);
        SSLSocketFactory f = (factory != null) ? factory : this.sslDefaultFactory;
        socket = f.createSocket();

        Thread current = Thread.currentThread();
        InetAddress hostAddress;
        if (current instanceof HostResolver) {
            HostResolver resolver = (HostResolver) current;
            hostAddress = resolver.resolve(host);
        } else {
            hostAddress = null;
        }
        InetSocketAddress address = (hostAddress != null) ? new InetSocketAddress(hostAddress, port)
                : new InetSocketAddress(host, port);
        socket.bind(new InetSocketAddress(localAddress, localPort));
        try {
            socket.connect(address, timeout);
        } catch (SocketTimeoutException e) {
            // Add timeout info. to the exception.
            throw new SocketTimeoutException(
                    e.getMessage() + ": timeout set at " + Integer.toString(timeout) + "ms.");
        }
        assert socket.isConnected() : "Socket not connected " + host;
    }
    return socket;
}

From source file:org.apache.jmeter.util.HttpSSLProtocolSocketFactory.java

/**
 * @see javax.net.SocketFactory#createSocket()
 *//*from  www  . j a v  a 2s . co  m*/
@Override
public Socket createSocket() throws IOException, UnknownHostException {
    SSLSocketFactory sslfac = getSSLSocketFactory();
    Socket sock = sslfac.createSocket();
    setSocket(sock);
    return wrapSocket(sock);
}

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

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {//from   w  w  w  .j  a  v a 2s  .c o  m
        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.saylor.harrison.opustestround2.audio.WebSocketUploader.java

/**
 * Trust server//from w w  w  .j  a v  a  2s.c o m
 *
 * @throws KeyManagementException
 * @throws NoSuchAlgorithmException
 */
private void trustServer() throws KeyManagementException, NoSuchAlgorithmException, IOException {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] certs = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext sslContext = null;
    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, certs, new java.security.SecureRandom());
    SSLSocketFactory factory = sslContext.getSocketFactory();
    this.setSocket(factory.createSocket());
}

From source file:org.restcomm.app.qoslib.Utils.RTWebSocket.java

private void connectWebSocket() {
    URI uri;/* w  ww.  j  av  a 2s . c  om*/
    try {
        String ws_uri = context.getString(R.string.MMC_WEBSOCKET_URL);
        uri = new URI(ws_uri);
    } catch (URISyntaxException e) {
        //e.printStackTrace();
        return;
    }

    String apiKey = context.getApiKey(context);

    HashMap<String, String> header = new HashMap<String, String>();
    header.put("apiKey", apiKey);
    mWebSocketClient = new WebSocketClient(uri, new Draft_17(), header, 10000) {
        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            //Log.i("Websocket", "Opened");
            LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "Websocket opened ");
            //mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
            PreferenceManager.getDefaultSharedPreferences(context).edit()
                    .putBoolean(PreferenceKeys.Miscellaneous.WEBSOCKET_RUNNING, true).commit();
            wsConnected = true;

            // Force intents to be resent for last known location, signal and cell
            context.getEventManager().signalSnapshot(null);

            context.getIntentDispatcher().updateNetwork();

        }

        @Override
        public void onMessage(String s) {
            final String message = s;

        }

        @Override
        public void onClose(int i, String s, boolean b) {
            LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "Websocket closed " + s);

            // close web socket
            PreferenceManager.getDefaultSharedPreferences(context).edit()
                    .putBoolean(PreferenceKeys.Miscellaneous.WEBSOCKET_RUNNING, false).commit();
            mWebSocketClient = null;
            wsConnected = false;
            mWebSocketQueue.clear();
            webSocketThread = null;

        }

        @Override
        public void onError(Exception e) {
            Log.i("Websocket", "Error " + e.getMessage());
            LoggerUtil.logToFile(LoggerUtil.Level.ERROR, TAG, "connectWebSocket", "onError ", e);
        }
    };

    LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "get SSL");
    SSLContext sslContext = null;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, null, null); // will use java's default key and trust store which is sufficient unless you deal with self-signed certificates

        SSLSocketFactory factory = sslContext.getSocketFactory();// (SSLSocketFactory) SSLSocketFactory.getDefault();

        mWebSocketClient.setSocket(factory.createSocket());

        mWebSocketClient.connect();
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "called connect");
    } catch (Exception e) {
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "connectWebSocket", "Exception: ", e);
    }
}

From source file:org.apache.hadoop.net.HopsSSLSocketFactory.java

public Socket createSocket() throws IOException, UnknownHostException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating SSL client socket");
    }// ww  w.  j  a v  a2  s. c o m
    if (conf.getBoolean(FORCE_CONFIGURE, false)) {
        setConf(conf);
    }
    SSLContext sslCtx = initializeSSLContext();
    SSLSocketFactory socketFactory = sslCtx.getSocketFactory();
    return socketFactory.createSocket();
}

From source file:i2p.bote.imap.ImapService.java

public ImapService(Configuration configuration, final PasswordVerifier passwordVerifier,
        EmailFolderManager folderManager) throws ConfigurationException {
    this.folderManager = folderManager;

    setLog(LoggerFactory.getLogger(ImapService.class));

    // Set up the keystore for the SSL certificate
    sslKeyStore = configuration.getSSLKeyStoreFile();
    setFileSystem(new FileSystem() {
        @Override/*  w w w .  j a  v a2  s. c o  m*/
        public InputStream getResource(String resource) throws IOException {
            return null;
        }

        @Override
        public File getFile(String fileURL) throws FileNotFoundException {
            if (fileURL.equals(SSL_KEYSTORE_FILE))
                return sslKeyStore;
            return null;
        }

        @Override
        public File getBasedir() throws FileNotFoundException {
            return null;
        }
    });

    HierarchicalConfiguration cfg = new HierarchicalConfiguration();
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket s = null;
    try {
        // Create an unconnected socket for getting supported cipher suites
        s = (SSLSocket) sf.createSocket();
        // enable STARTTLS using the above keystore
        cfg.setProperty("tls.[@startTLS]", true);
        cfg.setProperty("tls.keystore", SSL_KEYSTORE_FILE);
        cfg.setProperty("tls.secret", configuration.getSSLKeyStorePassword());
        // select strong cipher suites
        cfg.setProperty("tls.supportedCipherSuites.cipherSuite",
                StrongTls.getRecommendedCipherSuites(s.getSupportedCipherSuites()));
    } catch (IOException e) {
        log.error("Couldn't determine supported cipher suites", e);
    } finally {
        if (s != null)
            try {
                s.close();
            } catch (IOException e) {
            }
    }
    configure(cfg); // use the defaults for the rest

    setListenAddresses(new InetSocketAddress(configuration.getImapAddress(), configuration.getImapPort()));

    mailboxSessionMapperFactory = new MapperFactory(folderManager);
    MailboxACLResolver aclResolver = createMailboxACLResolver();
    GroupMembershipResolver groupMembershipResolver = new GroupMembershipResolver() {
        public boolean isMember(String user, String group) {
            return true;
        }
    };
    Authenticator authenticator = createAuthenticator(passwordVerifier);
    StoreMailboxManager<String> mailboxManager = new StoreMailboxManager<String>(mailboxSessionMapperFactory,
            authenticator, aclResolver, groupMembershipResolver);
    mailboxManager.setDelegatingMailboxListener(new HashMapDelegatingMailboxListener());
    mailboxManager.setMailboxSessionIdGenerator(new RandomMailboxSessionIdGenerator());

    SubscriptionManager subscriptionManager = createSubscriptionManager();

    ImapProcessor processor = DefaultImapProcessorFactory.createDefaultProcessor(mailboxManager,
            subscriptionManager);
    setImapProcessor(processor);

    setImapEncoder(DefaultImapEncoderFactory.createDefaultEncoder(new Localizer() {
        public String localize(HumanReadableText text, Locales locales) {
            return text.getDefaultValue();
        }
    }, true));
    setImapDecoder(DefaultImapDecoderFactory.createDecoder());
}

From source file:io.fabric8.kubernetes.api.KubernetesHelper.java

public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) {
    try {//from  w ww .  j a  v  a2  s .  com
        SSLSocketFactory sslsocketfactory = null;
        if (trustAllCerts) {
            sslsocketfactory = KubernetesFactory.TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory();
        } else {
            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }

        Socket socket = sslsocketfactory.createSocket();

        // Connect, with an explicit timeout value
        socket.connect(new InetSocketAddress(host, port), 1 * 1000);
        try {

            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            // Write a test byte to get a reaction :)
            out.write(1);

            while (in.available() > 0) {
                System.out.print(in.read());
            }

            return true;
        } finally {
            socket.close();
        }
    } catch (SSLHandshakeException e) {
        LOG.error(
                "SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable "
                        + KubernetesFactory.KUBERNETES_TRUST_ALL_CERIFICATES,
                e);
    } catch (SSLProtocolException e) {
        LOG.error("SSL protocol error", e);
    } catch (SSLKeyException e) {
        LOG.error("Bad SSL key", e);
    } catch (SSLPeerUnverifiedException e) {
        LOG.error("Could not verify server", e);
    } catch (SSLException e) {
        LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e);
    } catch (IOException e) {
        LOG.debug("Failed to validate service", e);
    }
    return false;
}

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

public ArrayList<String> getImageURLs(Status status, Twitter twitter) {

    ArrayList<String> images = TweetLinkUtils.getAllExternalPictures(status);
    try {//from  www  .j  a v a2s . 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 = "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");

                // want to check to make sure it doesn't have it already
                // 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;
}