Example usage for javax.net.ssl SSLException getCause

List of usage examples for javax.net.ssl SSLException getCause

Introduction

In this page you can find the example usage for javax.net.ssl SSLException getCause.

Prototype

public synchronized Throwable getCause() 

Source Link

Document

Returns the cause of this throwable or null if the cause is nonexistent or unknown.

Usage

From source file:net.jmhertlein.mcanalytics.console.gui.LoginPane.java

@FXML
public void onLoginButtonPressed(ActionEvent event) {
    HostEntry selected = hostList.getSelectionModel().getSelectedItem();
    if (selected == null)
        return;/*  w  w  w .  j  a  v  a2  s  . c o m*/

    try {
        SSLContext ctx = SSLUtil.buildClientContext(trust);
        SSLSocket raw = (SSLSocket) ctx.getSocketFactory().createSocket(selected.getUrl(), selected.getPort());
        raw.setWantClientAuth(true);
        try {
            System.out.println("Starting handshake...");
            raw.startHandshake();
        } catch (SSLException ssle) {
            if (ssle.getCause() instanceof UntrustedCertificateException) {
                System.out.println("Got the correct exception");
                UntrustedCertificateException uce = (UntrustedCertificateException) ssle.getCause();
                CertTrustPromptDialog dlg = new CertTrustPromptDialog(trust,
                        (X509Certificate) uce.getChain()[0]);
                dlg.showAndWait();
                System.out.println("DIALOG RETURNED");
            }
            return;
        }

        PrintWriter out = new PrintWriter(raw.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(raw.getInputStream()));
        APISocket sock = new APISocket(out, in);
        app.setAPISocket(sock);
        sock.startListener();

        //handle authentication
        boolean hasCert = false;
        FutureRequest<AuthenticationResult> login;
        if (trust.isCertificateEntry(selected.getUrl())) {
            try {
                ((X509Certificate) trust.getCertificate(selected.getUrl())).checkValidity();
                hasCert = true;
            } catch (CertificateExpiredException | CertificateNotYetValidException ex) {
                Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        System.out.println("Has cert: " + hasCert);
        KeyPair newPair = null;
        String username;

        if (hasCert) {
            username = SSLUtil.getCNs((X509Certificate) trust.getCertificate(selected.getUrl())).iterator()
                    .next();
            login = sock.submit(new AuthenticationRequest(username));
            System.out.println("Logging in w/ cert. CN: " + username + ", URL: " + selected.getUrl());
        } else if (rememberLoginBox.isSelected()) {
            newPair = SSLUtil.newECDSAKeyPair();
            username = usernameField.getText();
            PKCS10CertificationRequest csr = SSLUtil.newCertificateRequest(
                    SSLUtil.newX500Name(username, selected.getUrl(), "mcanalytics"), newPair);
            login = sock
                    .submit(new AuthenticationRequest(usernameField.getText(), passwordField.getText(), csr));
            System.out.println("Logging in with: " + usernameField.getText() + " + " + passwordField.getText()
                    + " and requesting a cert.");
        } else {
            username = usernameField.getText();
            login = sock.submit(new AuthenticationRequest(username, passwordField.getText()));
            System.out.println("Logging in with: " + username + " + " + passwordField.getText());
        }

        try {
            boolean success = login.get().getSuccess();
            if (success) {
                System.out.println("Login successful");
                if (login.get().hasCertificate()) {
                    trust.setCertificateEntry(selected.getUrl(), login.get().getCert());
                    trust.setKeyEntry(selected.getUrl() + "-private", newPair.getPrivate(), new char[0],
                            new Certificate[] { login.get().getCert(), login.get().getCA() });
                    System.out.println("Stored a trusted cert from server.");
                }
            } else {
                System.out.println("Login failed.");
                Dialog dlg = new Dialog();
                dlg.setTitle("Login Failed");
                dlg.setContentText("Could not login- invalid login credentials.");
                dlg.showAndWait();
                return;
            }
        } catch (InterruptedException | ExecutionException | KeyStoreException ex) {
            Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
            Dialogs.showMessage("Connection Error", "Connection Error", ex.getMessage(), ex.toString());
            System.out.println("Login error.");
            return;
        }
        //auth done

        Stage window = (Stage) loginButton.getScene().getWindow();
        window.setScene(new Scene(new ChartPane(username, sock)));
        window.show();
    } catch (IOException | KeyStoreException ex) {
        Logger.getLogger(LoginPane.class.getName()).log(Level.SEVERE, null, ex);
        Dialog dlg = new Dialog();
        dlg.setTitle("Connection Error");
        dlg.setContentText(ex.getMessage());
        dlg.showAndWait();
        System.out.println("Login error.");
        return;
    }
}

From source file:com.predic8.membrane.core.transport.http.HttpServerHandler.java

public void run() {
    Connection boundConnection = null; // see Request.isBindTargetConnectionToIncoming()
    try {/* w  ww .  j a  v a2s.  c o  m*/
        updateThreadName(true);
        setup();
        while (true) {
            srcReq = new Request();

            endpointListener.setIdleStatus(sourceSocket, true);
            try {
                srcIn.mark(2);
                if (srcIn.read() == -1)
                    break;
                srcIn.reset();
            } finally {
                endpointListener.setIdleStatus(sourceSocket, false);
            }

            if (boundConnection != null) {
                exchange.setTargetConnection(boundConnection);
                boundConnection = null;
            }

            srcReq.read(srcIn, true);

            exchange.received();

            if (srcReq.getHeader().getProxyConnection() != null) {
                srcReq.getHeader().add(Header.CONNECTION, srcReq.getHeader().getProxyConnection());
                srcReq.getHeader().removeFields(Header.PROXY_CONNECTION);
            }

            process();

            if (srcReq.isCONNECTRequest()) {
                log.debug("stopping HTTP Server Thread after establishing an HTTP connect");
                return;
            }
            boundConnection = exchange.getTargetConnection();
            exchange.setTargetConnection(null);
            if (!exchange.canKeepConnectionAlive())
                break;
            if (exchange.getResponse().isRedirect()) {
                break;
            }
            exchange.detach();
            exchange = new Exchange(this);
        }
    } catch (SocketTimeoutException e) {
        log.debug("Socket of thread " + counter + " timed out");
    } catch (SocketException se) {
        log.debug("client socket closed");
    } catch (SSLException s) {
        if (s.getCause() instanceof SSLException)
            s = (SSLException) s.getCause();
        if (s.getCause() instanceof SocketException)
            log.debug("ssl socket closed");
        else
            log.error("", s);
    } catch (IOException e) {
        log.error("", e);
    } catch (EndOfStreamException e) {
        log.debug("stream closed");
    } catch (AbortException e) {
        log.debug("exchange aborted.");
    } catch (NoMoreRequestsException e) {
        // happens at the end of a keep-alive connection
    } catch (NoResponseException e) {
        log.debug("No response received. Maybe increase the keep-alive timeout on the server.");
    } catch (EOFWhileReadingFirstLineException e) {
        log.debug("Client connection terminated before line was read. Line so far: (" + e.getLineSoFar() + ")");
    } catch (Exception e) {
        log.error("", e);
    }

    finally {
        endpointListener.setOpenStatus(sourceSocket, false);

        if (boundConnection != null)
            try {
                boundConnection.close();
            } catch (IOException e) {
                log.debug("Closing bound connection.", e);
            }

        closeConnections();

        exchange.detach();

        updateThreadName(false);
    }

}