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:pw.dedominic.airc.App.java

/**
 * Generates PircBotX config//from  w  w  w.  jav a 2s  .c o m
 *
 * @param selectedServer the selected server
 * @return the config
 */
private Configuration generateConnectConfig(Server selectedServer) {

    Configuration.Builder configBuilder = new Configuration.Builder();
    configBuilder.setName(selectedServer.getNick()).setAutoNickChange(true) // prevents collisions
            .addServer(selectedServer.getHost()).addAutoJoinChannels(selectedServer.getChannels())
            .addListener(new ConnectionListener(handler));

    if (selectedServer.isTls()) {
        if (settings.overrideTlsCheck()) {
            configBuilder.setSocketFactory(new UtilSSLSocketFactory().trustAllCertificates());
        } else {
            configBuilder.setSocketFactory(SSLSocketFactory.getDefault());
        }
    }
    if (!selectedServer.getPassword().equals(""))
        configBuilder.setServerPassword(selectedServer.getPassword());
    if (!selectedServer.getNickpass().equals(""))
        configBuilder.setNickservPassword(selectedServer.getNickpass());

    return configBuilder.buildConfiguration();
}

From source file:com.mch.registry.ccs.server.CcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 *
 * @throws XMPPException//from   ww  w  .ja 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:tsauto.TcpMsgReceiverAlphaFlashStream.java

private Socket createSocket(String host, int port, boolean useSSL) throws UnknownHostException, IOException {
    Socket socket = null;/*w  ww  .  j a va 2  s.com*/

    if (useSSL) {
        socket = SSLSocketFactory.getDefault().createSocket(host, port);
    } else {
        socket = new Socket(host, port);
    }

    return socket;
}

From source file:com.wealdtech.gcm.GCMClient.java

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

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

    connection = new XMPPTCPConnection(config);
    try {
        connection.connect();
    } catch (final SmackException e) {
        throw new ServerError("Smack exception", e);
    } catch (final IOException e) {
        throw new ServerError("IO exception", e);
    }

    connection.addConnectionListener(new ConnectionListener() {

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

        @Override
        public void reconnectionFailed(Exception e) {
            LOGGER.info("Reconnection failed.. ", e);
        }

        @Override
        public void reconnectingIn(int seconds) {
            LOGGER.info("Reconnecting in {} secs", seconds);
        }

        @Override
        public void connectionClosedOnError(Exception e) {
            LOGGER.info("Connection closed on error.");
        }

        @Override
        public void connected(final XMPPConnection connection) {
            LOGGER.info("Connected.");
        }

        @Override
        public void authenticated(final XMPPConnection connection) {
            LOGGER.info("Authenticated.");
        }

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

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

        @Override
        public void processPacket(Packet packet) {
            LOGGER.info("Received: {}", packet.toXML());
            final Message incomingMessage = (Message) packet;
            final GcmPacketExtension gcmPacket = (GcmPacketExtension) incomingMessage
                    .getExtension(GCM_NAMESPACE);
            final String json = gcmPacket.getJson();
            try {
                final Map<String, Object> jsonObject = WealdMapper.getMapper().readValue(json,
                        new TypeReference<Map<String, Object>>() {
                        });

                // present for "ack"/"nack", null otherwise
                final 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.warn("Unrecognized message type {}", messageType.toString());
                }
            } catch (JsonMappingException e) {
                LOGGER.error("Error mapping JSON {}: {}", json, e.getMessage());
            } catch (JsonParseException e) {
                LOGGER.error("Error parsing JSON {}: {}", json, e.getMessage());
            } catch (IOException e) {
                LOGGER.error("General IO error", e);
            }
        }
    }, new PacketTypeFilter(Message.class));

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

    try {
        connection.login(username, password);
    } catch (SmackException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.sonarqube.ws.client.HttpConnectorTest.java

@Test
public void support_tls_versions_of_java8() {
    underTest = HttpConnector.newBuilder().url(serverUrl).build();

    assertTlsAndClearTextSpecifications(underTest);
    assertThat(underTest.okHttpClient().sslSocketFactory())
            .isInstanceOf(SSLSocketFactory.getDefault().getClass());
}

From source file:de.fun2code.google.cloudprint.push.PushReceiver.java

/**
 * Sets up the SSL socket for use with XMPP.
 * /* w  ww. j  ava 2s .c o m*/
 * @param socket
 *            the socket to do TLS over.
 * @return   The SSL Socket.
 * @throws IOException
 */
public static SSLSocket setupSSLSocket(Socket socket) throws NoSuchAlgorithmException, KeyManagementException,
        KeyStoreException, UnrecoverableKeyException, IOException {
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    TrustManagerFactory tfactory = TrustManagerFactory.getInstance("SunPKIX");
    tfactory.init(keyStore);
    SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
    SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, socket.getInetAddress().getHostAddress(),
            socket.getPort(), true);
    sslsocket.setUseClientMode(true);
    return sslsocket;
}

From source file:org.codinjutsu.tools.mongo.logic.MongoManager.java

private MongoClient createMongoClient(ServerConfiguration configuration) throws UnknownHostException {
    List<String> serverUrls = configuration.getServerUrls();
    String username = configuration.getUsername();
    String password = configuration.getPassword();
    String userDatabase = configuration.getUserDatabase();
    if (serverUrls.isEmpty()) {
        throw new ConfigurationException("server host is not set");
    }/*from  ww w  . jav  a 2  s  .co  m*/

    List<ServerAddress> serverAddresses = new LinkedList<ServerAddress>();
    for (String serverUrl : serverUrls) {
        String[] host_port = serverUrl.split(":");
        serverAddresses.add(new ServerAddress(host_port[0], Integer.valueOf(host_port[1])));
    }

    MongoClientOptions.Builder optionBuilder = MongoClientOptions.builder();
    if (configuration.isSslConnection()) {
        optionBuilder.socketFactory(SSLSocketFactory.getDefault());
    }

    if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
        MongoCredential credential = MongoCredential.createMongoCRCredential(username, userDatabase,
                password.toCharArray());
        return new MongoClient(serverAddresses, Arrays.asList(credential), optionBuilder.build());
    }
    return new MongoClient(serverAddresses, optionBuilder.build());
}

From source file:com.apteligent.ApteligentJavaClient.java

/*********************************************************************************************************************/

private Token auth(String email, String password) throws IOException {
    String urlParameters = "grant_type=password&username=" + email + "&password=" + password;

    URL obj = new URL(API_TOKEN);
    HttpsURLConnection conn = (HttpsURLConnection) obj.openConnection();
    conn.setSSLSocketFactory((SSLSocketFactory) SSLSocketFactory.getDefault());
    conn.setDoOutput(true);/*  w  w w  . ja  v a  2s. co m*/
    conn.setDoInput(true);

    //add request header
    String basicAuth = new String(Base64.encodeBytes(apiKey.getBytes()));
    conn.setRequestProperty("Authorization", String.format("Basic %s", basicAuth));
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Content-Length", Integer.toString(urlParameters.getBytes().length));
    conn.setRequestMethod("POST");

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

    // read token
    JsonFactory jsonFactory = new JsonFactory();
    JsonParser jp = jsonFactory.createParser(conn.getInputStream());
    ObjectMapper mapper = getObjectMapper();
    Token token = mapper.readValue(jp, Token.class);

    return token;
}

From source file:com.grokkingandroid.sampleapp.samples.gcm.ccs.server.CcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 * @throws XMPPException//from   ww w .j a  va2  s .  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(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();
            logger.log(Level.INFO, "json []: " + 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(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:net.vidainc.home.server.xmpp.CcsClient.java

/**
 * Connects to GCM Cloud Connection Server using the supplied credentials.
 * /*from w  w w . java 2s  .co m*/
 * @throws XMPPException
 */
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);
}