Example usage for javax.net.ssl SSLSocket startHandshake

List of usage examples for javax.net.ssl SSLSocket startHandshake

Introduction

In this page you can find the example usage for javax.net.ssl SSLSocket startHandshake.

Prototype

public abstract void startHandshake() throws IOException;

Source Link

Document

Starts an SSL handshake on this connection.

Usage

From source file:com.serphacker.serposcope.scraper.http.extensions.ScrapClientSSLConnectionFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/* w w w  .j  ava  2  s .  c  o m*/
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        HostnameVerifier hostnameVerifier = insecure ? insecureHostnameVerifier : defaultHostnameVerifier;
        if (!hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:org.pircbotx.InputParser.java

/**
 * Process any lines relevant to connect. Only called before bot is logged
 * into the server/*from   www.ja  va 2  s .  c  om*/
 *
 * @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.beepcore.beep.profile.tls.jsse.TLSProfileJSSE.java

public void receiveMSG(MessageMSG msg) {
    Channel channel = msg.getChannel();

    InputDataStreamAdapter is = msg.getDataStream().getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    String data;//from   w  w w  .ja v  a2s.  com

    try {
        try {
            data = reader.readLine();
        } catch (IOException e) {
            msg.sendERR(BEEPError.CODE_PARAMETER_ERROR, "Error reading data");
            return;
        }

        if (data.equals(READY1) == false && data.equals(READY2) == false) {
            msg.sendERR(BEEPError.CODE_PARAMETER_INVALID, "Expected READY element");
        }

        this.begin(channel);

        msg.sendRPY(new StringOutputDataStream(PROCEED2));
    } catch (BEEPException e1) {
        channel.getSession().terminate("unable to send ERR");
        return;
    }

    try {
        Socket oldSocket = ((TCPSession) channel.getSession()).getSocket();
        /** @TODO add support for serverName */
        SSLSocket newSocket = (SSLSocket) socketFactory.createSocket(oldSocket,
                oldSocket.getInetAddress().getHostName(), oldSocket.getPort(), true);

        BeepListenerHCL l = new BeepListenerHCL(channel);

        newSocket.addHandshakeCompletedListener(l);
        newSocket.setUseClientMode(false);
        newSocket.setNeedClientAuth(needClientAuth);
        newSocket.setEnabledCipherSuites(newSocket.getSupportedCipherSuites());
        if (sslProtocols != null) {
            newSocket.setEnabledProtocols(sslProtocols);
        }

        newSocket.startHandshake();
    } catch (IOException e) {
        channel.getSession().terminate("TLS error: " + e.getMessage());
        return;
    }
}

From source file:me.mneri.rice.Connection.java

public void start() {
    if (mState != State.CLOSED)
        return;//from  w w w  .j av  a2s.  c o  m

    mState = State.STARTED;
    emit(new Event(START, this));

    new Thread(() -> {
        try {
            if (mSecure) {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                String algorithm = TrustManagerFactory.getDefaultAlgorithm();
                TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(algorithm);
                tmFactory.init((KeyStore) null);
                sslContext.init(null, tmFactory.getTrustManagers(), null);
                SSLSocketFactory sslFactory = sslContext.getSocketFactory();
                SSLSocket sslSocket = (SSLSocket) sslFactory.createSocket(mHost, mPort);
                sslSocket.startHandshake();
                mSocket = sslSocket;
            } else {
                mSocket = new Socket(mHost, mPort);
            }

            mSocket.setSoTimeout(mSoTimeout);
            mInputThread = new InputThread(mSocket.getInputStream(), mEncoding, new InputThreadObserver());
            mInputThread.start();
            OutputInterfaceFactory outFactory = OutputInterfaceFactory.instance();
            OutputStreamWriter outWriter = new OutputStreamWriter(mSocket.getOutputStream(), mEncoding);
            mOutputInterface = outFactory.createInterface(outWriter);

            mState = State.CONNECTED;
            emit(new Event(CONNECT, this));
            cap("LS");

            if (!TextUtils.isEmpty(mPass))
                pass(mPass);

            nick(mWantedNick);
            user(mUser, mLoginMode, "*", mReal);
        } catch (Exception e) {
            onDisconnection();
        }
    }).start();
}

From source file:org.apache.geode.internal.net.SocketCreator.java

/**
 * Will be a server socket... this one simply registers the listeners.
 *///  w  ww  .ja v  a  2 s . c  o  m
public void configureServerSSLSocket(Socket socket) throws IOException {
    if (socket instanceof SSLSocket) {
        SSLSocket sslSocket = (SSLSocket) socket;
        try {
            sslSocket.startHandshake();
            SSLSession session = sslSocket.getSession();
            Certificate[] peer = session.getPeerCertificates();
            if (logger.isDebugEnabled()) {
                logger.debug(LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0,
                        ((X509Certificate) peer[0]).getSubjectDN()));
            }
        } catch (SSLPeerUnverifiedException ex) {
            if (this.sslConfig.isRequireAuth()) {
                logger.fatal(
                        LocalizedMessage.create(
                                LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER_0_1,
                                new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                        ex);
                throw ex;
            }
        } catch (SSLException ex) {
            logger.fatal(
                    LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
                            new Object[] { socket.getInetAddress(), Integer.valueOf(socket.getPort()) }),
                    ex);
            throw ex;
        }
    }
}

From source file:com.newrelic.agent.deps.org.apache.http.conn.ssl.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {/*from w w w  .  j a va  2s .  c  om*/
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        if (this.log.isDebugEnabled()) {
            this.log.debug("Secure session established");
            this.log.debug(" negotiated protocol: " + session.getProtocol());
            this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());

            try {

                final Certificate[] certs = session.getPeerCertificates();
                final X509Certificate x509 = (X509Certificate) certs[0];
                final X500Principal peer = x509.getSubjectX500Principal();

                this.log.debug(" peer principal: " + peer.toString());
                final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                }

                final X500Principal issuer = x509.getIssuerX500Principal();
                this.log.debug(" issuer principal: " + issuer.toString());
                final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                        if (!aC.isEmpty()) {
                            altNames.add((String) aC.get(1));
                        }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                }
            } catch (Exception ignore) {
            }
        }

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

From source file:info.guardianproject.netcipher.client.SSLConnectionSocketFactory.java

private void verifyHostname(final SSLSocket sslsock, final String hostname) throws IOException {
    try {//from  ww w. j  ava2  s .c o  m
        SSLSession session = sslsock.getSession();
        if (session == null) {
            // In our experience this only happens under IBM 1.4.x when
            // spurious (unrelated) certificates show up in the server'
            // chain.  Hopefully this will unearth the real problem:
            final InputStream in = sslsock.getInputStream();
            in.available();
            // If ssl.getInputStream().available() didn't cause an
            // exception, maybe at least now the session is available?
            session = sslsock.getSession();
            if (session == null) {
                // If it's still null, probably a startHandshake() will
                // unearth the real problem.
                sslsock.startHandshake();
                session = sslsock.getSession();
            }
        }
        if (session == null) {
            throw new SSLHandshakeException("SSL session not available");
        }

        /*
              if (this.log.isDebugEnabled()) {
                this.log.debug("Secure session established");
                this.log.debug(" negotiated protocol: " + session.getProtocol());
                this.log.debug(" negotiated cipher suite: " + session.getCipherSuite());
                
                try {
                
                  final Certificate[] certs = session.getPeerCertificates();
                  final X509Certificate x509 = (X509Certificate) certs[0];
                  final X500Principal peer = x509.getSubjectX500Principal();
                
                  this.log.debug(" peer principal: " + peer.toString());
                  final Collection<List<?>> altNames1 = x509.getSubjectAlternativeNames();
                  if (altNames1 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames1) {
                      if (!aC.isEmpty()) {
        altNames.add((String) aC.get(1));
                      }
                    }
                    this.log.debug(" peer alternative names: " + altNames);
                  }
                
                  final X500Principal issuer = x509.getIssuerX500Principal();
                  this.log.debug(" issuer principal: " + issuer.toString());
                  final Collection<List<?>> altNames2 = x509.getIssuerAlternativeNames();
                  if (altNames2 != null) {
                    final List<String> altNames = new ArrayList<String>();
                    for (final List<?> aC : altNames2) {
                      if (!aC.isEmpty()) {
        altNames.add((String) aC.get(1));
                      }
                    }
                    this.log.debug(" issuer alternative names: " + altNames);
                  }
                } catch (Exception ignore) {
                }
              }
        */

        if (!this.hostnameVerifier.verify(hostname, session)) {
            final Certificate[] certs = session.getPeerCertificates();
            final X509Certificate x509 = (X509Certificate) certs[0];
            final X500Principal x500Principal = x509.getSubjectX500Principal();
            throw new SSLPeerUnverifiedException("Host name '" + hostname + "' does not match "
                    + "the certificate subject provided by the peer (" + x500Principal.toString() + ")");
        }
        // verifyHostName() didn't blowup - good!
    } catch (final IOException iox) {
        // close the socket before re-throwing the exception
        try {
            sslsock.close();
        } catch (final Exception x) {
            /*ignore*/ }
        throw iox;
    }
}

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

/**
 * Default public constructor./* www  .jav a2s .  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:iracing.webapi.IracingWebApi.java

private void installCerts() throws Exception {
    String host = "members.iracing.com";
    int port = 443;

    char[] password = CERT_STORE_PASSWORD.toCharArray();

    File file = new File("jssecacerts");
    if (!file.isFile()) {
        char seperator = File.separatorChar;
        File dir = new File(System.getProperty("java.home") + seperator + "lib" + seperator + "security");
        file = new File(dir, "jssecacerts");
        if (!file.isFile()) {
            file = new File(dir, "cacerts");
        }/*  w w w .  j  a v  a  2 s  . c o m*/
    }
    KeyStore ks;
    InputStream in = new FileInputStream(file);
    ks = KeyStore.getInstance(KeyStore.getDefaultType());
    try {
        ks.load(in, password);
    } catch (Exception e) {
    }
    in.close();

    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    tmf.init(ks);
    X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0];
    SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    SSLSocket socket = null;
    try {
        socket = (SSLSocket) factory.createSocket(host, port);
        socket.setSoTimeout(10000);
        socket.startHandshake();
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (socket != null)
            socket.close();
    }

    X509Certificate[] chain = tm.chain;
    if (chain == null)
        return;

    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    MessageDigest md5 = MessageDigest.getInstance("MD5");
    for (int i = 0; i < chain.length; i++) {
        X509Certificate cert = chain[i];
        sha1.update(cert.getEncoded());
        md5.update(cert.getEncoded());
    }

    for (int count = 0; count < chain.length; count++) {
        X509Certificate cert = chain[count];
        String alias = host + "-" + (count + 1);
        ks.setCertificateEntry(alias, cert);
        OutputStream out = new FileOutputStream("jssecacerts");
        try {
            ks.store(out, password);
        } finally {
            out.close();
        }
    }
}