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:org.jgentleframework.utils.network.sockets.SSLSocketTools.java

/**
 * Creates the socket./*w ww  .  j  a  v  a  2  s .c om*/
 * 
 * @param host
 *            the host
 * @param port
 *            the port
 * @param cipherSuites
 *            the cipher suites
 * @return the socket
 */
public Socket createSocket(String host, int port, SSLCipherSuites[] cipherSuites) {

    SSLSocket returnValue = null;
    try {
        java.security.Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        returnValue = (SSLSocket) socketFactory.createSocket(host, port);
        String[] CIPHERS = new String[cipherSuites.length];
        for (int i = 0; i < cipherSuites.length; i++) {
            CIPHERS[i] = cipherSuites[i].name();
        }
        returnValue.setEnabledCipherSuites(CIPHERS);
        return returnValue;
    } catch (IOException e) {
        if (log.isFatalEnabled()) {
            log.fatal("Could not create SSL socket !!", e);
        }
    }
    return returnValue;
}

From source file:com.jkoolcloud.jesl.net.socket.SocketClient.java

/**
 * {@inheritDoc}/*from ww w . j av  a  2  s .co m*/
 */
@Override
public synchronized void connect() throws IOException {
    if (isConnected())
        return;
    if (secure) {
        SocketFactory socketFactory = SSLSocketFactory.getDefault();
        socket = socketFactory.createSocket(host, port);
    } else {
        socket = new Socket(host, port);
    }
    out = new DataOutputStream(socket.getOutputStream());
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

From source file:piecework.config.MongoConfiguration.java

@Bean
@Primary/*w w w.j a  v a2 s.co m*/
public Mongo mongo() throws Exception {
    if (environment.acceptsProfiles("embedded-mongo")) {
        mongoInstance = embeddedMongo();
        mongoInstance.startEmbeddedMongo();
        mongoInstance.importData();
        return new MongoClient(Collections.singletonList(new ServerAddress("127.0.0.1", 37017)));
    }
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    if (environment.getProperty("mongo.use.ssl", Boolean.class, Boolean.FALSE))
        optionsBuilder.socketFactory(SSLSocketFactory.getDefault());

    return new MongoClient(getServerAddresses(), optionsBuilder.build());
}

From source file:org.apache.camel.component.smpp.SmppConnectionFactory.java

public Connection createConnection(String host, int port) throws IOException {
    try {//from   w w  w.j  a  v a 2  s. com
        Socket socket;
        SocketFactory socketFactory;
        socketFactory = config.getUsingSSL() ? SSLSocketFactory.getDefault() : SocketFactory.getDefault();
        if (config.getHttpProxyHost() != null) {
            socket = socketFactory.createSocket(config.getHttpProxyHost(), config.getHttpProxyPort());
            connectProxy(host, port, socket);
        } else {
            socket = socketFactory.createSocket(host, port);
        }
        return new SocketConnection(socket);

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:net.oneandone.sushi.fs.webdav.WebdavRoot.java

public synchronized WebdavConnection allocate() throws IOException {
    int size;/*from   ww  w  . j  a  v a 2s. c o  m*/

    allocated++;
    size = pool.size();
    if (size > 0) {
        return pool.remove(size - 1);
    } else {
        Socket socket;

        if ("https".equals(host.getSchemeName())) {
            socket = SSLSocketFactory.getDefault().createSocket(host.getHostName(), host.getPort());
        } else {
            socket = new Socket(host.getHostName(), host.getPort());
        }
        return WebdavConnection.open(socket, params);
    }
}

From source file:com.digitalpebble.storm.crawler.protocol.http.HttpResponse.java

/**
 * Default public constructor.// w ww  .  j av  a 2  s. c  om
 * 
 * @param http
 * @param url
 * @param knownMetadata
 * @throws IOException
 * @throws HttpException
 */
public HttpResponse(HttpProtocol http, URL url, Metadata knownMetadata) throws IOException, HttpException {

    this.http = http;
    this.url = url;

    Scheme scheme = null;

    if ("http".equals(url.getProtocol())) {
        scheme = Scheme.HTTP;
    } else if ("https".equals(url.getProtocol())) {
        scheme = Scheme.HTTPS;
    } else {
        throw new IOException("Unknown scheme (not http/https) for url:" + url);
    }

    String path = "".equals(url.getFile()) ? "/" : url.getFile();

    // some servers will redirect a request with a host line like
    // "Host: <hostname>:80" to "http://<hpstname>/<orig_path>"- they
    // don't want the :80...

    String host = url.getHost();
    int port;
    String portString;
    if (url.getPort() == -1) {
        if (scheme == Scheme.HTTP) {
            port = 80;
        } else {
            port = 443;
        }
        portString = "";
    } else {
        port = url.getPort();
        portString = ":" + port;
    }
    Socket socket = null;

    try {
        socket = new Socket(); // create the socket
        socket.setSoTimeout(http.getTimeout());

        // connect
        String sockHost = http.useProxy() ? http.getProxyHost() : host;
        int sockPort = http.useProxy() ? http.getProxyPort() : port;
        InetSocketAddress sockAddr = new InetSocketAddress(sockHost, sockPort);
        socket.connect(sockAddr, http.getTimeout());

        if (scheme == Scheme.HTTPS) {
            SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
            SSLSocket sslsocket = (SSLSocket) factory.createSocket(socket, sockHost, sockPort, true);
            sslsocket.setUseClientMode(true);

            // Get the protocols and ciphers supported by this JVM
            Set<String> protocols = new HashSet<String>(Arrays.asList(sslsocket.getSupportedProtocols()));
            Set<String> ciphers = new HashSet<String>(Arrays.asList(sslsocket.getSupportedCipherSuites()));

            // Intersect with preferred protocols and ciphers
            protocols.retainAll(http.getTlsPreferredProtocols());
            ciphers.retainAll(http.getTlsPreferredCipherSuites());

            sslsocket.setEnabledProtocols(protocols.toArray(new String[protocols.size()]));
            sslsocket.setEnabledCipherSuites(ciphers.toArray(new String[ciphers.size()]));

            sslsocket.startHandshake();
            socket = sslsocket;
        }

        this.conf = http.getConf();
        if (ConfUtils.getBoolean(conf, "store.ip.address", false) == true) {
            headers.setValue("_ip_", sockAddr.getAddress().getHostAddress());
        }

        // make request
        OutputStream req = socket.getOutputStream();

        StringBuffer reqStr = new StringBuffer("GET ");
        if (http.useProxy()) {
            reqStr.append(url.getProtocol() + "://" + host + portString + path);
        } else {
            reqStr.append(path);
        }

        reqStr.append(" HTTP/1.0\r\n");

        reqStr.append("Host: ");
        reqStr.append(host);
        reqStr.append(portString);
        reqStr.append("\r\n");

        reqStr.append("Accept-Encoding: x-gzip, gzip, deflate\r\n");

        String userAgent = http.getUserAgent();
        if ((userAgent == null) || (userAgent.length() == 0)) {
            if (HttpProtocol.LOGGER.isErrorEnabled()) {
                HttpProtocol.LOGGER.error("User-agent is not set!");
            }
        } else {
            reqStr.append("User-Agent: ");
            reqStr.append(userAgent);
            reqStr.append("\r\n");
        }

        reqStr.append("Accept-Language: ");
        reqStr.append(this.http.getAcceptLanguage());
        reqStr.append("\r\n");

        reqStr.append("Accept: ");
        reqStr.append(this.http.getAccept());
        reqStr.append("\r\n");

        if (knownMetadata != null) {
            String ifModifiedSince = knownMetadata.getFirstValue("cachedLastModified");
            if (StringUtils.isNotBlank(ifModifiedSince)) {
                reqStr.append("If-Modified-Since: ");
                reqStr.append(ifModifiedSince);
                reqStr.append("\r\n");
            }

            String ifNoneMatch = knownMetadata.getFirstValue("cachedEtag");
            if (StringUtils.isNotBlank(ifNoneMatch)) {
                reqStr.append("If-None-Match: ");
                reqStr.append(ifNoneMatch);
                reqStr.append("\r\n");
            }
        }

        reqStr.append("\r\n");

        // @see http://www.w3.org/Protocols/rfc2068/rfc2068.txt for default
        // charset
        // TODO use UTF-8 and set a charset value explicitely
        byte[] reqBytes = reqStr.toString().getBytes(StandardCharsets.ISO_8859_1);

        req.write(reqBytes);
        req.flush();

        PushbackInputStream in = // process response
                new PushbackInputStream(
                        new BufferedInputStream(socket.getInputStream(), HttpProtocol.BUFFER_SIZE),
                        HttpProtocol.BUFFER_SIZE);

        StringBuffer line = new StringBuffer();

        boolean haveSeenNonContinueStatus = false;
        while (!haveSeenNonContinueStatus) {
            // parse status code line
            this.code = parseStatusLine(in, line);
            // parse headers
            parseHeaders(in, line);
            haveSeenNonContinueStatus = code != 100; // 100 is
                                                     // "Continue"
        }
        String transferEncoding = getHeader(HttpHeaders.TRANSFER_ENCODING);
        if (transferEncoding != null && "chunked".equalsIgnoreCase(transferEncoding.trim())) {
            readChunkedContent(in, line);
        } else {
            readPlainContent(in);
        }

        String contentEncoding = getHeader(HttpHeaders.CONTENT_ENCODING);
        if ("gzip".equals(contentEncoding) || "x-gzip".equals(contentEncoding)) {
            content = http.processGzipEncoded(content, url);
        } else if ("deflate".equals(contentEncoding)) {
            content = http.processDeflateEncoded(content, url);
        } else {
            HttpProtocol.LOGGER.trace("fetched {}  bytes from {}", content.length, url);
        }

    } finally {
        if (socket != null)
            socket.close();
    }

}

From source file:immf.MyWiser.java

private SSLSocketFactory createSslSocketFactory(String keystoreFile, String keyType, String keypasswd) {
    InputStream keyis = null;//from   w ww.  j  a  va 2  s  .c o m
    try {
        keyis = new FileInputStream(keystoreFile);
        KeyStore keyStore = KeyStore.getInstance(keyType);
        keyStore.load(keyis, keypasswd.toCharArray());

        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(keyStore, keypasswd.toCharArray());

        SSLContext context = SSLContext.getInstance("TLS");

        context.init(kmf.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (Exception e) {
        e.printStackTrace();
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    } finally {
        try {
            keyis.close();
        } catch (Exception e) {
        }
    }
}

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/*from   w  w  w . j  a  v  a 2  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:org.lizardirc.beancounter.Beancounter.java

public Beancounter(Properties properties) {
    String botName = properties.getProperty("botName", "Beancounter");
    String botUsername = properties.getProperty("botUsername", "beancounter");
    String serverHost = properties.getProperty("serverHost");
    boolean useTls = Boolean.parseBoolean(properties.getProperty("useTls", "false"));
    boolean verifyHostname = Boolean.parseBoolean(properties.getProperty("verifyHostname", "true"));
    String allowedCertificates = properties.getProperty("allowedCertificates", "");
    int serverPort = Integer.parseInt(properties.getProperty("serverPort", useTls ? "6697" : "6667"));
    String[] autoJoinChannels = properties.getProperty("autoJoinChannels", "").split(",");
    String saslUsername = properties.getProperty("sasl.username", "");
    String saslPassword = properties.getProperty("sasl.password", "");
    boolean autoReconnect = Boolean.parseBoolean(properties.getProperty("autoReconnect", "true"));
    String serverPassword = properties.getProperty("serverPassword", "");

    ExecutorService executorService = constructExecutorService();
    ListenerManager<PircBotX> listenerManager = new ThreadedListenerManager<>(executorService);

    Configuration.Builder<PircBotX> confBuilder = new Configuration.Builder<>().setAutoReconnect(autoReconnect)
            .setName(botName).setLogin(botUsername).setServerHostname(serverHost).setServerPort(serverPort)
            .setListenerManager(listenerManager).setCapEnabled(true) // Of course, the PircBotX documentation doesn't indicate this is necessary....
            .setAutoNickChange(true);//from   www.  ja  v  a  2s.co  m

    Listeners<PircBotX> listeners = new Listeners<>(executorService, constructScheduledExecutorService(),
            confBuilder.getListenerManager(), properties);
    listeners.register();

    if (useTls) {
        SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        if (verifyHostname) {
            socketFactory = new VerifyingSslSocketFactory(serverHost, socketFactory);
        }
        List<String> fingerprints = Arrays.stream(allowedCertificates.split(",")).filter(s -> !s.isEmpty())
                .collect(Collectors.toList());
        if (fingerprints.size() > 0) {
            socketFactory = new FingerprintingSslSocketFactory(fingerprints, socketFactory);
        }
        confBuilder.setSocketFactory(socketFactory);
    }

    for (String channel : autoJoinChannels) {
        confBuilder.addAutoJoinChannel(channel);
    }

    if (!saslUsername.isEmpty() && !saslPassword.isEmpty()) {
        confBuilder.addCapHandler(new SASLCapHandler(saslUsername, saslPassword));
    }

    if (!serverPassword.isEmpty()) {
        confBuilder.setServerPassword(serverPassword);
    }

    setVersionString(confBuilder);

    bot = new PircBotX(confBuilder.buildConfiguration());
}

From source file:org.mule.module.gcm.CcsConnector.java

/**
 * Connect and authenticate to the CSS server.
 * /*from w  ww  .  jav a  2s. com*/
 * @param projectId The project ID (aka sender ID).
 * @throws ConnectionException throw in case connecting to the CCS server fails.
 */
@Connect
public void connect(@ConnectionKey final String projectId) throws ConnectionException {
    this.projectId = projectId;

    try {
        final ConnectionConfiguration config = new ConnectionConfiguration("gcm.googleapis.com", 5235);
        config.setCompressionEnabled(true);
        config.setSASLAuthenticationEnabled(true);
        config.setSocketFactory(SSLSocketFactory.getDefault());
        xmppConnection = new XMPPConnection(config);
        xmppConnection.connect();

        if (!xmppConnection.isConnected()) {
            throw new ConnectionException(ConnectionExceptionCode.CANNOT_REACH, null,
                    "XMPP connection failed to: "
                            + ToStringBuilder.reflectionToString(config, ToStringStyle.SHORT_PREFIX_STYLE));
        }
    } catch (final XMPPException xmppe) {
        throw new ConnectionException(ConnectionExceptionCode.CANNOT_REACH, null, xmppe.getMessage(), xmppe);
    }

    try {
        xmppConnection.login(getLoginUser(), getApiKey());
        xmppConnection.getChatManager().addChatListener(new ChatManagerListener() {
            @Override
            public void chatCreated(final Chat chat, final boolean createdLocally) {
                if (!createdLocally) {
                    CcsConnector.this.chat = chat;
                    chat.addMessageListener(new MessageListener() {
                        @Override
                        public void processMessage(final Chat chat, final Message message) {
                            try {
                                handleInboundMessage(message);
                            } catch (final Exception e) {
                                logger.error("Failed to handle inbound message: " + message, e);
                            }
                        }
                    });
                }
            }
        });
    } catch (final XMPPException xmppe) {
        throw new ConnectionException(ConnectionExceptionCode.INCORRECT_CREDENTIALS, null, xmppe.getMessage(),
                xmppe);
    }
}