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:com.example.CcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 * @throws XMPPException//w w w.ja v a  2s .  c om
 */
public void connect() 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(mDebuggable);

    // -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(packet -> {
        logger.log(Level.INFO, "Received: " + packet.toXML());
        System.out.print(packet.toXML());
        Message incomingMessage = (Message) packet;
        GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage.getExtension(GCM_NAMESPACE);
        String json = gcmPacket.getJson();
        System.out.print(json);
        try {
            @SuppressWarnings("unchecked")
            Map<String, Object> jsonMap = (Map<String, Object>) JSONValue.parseWithException(json);

            handleMessage(jsonMap);
        } 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((PacketInterceptor) packet -> logger.log(Level.INFO, "Sent: {0}", packet.toXML()), new PacketTypeFilter(Message.class));

    connection.login(mProjectId + "@gcm.googleapis.com", mApiKey);
    logger.log(Level.INFO, "logged in: " + mProjectId);
}

From source file:com.nick.bpit.CcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @throws XMPPException/*from   w  w  w  .j a v  a  2 s .  c o m*/
 */
public void connect() 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(mDebuggable);

    // -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> jsonMap = (Map<String, Object>) JSONValue.parseWithException(json);

                handleMessage(jsonMap);
            } 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(mProjectId + "@gcm.googleapis.com", mApiKey);
    logger.log(Level.INFO, "logged in: " + mProjectId);
}

From source file:com.apteligent.ApteligentJavaClient.java

private HttpsURLConnection sendGetRequest(String endpoint, String urlParameters) throws IOException {
    // build connection object for GET request
    URL obj = new URL(endpoint + urlParameters);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(false);//from ww  w  .  j a v a2  s.c o m
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestMethod("GET");
    return conn;
}

From source file:com.zimbra.cs.mailclient.MailConnection.java

private SSLSocketFactory getSSLSocketFactory() {
    SSLSocketFactory ssf = config.getSSLSocketFactory();
    return ssf != null ? ssf : (SSLSocketFactory) SSLSocketFactory.getDefault();
}

From source file:gov.miamidade.open311.utilities.SslContextedSecureProtocolSocketFactory.java

/**
 * Returns the SSLSocketFactory to use to create the sockets. If the
 * sslContext is non-null, this is built from the sslContext; otherwise,
 * this is the default SSLSocketFactory.
 *
 * @return the SSLSocketFactory to use to create the sockets.
 *///from  w  w  w  .  j a  va 2s  .c o  m
protected SSLSocketFactory getSslSocketFactory() {
    SSLSocketFactory sslSocketFactory = null;
    synchronized (this) {
        if (this.sslContext != null) {
            sslSocketFactory = this.sslContext.getSocketFactory();
        }
    }
    if (sslSocketFactory == null) {
        sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    return sslSocketFactory;
}

From source file:com.apteligent.ApteligentJavaClient.java

private HttpsURLConnection sendPostRequest(String endpoint, String params) throws IOException {
    // build conn object for POST request
    URL obj = new URL(endpoint);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);//from   w  ww  .j a v  a 2 s . c  om
    conn.setDoInput(true);
    conn.setRequestProperty("Authorization", "Bearer " + this.token.getAccessToken());
    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length));
    conn.setRequestMethod("POST");

    // Send post request
    DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
    wr.writeBytes(params);
    wr.flush();
    wr.close();
    return conn;
}

From source file:org.openhim.mediator.denormalization.ATNAAuditingActor.java

private Socket getSocket(final MediatorSocketRequest req) throws IOException {
    if (req.isSecure()) {
        SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        return factory.createSocket(req.getHost(), req.getPort());
    } else {/*www.  j  a  v  a2s.co  m*/
        return new Socket(req.getHost(), req.getPort());
    }
}

From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java

private HttpClientConnectionManager createConnectionManager(final Client client, final Configuration config,
        final SSLContext sslContext, final boolean useSystemProperties) {

    final String[] supportedProtocols = useSystemProperties ? split(System.getProperty("https.protocols"))
            : null;// w  w  w.  ja v  a 2  s. com
    final String[] supportedCipherSuites = useSystemProperties ? split(System.getProperty("https.cipherSuites"))
            : null;

    HostnameVerifier hostnameVerifier = client.getHostnameVerifier();

    final LayeredConnectionSocketFactory sslSocketFactory;
    if (sslContext != null) {
        sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites,
                hostnameVerifier);
    } else {
        if (useSystemProperties) {
            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(),
                    supportedProtocols, supportedCipherSuites, hostnameVerifier);
        } else {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), hostnameVerifier);
        }
    }

    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    final Integer chunkSize = ClientProperties.getValue(config.getProperties(),
            ClientProperties.CHUNKED_ENCODING_SIZE, ClientProperties.DEFAULT_CHUNK_SIZE, Integer.class);

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            registry, new ConnectionFactory(chunkSize));

    if (useSystemProperties) {
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            connectionManager.setDefaultMaxPerRoute(max);
            connectionManager.setMaxTotal(2 * max);
        }
    }

    return connectionManager;
}

From source file:cache.reverseproxy.CacheableServicesReverseProxy.java

public static Socket createSecureSocket(String host, int port) throws IOException {
    SSLSocketFactory sslFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();

    SSLSocket newSocket = (SSLSocket) sslFactory.createSocket(host, port);

    newSocket.setUseClientMode(true);//from  w w  w .j  a v  a 2s .com
    newSocket.startHandshake();

    return newSocket;
}

From source file:com.github.dockerjava.jaxrs.connector.ApacheConnector.java

private HttpClientConnectionManager createConnectionManager(final Configuration config,
        final SSLContext sslContext, X509HostnameVerifier hostnameVerifier, final boolean useSystemProperties) {

    final String[] supportedProtocols = useSystemProperties ? split(System.getProperty("https.protocols"))
            : null;//from   w ww . j a v  a2 s .  c o m
    final String[] supportedCipherSuites = useSystemProperties ? split(System.getProperty("https.cipherSuites"))
            : null;

    if (hostnameVerifier == null) {
        hostnameVerifier = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    }

    final LayeredConnectionSocketFactory sslSocketFactory;
    if (sslContext != null) {
        sslSocketFactory = new SSLConnectionSocketFactory(sslContext, supportedProtocols, supportedCipherSuites,
                hostnameVerifier);
    } else {
        if (useSystemProperties) {
            sslSocketFactory = new SSLConnectionSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault(),
                    supportedProtocols, supportedCipherSuites, hostnameVerifier);
        } else {
            sslSocketFactory = new SSLConnectionSocketFactory(SSLContexts.createDefault(), hostnameVerifier);
        }
    }

    final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.getSocketFactory())
            .register("https", sslSocketFactory).build();

    final Integer chunkSize = ClientProperties.getValue(config.getProperties(),
            ClientProperties.CHUNKED_ENCODING_SIZE, 4096, Integer.class);

    final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(
            registry, new ConnectionFactory(chunkSize));

    if (useSystemProperties) {
        String s = System.getProperty("http.keepAlive", "true");
        if ("true".equalsIgnoreCase(s)) {
            s = System.getProperty("http.maxConnections", "5");
            final int max = Integer.parseInt(s);
            connectionManager.setDefaultMaxPerRoute(max);
            connectionManager.setMaxTotal(2 * max);
        }
    }

    return connectionManager;
}