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:run.var.teamcity.cloud.docker.client.apcon.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;/*from   w ww . j a v a 2 s .c om*/
    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(
                    org.apache.http.conn.ssl.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:org.eclipse.wst.ws.internal.explorer.platform.wsdl.transport.HTTPTransport.java

private Socket buildSocket(URL url) throws UnknownHostException, IOException {
    Socket s = null;/*from  w w w . j ava2  s  .  co m*/
    String host = url.getHost();
    int port = url.getPort();
    String proxyHost = System.getProperty(SYS_PROP_HTTP_PROXY_HOST);
    int proxyPort = Integer.getInteger(SYS_PROP_HTTP_PROXY_PORT, DEFAULT_HTTP_PORT).intValue();

    String nonProxyHosts = System.getProperty(SYS_PROP_HTTP_NON_PROXY_HOSTS);

    //  String proxyUserName = System.getProperty(SYS_PROP_HTTP_PROXY_USER_NAME);
    //  String proxyPassword = System.getProperty(SYS_PROP_HTTP_PROXY_PASSWORD);
    if (url.getProtocol().equalsIgnoreCase(HTTPS)) {
        proxyHost = System.getProperty(SYS_PROP_HTTPS_PROXY_HOST);
        proxyPort = Integer.getInteger(SYS_PROP_HTTPS_PROXY_PORT, DEFAULT_HTTPS_PORT).intValue();
        nonProxyHosts = System.getProperty(SYS_PROP_HTTPS_NON_PROXY_HOSTS);

        if (proxyHost != null && proxyHost.length() > 0
                && !isHostInNonProxyHosts(host, nonProxyHosts, DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME)) {
            // SSL with proxy server
            Socket tunnel = buildTunnelSocket(url, proxyHost, proxyPort);
            s = ((SSLSocketFactory) SSLSocketFactory.getDefault()).createSocket(tunnel, host, port, true);
        } else
            s = SSLSocketFactory.getDefault().createSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT));
        // Removing dependency on soap.jar
        //  s = SSLUtils.buildSSLSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT), proxyHost, proxyPort);
        // TODO:
        // Build an SSL socket that supports proxyUser and proxyPassword,
        // as demonstrated in the following (original) line of code:
        //  s = SSLUtils.buildSSLSocket(host, (port > 0 ? port : DEFAULT_HTTPS_PORT), proxyHost, proxyPort, proxyUserName, proxyPassword);
    } else if (proxyHost != null && proxyHost.length() > 0
            && !isHostInNonProxyHosts(host, nonProxyHosts, DEFAULT_CASE_SENSITIVE_FOR_HOST_NAME))
        s = new Socket(proxyHost, proxyPort);
    else
        s = new Socket(host, (port > 0 ? port : DEFAULT_HTTP_PORT));
    return s;
}

From source file:org.ejbca.core.protocol.ocsp.OCSPUnidClient.java

private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {

    final KeyManager km[];
    final TrustManager tm[];

    // Put the key and certs in the user keystore (if available)
    if (this.ks != null) {
        final KeyManagerFactory kmf;
        kmf = KeyManagerFactory.getInstance("SunX509");
        kmf.init(this.ks, this.passphrase.toCharArray());
        km = kmf.getKeyManagers();//from  w  w  w  .j a v a 2  s.  c  om
    } else {
        km = null;
    }
    // Now make a truststore to verify the server
    if (this.certChain != null && this.certChain.length > 0) {
        final KeyStore trustks = KeyStore.getInstance("jks");
        trustks.load(null, "foo123".toCharArray());
        // add trusted CA cert
        trustks.setCertificateEntry("trusted", this.certChain[this.certChain.length - 1]);
        final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
        tmf.init(trustks);
        tm = tmf.getTrustManagers();
    } else {
        tm = null;
    }
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);

    return ctx.getSocketFactory();
}

From source file:com.techcavern.pircbotz.InputParser.java

/**
 * Process any lines relevant to connect. Only called before bot is logged into the server
 * @param rawLine Raw, unprocessed line from the server
 * @param code //from w w  w  .ja v  a2  s .  c o m
 * @param target
 * @param parsedLine Processed line
 * @throws IrcException If the server rejects the bot (nick already in use or a 4** or 5** code
 * @throws IOException If an error occurs during upgrading to SSL
 */
public void processConnect(String rawLine, String code, String target, List<String> parsedLine)
        throws IrcException, IOException {
    if (CONNECT_CODES.contains(code)) {
        // We're connected to the server.
        bot.loggedIn(configuration.getName() + (nickSuffix == 0 ? "" : nickSuffix));
        log.debug("Logged onto server.");

        configuration.getListenerManager().dispatchEvent(new ConnectEvent<PircBotZ>(bot));

        //Handle automatic on connect stuff
        if (configuration.getNickservPassword() != null)
            bot.sendIRC().identify(configuration.getNickservPassword());
        ImmutableMap<String, String> autoConnectChannels = bot.reconnectChannels();
        if (autoConnectChannels == null)
            autoConnectChannels = configuration.getAutoJoinChannels();
        for (Map.Entry<String, String> channelEntry : autoConnectChannels.entrySet())
            bot.sendIRC().joinChannel(channelEntry.getKey(), channelEntry.getValue());
    } else if (code.equals("433")) {
        //EXAMPLE: * AnAlreadyUsedName :Nickname already in use
        //Nickname in use, rename
        String usedNick = parsedLine.get(1);
        boolean autoNickChange = configuration.isAutoNickChange();
        String autoNewNick = null;
        if (autoNickChange) {
            nickSuffix++;
            bot.sendIRC().changeNick(autoNewNick = configuration.getName() + nickSuffix);
        }
        configuration.getListenerManager()
                .dispatchEvent(new NickAlreadyInUseEvent<PircBotZ>(bot, usedNick, autoNewNick, autoNickChange));
    } else if (code.equals("439")) {
        //EXAMPLE: PircBotX: Target change too fast. Please wait 104 seconds
        // No action required.
        //TODO: Should we delay joining channels here or something?
        log.warn("Ignoring too fast error");
    } else if (configuration.isCapEnabled() && code.equals("421") && parsedLine.get(1).equals("CAP")) {
        //EXAMPLE: 421 you CAP :Unknown command
        log.warn("Ignoring unknown command error, server does not support CAP negotiation");
    } else if (configuration.isCapEnabled() && code.equals("451") && target.equals("CAP")) {
        //EXAMPLE: 451 CAP :You have not registered
        //Ignore, this is from servers that don't support CAP
        log.warn("Ignoring not registered error, server does not support CAP negotiation");
    } else if (code.startsWith("5") || code.startsWith("4"))
        throw new IrcException(IrcException.Reason.CannotLogin, "Received error: " + rawLine);
    else if (code.equals("670")) {
        //Server is saying that we can upgrade to TLS
        SSLSocketFactory sslSocketFactory = ((SSLSocketFactory) SSLSocketFactory.getDefault());
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            if (curCapHandler instanceof TLSCapHandler)
                sslSocketFactory = ((TLSCapHandler) curCapHandler).getSslSocketFactory();
        SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(bot.getSocket(),
                bot.getLocalAddress().getHostAddress(), bot.getSocket().getPort(), true);
        sslSocket.startHandshake();
        bot.changeSocket(sslSocket);
        //Notify CAP Handlers
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            curCapHandler.handleUnknown(bot, rawLine);
    } else if (code.equals("CAP")) {
        //Handle CAP Code; remove extra from params
        String capCommand = parsedLine.get(1);
        ImmutableList<String> capParams = ImmutableList.copyOf(StringUtils.split(parsedLine.get(2)));
        if (capCommand.equals("LS"))
            for (CapHandler curCapHandler : configuration.getCapHandlers()) {
                log.debug("Executing cap handler " + curCapHandler);
                if (curCapHandler.handleLS(bot, capParams)) {
                    log.debug("Cap handler " + curCapHandler + " finished");
                    capHandlersFinished.add(curCapHandler);
                }
            }
        else if (capCommand.equals("ACK")) {
            //Server is enabling a capability, store that
            bot.getEnabledCapabilities().addAll(capParams);

            for (CapHandler curCapHandler : configuration.getCapHandlers())
                if (curCapHandler.handleACK(bot, capParams)) {
                    log.trace("Removing cap handler " + curCapHandler);
                    capHandlersFinished.add(curCapHandler);
                }
        } else if (capCommand.equals("NAK")) {
            for (CapHandler curCapHandler : configuration.getCapHandlers())
                if (curCapHandler.handleNAK(bot, capParams))
                    capHandlersFinished.add(curCapHandler);
        } else
            //Maybe the CapHandlers know how to use it
            for (CapHandler curCapHandler : configuration.getCapHandlers())
                if (curCapHandler.handleUnknown(bot, rawLine))
                    capHandlersFinished.add(curCapHandler);
    } else
        //Pass to CapHandlers, could be important
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            if (curCapHandler.handleUnknown(bot, rawLine))
                capHandlersFinished.add(curCapHandler);

    //Send CAP END if all CapHandlers are finished
    if (configuration.isCapEnabled() && !capEndSent
            && capHandlersFinished.containsAll(configuration.getCapHandlers())) {
        capEndSent = true;
        bot.sendCAP().end();
        bot.enabledCapabilities = Collections.unmodifiableList(bot.enabledCapabilities);
    }
}

From source file:ed.net.httpclient.HttpConnection.java

public static SSLSocketFactory getDefaultSSLSocketFactory() {
    SocketFactory f = SSLSocketFactory.getDefault();
    return (SSLSocketFactory) f;
}

From source file:org.pircbotx.InputParser.java

/**
 * Process any lines relevant to connect. Only called before bot is logged
 * into the server/*from   www.j a  v a2s . com*/
 *
 * @param rawLine Raw, unprocessed line from the server
 * @param code
 * @param target
 * @param parsedLine Processed line
 * @throws IrcException If the server rejects the bot (nick already in use
 * or a 4** or 5** code
 * @throws IOException If an error occurs during upgrading to SSL
 */
public void processConnect(String rawLine, String code, String target, List<String> parsedLine)
        throws IrcException, IOException {
    if (CONNECT_CODES.contains(code)) {
        // We're connected to the server.
        bot.onLoggedIn(parsedLine.get(0));
        log.debug("Logged onto server.");

        configuration.getListenerManager().dispatchEvent(new ConnectEvent(bot));

        //Handle automatic on connect stuff
        if (configuration.getNickservPassword() != null)
            bot.sendIRC().identify(configuration.getNickservPassword());
        ImmutableMap<String, String> autoConnectChannels = bot.reconnectChannels();
        if (autoConnectChannels == null)
            if (configuration.isNickservDelayJoin())
                autoConnectChannels = ImmutableMap.of();
            else
                autoConnectChannels = configuration.getAutoJoinChannels();
        for (Map.Entry<String, String> channelEntry : autoConnectChannels.entrySet())
            bot.sendIRC().joinChannel(channelEntry.getKey(), channelEntry.getValue());
    } else if (code.equals("439"))
        //EXAMPLE: PircBotX: Target change too fast. Please wait 104 seconds
        // No action required.
        //TODO: Should we delay joining channels here or something?
        log.warn("Ignoring too fast error");
    else if (configuration.isCapEnabled() && code.equals("421") && parsedLine.get(1).equals("CAP"))
        //EXAMPLE: 421 you CAP :Unknown command
        log.warn("Ignoring unknown command error, server does not support CAP negotiation");
    else if (configuration.isCapEnabled() && code.equals("451") && target.equals("CAP")) {
        //EXAMPLE: 451 CAP :You have not registered
        //Ignore, this is from servers that don't support CAP
        log.warn("Ignoring not registered error, server does not support CAP negotiation");
    } else if (configuration.isCapEnabled() && code.equals("410") && parsedLine.get(1).contains("CAP")) {
        //EXAMPLE: 410 :Invalid CAP command
        //Ignore, Twitch.tv uses this code for some reason
        log.warn("Ignoring invalid command error, server does not support CAP negotiation");
    } else if ((code.startsWith("5") || code.startsWith("4")) && !code.equals("433"))
        //Ignore 433 NickAlreadyInUse, handled later
        throw new IrcException(IrcException.Reason.CannotLogin, "Received error: " + rawLine);
    else if (code.equals("670")) {
        //Server is saying that we can upgrade to TLS
        log.debug("Upgrading to TLS connection");
        SSLSocketFactory sslSocketFactory = ((SSLSocketFactory) SSLSocketFactory.getDefault());
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            if (curCapHandler instanceof TLSCapHandler)
                sslSocketFactory = ((TLSCapHandler) curCapHandler).getSslSocketFactory();
        SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(bot.getSocket(),
                bot.getLocalAddress().getHostAddress(), bot.getSocket().getPort(), true);
        sslSocket.startHandshake();
        bot.changeSocket(sslSocket);

        //Notify CAP Handlers
        for (CapHandler curCapHandler : configuration.getCapHandlers())
            if (curCapHandler.handleUnknown(bot, rawLine))
                addCapHandlerFinished(curCapHandler);
    } else if (code.equals("CAP") && configuration.isCapEnabled()) {
        //Handle CAP Code; remove extra from params
        String capCommand = parsedLine.get(1);
        ImmutableList<String> capParams = ImmutableList.copyOf(StringUtils.split(parsedLine.get(2)));
        if (capCommand.equals("LS")) {
            log.debug("Starting Cap Handlers {}", getCapHandlersRemaining());
            for (CapHandler curCapHandler : getCapHandlersRemaining()) {
                if (curCapHandler.handleLS(bot, capParams))
                    addCapHandlerFinished(curCapHandler);
            }
        } else if (capCommand.equals("ACK")) {
            //Server is enabling a capability, store that
            bot.getEnabledCapabilities().addAll(capParams);

            for (CapHandler curCapHandler : getCapHandlersRemaining())
                if (curCapHandler.handleACK(bot, capParams))
                    addCapHandlerFinished(curCapHandler);
        } else if (capCommand.equals("NAK")) {
            for (CapHandler curCapHandler : getCapHandlersRemaining())
                if (curCapHandler.handleNAK(bot, capParams))
                    addCapHandlerFinished(curCapHandler);
        } else {
            //Maybe the CapHandlers know how to use it
            for (CapHandler curCapHandler : getCapHandlersRemaining())
                if (curCapHandler.handleUnknown(bot, rawLine))
                    addCapHandlerFinished(curCapHandler);
        }
    } else
        //Pass to CapHandlers, could be important
        for (CapHandler curCapHandler : getCapHandlersRemaining())
            if (curCapHandler.handleUnknown(bot, rawLine))
                addCapHandlerFinished(curCapHandler);
}

From source file:org.ejbca.core.protocol.ws.CommonEjbcaWS.java

/** Getting SSL socket factory using the Admin cert created for client certificate authentication **/
private SSLSocketFactory getSSLFactory() throws IOException, NoSuchAlgorithmException,
        UnrecoverableKeyException, KeyStoreException, CertificateException, KeyManagementException {
    // Put the key and certs in the user keystore (if available)
    java.security.KeyStore ks = java.security.KeyStore.getInstance("jks");
    ks.load(new FileInputStream(TEST_ADMIN_FILE), PASSWORD.toCharArray());
    final KeyManagerFactory kmf;
    kmf = KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks, PASSWORD.toCharArray());
    final KeyManager km[] = kmf.getKeyManagers();

    final TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);//  ww  w  .  ja  va 2s.  com
    final TrustManager tm[] = tmf.getTrustManagers();
    if (km == null && tm == null) {
        return (SSLSocketFactory) SSLSocketFactory.getDefault();
    }
    final SSLContext ctx = SSLContext.getInstance("TLS");
    ctx.init(km, tm, null);
    return ctx.getSocketFactory();
}

From source file:net.jotel.ws.client.WebSocketClient.java

private Socket createSocket() throws IOException {
    Socket s;/*from  w ww  .  ja  va  2 s  .c  om*/
    if (secure) {
        SocketFactory factory = SSLSocketFactory.getDefault();
        s = factory.createSocket(host, port);
    } else {
        s = new Socket(host, port);
    }
    s.setKeepAlive(true);
    s.setSoTimeout(100000);

    return s;
}

From source file:io.fabric8.kubernetes.api.KubernetesHelper.java

public static boolean isServiceSsl(String host, int port, boolean trustAllCerts) {
    try {// ww w.jav  a2s. c  o m
        SSLSocketFactory sslsocketfactory = null;
        if (trustAllCerts) {
            sslsocketfactory = KubernetesFactory.TrustEverythingSSLTrustManager.getTrustingSSLSocketFactory();
        } else {
            sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        }

        Socket socket = sslsocketfactory.createSocket();

        // Connect, with an explicit timeout value
        socket.connect(new InetSocketAddress(host, port), 1 * 1000);
        try {

            InputStream in = socket.getInputStream();
            OutputStream out = socket.getOutputStream();

            // Write a test byte to get a reaction :)
            out.write(1);

            while (in.available() > 0) {
                System.out.print(in.read());
            }

            return true;
        } finally {
            socket.close();
        }
    } catch (SSLHandshakeException e) {
        LOG.error(
                "SSL handshake failed - this probably means that you need to trust the kubernetes root SSL certificate or set the environment variable "
                        + KubernetesFactory.KUBERNETES_TRUST_ALL_CERIFICATES,
                e);
    } catch (SSLProtocolException e) {
        LOG.error("SSL protocol error", e);
    } catch (SSLKeyException e) {
        LOG.error("Bad SSL key", e);
    } catch (SSLPeerUnverifiedException e) {
        LOG.error("Could not verify server", e);
    } catch (SSLException e) {
        LOG.debug("Address does not appear to be SSL-enabled - falling back to http", e);
    } catch (IOException e) {
        LOG.debug("Failed to validate service", e);
    }
    return false;
}