Example usage for org.apache.http.conn.ssl SSLSocketFactory createSocket

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory createSocket

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory createSocket.

Prototype

public Socket createSocket() throws IOException 

Source Link

Usage

From source file:org.zywx.wbpalmstar.platform.certificates.HSSLSocketFactory.java

@Override
public Socket createSocket() throws IOException {
    javax.net.ssl.SSLSocketFactory socketfact = mSSLContext.getSocketFactory();
    Socket result = socketfact.createSocket();
    return result;
}

From source file:com.fuzhouxiu.coretransfer.net.core.TcpSocket.java

/** Creates a new UdpSocket */
public TcpSocket(IpAddress ipaddr, int port, String host) throws java.io.IOException {
    //      socket = new Socket(ipaddr.getInetAddress(), port); modified
    SSLSocketFactory f = (SSLSocketFactory) SSLSocketFactory.getSocketFactory();
    if (host == null)
        socket = new Socket();
    else//from  w  w w .  ja  va  2 s  . c om
        socket = f.createSocket();
    if (lock)
        throw new java.io.IOException();
    lock = true;
    try {
        socket.connect(new InetSocketAddress(ipaddr.toString(), port),
                Thread.currentThread().getName().equals("main") ? 1000 : 10000);
    } catch (java.io.IOException e) {
        lock = false;
        throw e;
    }
    if (host != null) {
        HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
        SSLSession s = ((SSLSocket) socket).getSession();
        if (!hv.verify(host, s)) {
            lock = false;
            throw new java.io.IOException();
        }
    }
    lock = false;
}

From source file:org.hyperic.hq.plugin.netservices.NetServicesCollector.java

public SocketWrapper getSocketWrapper(boolean acceptUnverifiedCertificatesOverride) throws IOException {
    if (isSSL()) {
        // Sometimes we may want to override what's set in the keystore config...mostly for init purposes...
        boolean accept = acceptUnverifiedCertificatesOverride ? true : keystoreConfig.isAcceptUnverifiedCert();
        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, accept);
        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();
        Socket socket = factory.createSocket();

        socket.connect(getSocketAddress(), getTimeoutMillis());
        socket.setSoTimeout(getTimeoutMillis());
        ((SSLSocket) socket).startHandshake();

        return new SocketWrapper(socket);
    } else {/*  w w w.  j a  v  a  2s . c  om*/
        Socket socket = new Socket();
        connect(socket);
        return new SocketWrapper(socket);
    }
}

From source file:org.hyperic.hq.bizapp.agent.client.SecureAgentConnection.java

@Override
protected Socket getSocket() throws IOException {
    SSLSocket socket;//from  w  w w. j  a  v a 2 s.  com

    log.debug("Creating secure socket");

    try {
        // Check for configured agent read timeout from System properties
        int readTimeout;

        try {
            readTimeout = Integer.parseInt(System.getProperty(PROP_READ_TIMEOUT));
        } catch (NumberFormatException e) {
            readTimeout = READ_TIMEOUT;
        }

        // Check for configured agent post handshake timeout
        // from System properties
        int postHandshakeTimeout;
        try {
            postHandshakeTimeout = Integer.parseInt(System.getProperty(PROP_POST_HANDSHAKE_TIMEOUT));
        } catch (NumberFormatException e) {
            postHandshakeTimeout = POST_HANDSHAKE_TIMEOUT;
        }

        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, acceptUnverifiedCertificate);

        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();

        // See the following links...
        // http://www.apache.org/dist/httpcomponents/httpcore/RELEASE_NOTES-4.1.x.txt
        // http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?message=13695343&cat=10&thread=73546&treeDisplayType=threadmode1&forum=178#13695343
        // In any case, it would seem as though the bug has since been fixed in IBM's JRE, no need to work around it anymore...
        socket = (SSLSocket) factory.createSocket();

        // Make sure the InetAddress used to initialize the socket has a non-null hostname (empty string).
        // This prevents slow and unnecessary reverse DNS querying when the connection is opened.
        InetAddress withoutHost = InetAddress.getByName(this.agentAddress);
        InetAddress withHost = InetAddress.getByAddress("", withoutHost.getAddress());
        InetSocketAddress address = new InetSocketAddress(withHost, this.agentPort);

        socket.connect(address, readTimeout);

        // Set the socket timeout during the initial handshake to detect
        // connection issues with the agent.  
        socket.setSoTimeout(readTimeout);

        log.debug("Secure socket is connected to " + address + " - starting handshake.");

        socket.startHandshake();

        log.debug("SSL handshake complete");

        // [HHQ-3694] The timeout is set to a post handshake value.
        socket.setSoTimeout(postHandshakeTimeout);

    } catch (IOException exc) {
        IOException toThrow = new IOException(
                "Unable to connect to " + this.agentAddress + ":" + this.agentPort + ": " + exc.getMessage());
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    // Write our security settings
    try {
        DataOutputStream dOs;

        dOs = new DataOutputStream(socket.getOutputStream());
        dOs.writeUTF(this.authToken);
    } catch (IOException exc) {
        IOException toThrow = new IOException("Unable to write auth params to server");
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    return socket;
}

From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java

@SuppressWarnings("deprecation")
@Test//from   ww  w . j a  v a2  s.com
public void testSSLConnection() throws Exception {
    Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
    SSLSocketFactory ssf = new SSLSocketFactory(SSLContext.getInstance("TLS"));
    ssf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
    Scheme https = new Scheme("https", ssf, 443);
    SchemeRegistry sr = new SchemeRegistry();
    sr.register(http);
    sr.register(https);

    TrustManager easyTrustManager = new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkClientTrusted");
        }

        public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) {
            System.out.println("checkServerTrusted");
        }

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

    SSLContext sslcontext = SSLContext.getInstance("TLS");
    sslcontext.init(null, new TrustManager[] { easyTrustManager }, null);
    SSLSocketFactory sf = new SSLSocketFactory(sslcontext);
    SSLSocket socket = (SSLSocket) sf.createSocket();
    socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" });
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000);
    sf.connectSocket(socket, "119.29.234.42", 443, null, -1, params);
}

From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java

/**
 * Initializes the HTTPs connection/*from  ww w . ja  va  2s  .  c om*/
 * 
 * @param sslPort
 *            the number of the port the server should be listening for
 *            SSL/TLS connections
 */
public void InitializeSecure(int sslPort) {
    if (sslPort != -1) {
        SSLSocketFactory sslf = null;
        SSLSocket s = null;
        port = sslPort;
        try {
            // notifyOfProggress(false);
            KeyStore trusted = KeyStore.getInstance(KeyStore.getDefaultType());
            trusted.load(null, null);

            sslf = new MySSLSocketFactory(trusted);
            Log.w("Android mobile voting", "1");
            sslf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            Log.w("Android mobile voting", "2");
            BasicHttpParams params = new BasicHttpParams();
            Log.w("Android mobile voting", "3");
            HttpConnectionParams.setConnectionTimeout(params, 500);
            Log.w("Android mobile voting", "4");
            s = (SSLSocket) sslf.connectSocket(sslf.createSocket(), server.getAddress(), sslPort, null, 0,
                    params);
            if (exc) {
                SSLSession ssls = null;
                ssls = s.getSession();
                final javax.security.cert.X509Certificate[] x = ssls.getPeerCertificateChain();

                for (int i = 0; i < x.length; i++) {

                    parent.mHandler.post(new Runnable() {

                        @Override
                        public void run() {

                            try {
                                parent.askForTrust(getThumbPrint(x[0]), instance);
                            } catch (NoSuchAlgorithmException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (CertificateEncodingException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            } catch (final Exception ex) {
                                parent.mHandler.post(new Runnable() {

                                    @Override
                                    public void run() {
                                        parent.showToast(ex.toString());

                                    }

                                });
                                Log.w("Android Mobile Voting", "400 Error");
                                parent.finish();
                            }

                        }
                    });

                }

            }

            s.startHandshake();

            Scheme https = new Scheme("https", sslf, sslPort);

            schemeRegistry.register(https);
            usingScheme = "https";
            port = sslPort;
            if (!exc)
                retrieveQuestions();
        } catch (final Exception ex) {
            parent.mHandler.post(new Runnable() {

                @Override
                public void run() {
                    parent.showToast(ex.toString());

                }

            });
            // Log.w("Android Mobile Voting", "400 Error");
            parent.finish();

        }
    } else {
        parent.mHandler.post(new Runnable() {

            @Override
            public void run() {
                parent.showNoSSLDialog(instance);

            }

        });
    }

}