Example usage for javax.net.ssl SSLSocketFactory getDefault

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

Introduction

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

Prototype

public static SocketFactory getDefault() 

Source Link

Document

Returns the default SSL socket factory.

Usage

From source file:SocketFetcher.java

/**
 * Start TLS on an existing socket. Supports the "STARTTLS" command in many
 * protocols./*  w ww.  j a  v  a 2 s  .c o m*/
 */
public static Socket startTLS(Socket socket, Properties props, String prefix) throws IOException {
    InetAddress a = socket.getInetAddress();
    String host = a.getHostName();
    int port = socket.getPort();
    // System.out.println("SocketFetcher: startTLS host " + host + ", port " +
    // port);

    try {
        SSLSocketFactory ssf;
        String sfClass = props.getProperty(prefix + ".socketFactory.class", null);
        SocketFactory sf = getSocketFactory(sfClass);
        if (sf != null && sf instanceof SSLSocketFactory)
            ssf = (SSLSocketFactory) sf;
        else
            ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
        socket = ssf.createSocket(socket, host, port, true);
        configureSSLSocket(socket, props, prefix);
    } catch (Exception ex) {
        if (ex instanceof InvocationTargetException) {
            Throwable t = ((InvocationTargetException) ex).getTargetException();
            if (t instanceof Exception)
                ex = (Exception) t;
        }
        if (ex instanceof IOException)
            throw (IOException) ex;
        // wrap anything else before sending it on
        IOException ioex = new IOException(
                "Exception in startTLS: host " + host + ", port " + port + "; Exception: " + ex);
        throw ioex;
    }
    return socket;
}

From source file:client.ui.Container.java

public void test(String URL) throws IOException, MalformedURLException {

    Thread worker = new Thread() {
        public void run() {
            String error = null;/*from  ww w  .ja va  2s . c  om*/

            try {
                int http = 0;
                int h2 = 0;

                URL entry = new URL(URL);
                Request request = new Request.Builder().url(entry.toString()).build();

                Response response = httpClient.newCall(request).execute();
                log("Getting urls to test from: " + entry.toString());

                JSONObject json = new JSONObject(response.body().string());

                JSONArray urls = json.getJSONArray("urls");
                progress.setMaximum(urls.length());
                progress.setIndeterminate(false);

                SocketFactory factory = SSLSocketFactory.getDefault();
                JSONArray certs = new JSONArray();

                for (int i = 0; i < urls.length(); ++i) {
                    URL url = new URL(urls.getString(i));

                    if ("https".equals(url.getProtocol())) {
                        certs.put(getCert(factory, url));
                    }

                    response = request(httpClient, url);
                    if (response != null) {
                        http++;
                    }

                    response = request(http2Client, url);
                    if (response != null) {
                        h2++;
                    }
                    progress.setValue(progress.getValue() + 1);
                }

                URL finish = new URL(entry.getProtocol(), entry.getHost(), entry.getPort(),
                        json.getString("finish"));

                json = new JSONObject();
                json.put("certs", certs);

                response = request(httpClient, finish, json.toString());
                json = new JSONObject(response.body().string());

                String vcode = json.getString("vcode");
                if (vcode.length() > 0) {
                    vcodeLabel.setText("Please, copy the VCODE:");
                    vcodeOutput.setText(vcode);
                    vcodeOutput.setEnabled(true);
                }

                JOptionPane.showMessageDialog(Container.this,
                        "Successful requests: " + "\nHTTP/1.1: " + Integer.toString(http) + "/"
                                + Integer.toString(urls.length()) + "\nHTTP/2:    " + Integer.toString(h2) + "/"
                                + Integer.toString(urls.length()),
                        "Completed!", JOptionPane.INFORMATION_MESSAGE);

            } catch (Exception e) {
                error = e.getMessage();
            }

            if (error != null) {
                System.out.println(error);
                JOptionPane.showMessageDialog(Container.this, "Error: " + error, "Error",
                        JOptionPane.ERROR_MESSAGE);

                progress.setIndeterminate(false);
                progress.setValue(0);
            }

            campaignInput.setEnabled(true);
            workerInput.setEnabled(true);
            urlInput.setEnabled(true);
            button.setEnabled(true);
        }
    };

    worker.start();
}

From source file:android.net.SSLCertificateSocketFactory.java

private SSLSocketFactory makeSocketFactory(KeyManager[] keyManagers, TrustManager[] trustManagers) {
    try {//from ww  w.j  a  v  a  2 s  .  com
        OpenSSLContextImpl sslContext = new OpenSSLContextImpl();
        sslContext.engineInit(keyManagers, trustManagers, null);
        sslContext.engineGetClientSessionContext().setPersistentCache(mSessionCache);
        return sslContext.engineGetSocketFactory();
    } catch (KeyManagementException e) {
        Log.wtf(TAG, e);
        return (SSLSocketFactory) SSLSocketFactory.getDefault(); // Fallback
    }
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.lang.String,int)
 *///from  w  w w .java  2  s.  c o m
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(host, port);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:xmppserver.SmackCcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @param username/*from  ww  w. j a v a 2 s  . com*/
 *            GCM_SENDER_ID@gcm.googleapis.com
 * @param password
 *            API Key
 * @throws XMPPException
 */
public void connect(String username, String password) throws XMPPException {
    config = new ConnectionConfiguration(GCM_SERVER, GCM_PORT);
    config.setSecurityMode(SecurityMode.enabled);
    config.setReconnectionAllowed(true);
    config.setRosterLoadedAtLogin(false);
    config.setSendPresence(false);
    config.setSocketFactory(SSLSocketFactory.getDefault());

    // NOTE: Set to true to launch a window with information about packets
    // sent and received
    config.setDebuggerEnabled(true);

    // -Dsmack.debugEnabled=true
    XMPPConnection.DEBUG_ENABLED = true;

    connection = new XMPPConnection(config);
    connection.connect();

    connection.addConnectionListener(new ConnectionListener() {

        @Override
        public void reconnectionSuccessful() {
            logger.info("Reconnecting..");
        }

        @Override
        public void reconnectionFailed(Exception e) {
            logger.log(Level.INFO, "Reconnection failed.. ", e);
        }

        @Override
        public void reconnectingIn(int seconds) {
            logger.log(Level.INFO, "Reconnecting in %d secs", seconds);
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            logger.log(Level.INFO, "Connection closed on error.");
        }

        @Override
        public void connectionClosed() {
            logger.info("Connection closed.");
        }
    });

    // Handle incoming packets
    connection.addPacketListener(new PacketListener() {

        @Override
        public void processPacket(Packet packet) {
            logger.log(Level.INFO, "Received: " + packet.toXML());
            Message incomingMessage = (Message) packet;
            GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE);
            String json = gcmPacket.getJson();
            try {
                @SuppressWarnings("unchecked")
                Map<String, Object> jsonObject = (Map<String, Object>) JSONValue.parseWithException(json);

                // present for "ack"/"nack", null otherwise
                Object messageType = jsonObject.get("message_type");

                if (messageType == null) {
                    // Normal upstream data message
                    handleIncomingDataMessage(jsonObject);

                    // Send ACK to CCS
                    String messageId = jsonObject.get("message_id").toString();
                    String from = jsonObject.get("from").toString();
                    String ack = createJsonAck(from, messageId);
                    send(ack);
                } else if ("ack".equals(messageType.toString())) {
                    // Process Ack
                    handleAckReceipt(jsonObject);
                } else if ("nack".equals(messageType.toString())) {
                    // Process Nack
                    handleNackReceipt(jsonObject);
                } else {
                    logger.log(Level.WARNING, "Unrecognized message type (%s)", messageType.toString());
                }
            } catch (ParseException e) {
                logger.log(Level.SEVERE, "Error parsing JSON " + json, e);
            } catch (Exception e) {
                logger.log(Level.SEVERE, "Couldn't send echo.", e);
            }
        }
    }, new PacketTypeFilter(Message.class));

    // Log all outgoing packets
    connection.addPacketInterceptor(new PacketInterceptor() {
        @Override
        public void interceptPacket(Packet packet) {
            logger.log(Level.INFO, "Sent: {0}", packet.toXML());
        }
    }, new PacketTypeFilter(Message.class));

    connection.login(username, password);
}

From source file:au.edu.monash.merc.capture.util.httpclient.ssl.StrictSSLProtocolSocketFactory.java

/**
 * @see SecureProtocolSocketFactory#createSocket(java.net.Socket,java.lang.String,int,boolean)
 *//*from w ww  .j  av a2 s.  c o  m*/
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
        throws IOException, UnknownHostException {
    SSLSocketFactory sf = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslSocket = (SSLSocket) sf.createSocket(socket, host, port, autoClose);
    verifyHostname(sslSocket);

    return sslSocket;
}

From source file:SocketFetcher.java

/**
 * Start TLS on an existing socket./* w w  w.j  a  va  2 s.  co  m*/
 * Supports the "STARTTLS" command in many protocols.
 */
public static Socket startTLS(Socket socket, Properties props, String prefix) throws IOException {
    InetAddress a = socket.getInetAddress();
    String host = a.getHostName();
    int port = socket.getPort();
    //System.out.println("SocketFetcher: startTLS host " + host + ", port " + port);

    try {
        SSLSocketFactory ssf;
        String sfClass = props.getProperty(prefix + ".socketFactory.class", null);
        SocketFactory sf = getSocketFactory(sfClass);
        if (sf != null && sf instanceof SSLSocketFactory)
            ssf = (SSLSocketFactory) sf;
        else
            ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
        socket = ssf.createSocket(socket, host, port, true);
        configureSSLSocket(socket, props, prefix);
    } catch (Exception ex) {
        if (ex instanceof InvocationTargetException) {
            Throwable t = ((InvocationTargetException) ex).getTargetException();
            if (t instanceof Exception)
                ex = (Exception) t;
        }
        if (ex instanceof IOException)
            throw (IOException) ex;
        // wrap anything else before sending it on
        IOException ioex = new IOException(
                "Exception in startTLS: host " + host + ", port " + port + "; Exception: " + ex);
        ioex.initCause(ex);
        throw ioex;
    }
    return socket;
}

From source file:kx.c.java

/**
 * Initializes a new {@link c} instance.
 * /*  www.  ja  va2s . c o  m*/
 * @param host Host of remote q process
 * @param port Port of remote q process
 * @param usernamepassword Username and password as "username:password" for remote authorization
 * @param useTLS whether to use TLS to encrypt the connection
 * 
 * @throws KException if access denied
 * @throws IOException if an I/O error occurs.
 */
public c(String host, int port, String usernamepassword, boolean useTLS) throws KException, IOException {
    B = new byte[2 + ns(usernamepassword)];
    s = new Socket(host, port);
    if (useTLS) {
        s = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(s, host, port, true);
        ((SSLSocket) s).startHandshake();
    }
    io(s);
    J = 0;
    w(usernamepassword + "\3");
    o.write(B);
    if (1 != i.read(B, 0, 1)) {
        close();
        if (useTLS) {
            throw new KException("access");
        }
        B = new byte[1 + ns(usernamepassword)];
        io(new Socket(host, port));
        J = 0;
        w(usernamepassword);
        o.write(B);
        if (1 != i.read(B, 0, 1)) {
            close();
            throw new KException("access");
        }
    }
    vt = Math.min(B[0], 3);
}

From source file:org.wso2.carbon.identity.authenticator.wikid.WiKIDAuthenticator.java

/**
 * Send REST call/*ww w. j  a v  a 2 s .  c o  m*/
 */
private String sendRESTCall(String url, String urlParameters, String formParameters, String httpMethod) {
    String line;
    StringBuilder responseString = new StringBuilder();
    HttpsURLConnection connection = null;
    try {
        setHttpsClientCert(
                "/media/sf_SharedFoldersToVBox/is-connectors/wikid/wikid-authenticator/org.wso2.carbon.identity.authenticator/src/main/resources/localhostWiKID",
                "shakila");
        SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();

        URL wikidEP = new URL(url + urlParameters);
        connection = (HttpsURLConnection) wikidEP.openConnection();
        connection.setSSLSocketFactory(sslsocketfactory);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty(WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE,
                WiKIDAuthenticatorConstants.HTTP_CONTENT_TYPE_XWFUE);
        if (httpMethod.toUpperCase().equals(WiKIDAuthenticatorConstants.HTTP_POST)) {
            OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(),
                    WiKIDAuthenticatorConstants.CHARSET);
            writer.write(formParameters);
            writer.close();
        }
        if (connection.getResponseCode() == 200) {
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = br.readLine()) != null) {
                responseString.append(line);
            }
            br.close();
        } else {
            return WiKIDAuthenticatorConstants.FAILED + WiKIDAuthenticatorConstants.REQUEST_FAILED;
        }
    } catch (ProtocolException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (MalformedURLException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug(WiKIDAuthenticatorConstants.FAILED + e.getMessage());
        }
        return WiKIDAuthenticatorConstants.FAILED + e.getMessage();
    } finally {
        connection.disconnect();
    }
    return responseString.toString();
}

From source file:ca.uhn.hl7v2.testpanel.model.conn.AbstractConnection.java

SocketFactory getSocketFactory() {
    return new SocketFactory() {

        @Override//  ww  w  . j  a va 2s .co  m
        public Socket createTlsSocket() throws IOException {
            try {
                if (getTransport() == TransportStyleEnum.HL7_OVER_HTTP && getTlsKeystore() != null) {
                    return createHohSocketFactory().createClientSocket();
                }
            } catch (KeyStoreException e) {
                throw new IOException(e.getMessage(), e);
            }
            return SSLSocketFactory.getDefault().createSocket();
        }

        @Override
        public ServerSocket createTlsServerSocket() throws IOException {
            try {
                if (getTransport() == TransportStyleEnum.HL7_OVER_HTTP && getHohSignatureKeystore_() != null) {
                    return createHohSocketFactory().createServerSocket();
                }
            } catch (KeyStoreException e) {
                throw new IOException(e.getMessage(), e);
            }
            return SSLServerSocketFactory.getDefault().createServerSocket();
        }

        private CustomCertificateTlsSocketFactory createHohSocketFactory() throws KeyStoreException {
            KeyStore keystore = getTlsKeystore();
            String keystorePassword = getTlsKeystorePassword();
            CustomCertificateTlsSocketFactory sf = new CustomCertificateTlsSocketFactory(keystore,
                    keystorePassword);
            return sf;
        }

        @Override
        public Socket createSocket() throws IOException {
            return javax.net.SocketFactory.getDefault().createSocket();
        }

        @Override
        public ServerSocket createServerSocket() throws IOException {
            return ServerSocketFactory.getDefault().createServerSocket();
        }

        @Override
        public void configureNewAcceptedSocket(Socket theSocket) throws SocketException {
            // nothing
        }
    };
}