Example usage for javax.net.ssl SSLSocket getOutputStream

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

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:org.apache.hadoop.gateway.jetty.SslSocketTest.java

@Ignore
@Test/*from w ww  .j  a  v  a2s. c o m*/
public void testSsl() throws IOException, InterruptedException {
    SslServer server = new SslServer();
    Thread thread = new Thread(server);
    thread.start();
    server.waitUntilReady();

    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "utf-8");
    params.setBooleanParameter("http.protocol.expect-continue", false);

    SSLSocketFactory sslsocketfactory = SSLSocketFactory.getSocketFactory();
    SSLSocket sslsocket = (SSLSocket) sslsocketfactory.createSocket(params);

    sslsocket.connect(new InetSocketAddress("localhost", 9999));

    OutputStream outputstream = sslsocket.getOutputStream();
    OutputStreamWriter outputstreamwriter = new OutputStreamWriter(outputstream);
    BufferedWriter bufferedwriter = new BufferedWriter(outputstreamwriter);

    bufferedwriter.write("HELLO\n");
    bufferedwriter.flush();
}

From source file:org.kuali.mobility.push.service.send.iOSSendService.java

/**
 * Sends the specified <code>Push</code> message to the specified <code>Device</code>.
 * This implementation makes use of a connection pool. If there is currently no connection 
 * available the current thread will block until a connection becomes available (unless 
 * otherwise configured)/*from   w  w  w.ja  va 2 s  .co m*/
 */
@Override
public void sendPush(Push push, Device device) {

    byte[] payload = preparePayload(push);
    byte[] deviceToken = createDeviceToken(device);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        baos.write(1); // Command Byte: New format = 1
        baos.write(deviceToken[FIRST_BYTE]); // Identifier Byte 1
        baos.write(deviceToken[SECOND_BYTE]); // Identifier Byte 2
        baos.write(deviceToken[THIRD_BYTE]); // Identifier Byte 3
        baos.write(deviceToken[FORTH_BYTE]); // Identifier Byte 4
        baos.write(0); // Expiry Byte 1
        baos.write(0); // Expiry Byte 2
        baos.write(0); // Expiry Byte 3
        baos.write(1); // Expiry Byte 4
        baos.write(0); // Device ID Length
        baos.write(DEVICE_ID_LENGTH);
        baos.write(deviceToken); // Device ID
        baos.write(0); // Payload Length
        baos.write(payload.length);
        baos.write(payload); // Payload
    } catch (IOException e) {
        LOG.error("Failed Creating Payload", e);
        return;
    }

    int retryAttempt = 1; // Number of tries to send the notification, quits when zero or lower
    boolean success = false;
    OutputStream out = null;//CodeReview could use chained streams here
    while (!success && retryAttempt <= MAX_RETRY_ATTEMPTS) {
        SSLSocket socket = null;
        try {
            socket = iOSConnectionPool.borrowObject();
            out = socket.getOutputStream();
            out.write(baos.toByteArray());
            if (LOG.isDebugEnabled()) {
                LOG.debug(baos.toString());
            }
            out.flush(); // We do not close the output stream as it is reused
            success = true;
        } catch (Exception e) {
            LOG.error("Exception while trying to write message over socket (Retry attempt : " + retryAttempt
                    + ")", e);
            IOUtils.closeQuietly(out); // Close potentially broken stream
            retryAttempt++;
        } finally {
            try {
                iOSConnectionPool.returnObject(socket);
            } catch (Exception e) {
                LOG.warn("Exception while trying to put Socket back into pool", e);
            }
        }
    }
}

From source file:com.zimbra.cs.mailclient.MailConnection.java

protected void startTls() throws IOException {
    checkState(State.NOT_AUTHENTICATED);
    sendStartTls();/*from   www. ja v a  2 s .  c  o m*/
    SSLSocket sock = newSSLSocket(socket);
    sock.startHandshake();
    initStreams(sock.getInputStream(), sock.getOutputStream());
}

From source file:spade.resolver.Recursive.java

/**
 * Computes a result, or throws an exception if unable to do so.
 *
 * @return computed result//from   w ww . java2s . c o  m
 * @throws Exception if unable to compute a result
 */
@Override
public Graph call() throws Exception {
    Graph resultGraph = null;
    try {
        // Establish a connection to the remote host
        String host = networkVertex.getAnnotation(OPMConstants.ARTIFACT_REMOTE_ADDRESS);
        int port = Integer.parseInt(Settings.getProperty("commandline_query_port"));
        logger.log(Level.INFO, "network Vertex: " + networkVertex);
        SSLSocket remoteSocket = (SSLSocket) Kernel.sslSocketFactory.createSocket();
        int connectTimeOut = 5000; // 5 sec
        remoteSocket.connect(new InetSocketAddress(host, port), connectTimeOut);
        //            SSLSocket remoteSocket = (SSLSocket) Kernel.sslSocketFactory.createSocket(host, port);

        OutputStream outStream = remoteSocket.getOutputStream();
        InputStream inStream = remoteSocket.getInputStream();
        ObjectInputStream graphInputStream = new ObjectInputStream(inStream);
        PrintWriter remoteSocketOut = new PrintWriter(outStream, true);

        String networkVertexQuery = "GetVertex(" + OPMConstants.ARTIFACT_LOCAL_ADDRESS
                + AbstractQuery.OPERATORS.EQUALS
                + networkVertex.getAnnotation(OPMConstants.ARTIFACT_REMOTE_ADDRESS) + " AND "
                + OPMConstants.ARTIFACT_LOCAL_PORT + AbstractQuery.OPERATORS.EQUALS
                + networkVertex.getAnnotation(OPMConstants.ARTIFACT_REMOTE_PORT) + " AND "
                + OPMConstants.ARTIFACT_REMOTE_ADDRESS + AbstractQuery.OPERATORS.EQUALS
                + networkVertex.getAnnotation(OPMConstants.ARTIFACT_LOCAL_ADDRESS) + " AND "
                + OPMConstants.ARTIFACT_REMOTE_PORT + AbstractQuery.OPERATORS.EQUALS
                + networkVertex.getAnnotation(OPMConstants.ARTIFACT_LOCAL_PORT) + " AND " + OPMConstants.SOURCE
                + AbstractQuery.OPERATORS.EQUALS + OPMConstants.SOURCE_AUDIT_NETFILTER + ")";

        remoteSocketOut.println(networkVertexQuery);
        logger.log(Level.INFO, "remote vertex query: " + networkVertexQuery);
        String returnType = (String) graphInputStream.readObject();
        // Check whether the remote query server returned a vertex set in response
        Set<AbstractVertex> vertexSet;
        if (returnType.equals(Set.class.getName())) {
            vertexSet = (Set<AbstractVertex>) graphInputStream.readObject();
        } else {
            logger.log(Level.INFO, "Return type not Set!");
            return null;
        }
        AbstractVertex targetNetworkVertex;
        if (!CollectionUtils.isEmpty(vertexSet)) {
            targetNetworkVertex = vertexSet.iterator().next();
        } else {
            logger.log(Level.INFO, "TargetNetworkVertex empty!");
            return null;
        }
        String targetNetworkVertexHash = targetNetworkVertex.bigHashCode();

        String lineageQuery = "GetLineage(" + PRIMARY_KEY + AbstractQuery.OPERATORS.EQUALS
                + targetNetworkVertexHash + ", " + depth + ", " + direction + ")";
        remoteSocketOut.println(lineageQuery);
        logger.log(Level.INFO, "remote lineage query: " + lineageQuery);

        returnType = (String) graphInputStream.readObject();
        if (returnType.equals(Graph.class.getName())) {
            AbstractEdge localToRemoteEdge = new Edge(networkVertex, targetNetworkVertex);
            localToRemoteEdge.addAnnotation("type", "WasDerivedFrom");
            AbstractEdge remoteToLocalEdge = new Edge(targetNetworkVertex, networkVertex);
            remoteToLocalEdge.addAnnotation("type", "WasDerivedFrom");
            resultGraph = (Graph) graphInputStream.readObject();
            resultGraph.putVertex(networkVertex);
            resultGraph.putEdge(localToRemoteEdge);
            resultGraph.putEdge(remoteToLocalEdge);
        } else {
            logger.log(Level.INFO, "Return type not Graph!");
        }

        remoteSocketOut.println("exit");
        remoteSocketOut.close();
        graphInputStream.close();
        inStream.close();
        outStream.close();
        remoteSocket.close();
    } catch (NumberFormatException | IOException | ClassNotFoundException exception) {
        logger.log(Level.SEVERE, "Remote resolution unsuccessful!", exception);
        return null;
    }

    logger.log(Level.INFO, "Remote resolution successful!");
    return resultGraph;
}

From source file:com.isecpartners.gizmo.HttpRequest.java

public void sendDataToClient() throws IOException {
    if (sock instanceof SSLSocket) {
        SSLSocket sslSock = (SSLSocket) sock;
        if (sslSock == null || resp == null) {
            return;
        }//w ww . j a  v  a 2  s. c o  m
        sslSock.getOutputStream().write(resp.byteContents());
    } else {
        this.sock.getOutputStream().write(resp.byteContents());
        this.sock.getOutputStream().flush();
    }
    if (version.equals("1.0") && !cached) {
        this.sock.close();
    }
    this.sent = true;
}

From source file:ch.cyberduck.core.ftp.FTPClient.java

@Override
protected void sslNegotiation() throws IOException {
    if (protocol.isSecure()) {
        final SSLSocket socket = (SSLSocket) sslSocketFactory.createSocket(_socket_,
                _socket_.getInetAddress().getHostAddress(), _socket_.getPort(), false);
        socket.setEnableSessionCreation(true);
        socket.setUseClientMode(true);//  ww w . ja  v a  2s . c  om
        socket.startHandshake();
        _socket_ = socket;
        _controlInput_ = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), getControlEncoding()));
        _controlOutput_ = new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream(), getControlEncoding()));
    }
}

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;//from   w w w .ja  va2 s. c om

    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:org.kuali.mobility.push.dao.PushDaoImpl.java

@SuppressWarnings("unchecked")
private boolean sendPushToIOS(Push push, Device device, SSLSocket socket) {
    String payload = preparePayload(push);
    LOG.info("Push: " + push);
    LOG.info("Device: " + device);
    String token = device.getRegId();

    try {/*from  ww  w  .  jav a 2  s  .  com*/
        char[] t = token.toCharArray();
        byte[] b = Hex.decodeHex(t);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // Command Byte. 
        baos.write(0);
        // Device ID Length
        baos.write(0);
        baos.write(32);
        // Device ID
        baos.write(b);
        // Payload Length
        baos.write(0);
        baos.write(payload.length());
        // Payload
        baos.write(payload.getBytes());
        LOG.info("Payload: Final size: " + baos.size());

        if (socket != null) {
            OutputStream out = socket.getOutputStream();
            InputStream in = socket.getInputStream();
            out.write(baos.toByteArray());
            out.flush();
        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
    return true;
}

From source file:com.isecpartners.gizmo.HttpRequest.java

public boolean fetchResponse(boolean cached) {
    this.cached = cached;

    OutputStream out = null;/*from   w  w  w  . j av  a2 s .c o  m*/
    BufferedReader strBr = null;

    try {
        if (cached) {
            strBr = new BufferedReader(new StringReader(this.interrimContents.toString()));
        }

        removeLine("PROXY-CONNECTION", workingContents);
        updateContentLength();

        if (mk_header(workingContents).contains("CONNECT") && !this.connect_protocol_handled) {
            handle_connect_protocol();
            if (!GizmoView.getView().config().terminateSSL()) {
                this.passthroughssl = true;
                return false;
            }
        }

        if (isSSL || this.sock instanceof SSLSocket) {
            SSLSocket sslSock = (SSLSocket) this.sock;
            SSLSocket sslOut = null;
            if (workingContents == null) {
                return false;
            }

            if (workingContents.indexOf("\r\n") == -1) {
                return false;
            }

            if (!this.override_host)
                host = rewriteMethodLine(workingContents);

            if (!user_defined_port) {
                port = 443;
            }

            if (outboundSock == null || (!(outboundSock instanceof SSLSocket))) {

                SSLSocketFactory sslsocketfactory = sloppySSL();
                sslOut = (SSLSocket) sslsocketfactory.createSocket(host, port);
            } else {
                sslOut = (SSLSocket) outboundSock;
            }

            sslOut.getOutputStream().write(workingContents.toString().getBytes());
            this.resp = HttpResponse.create(sslOut.getInputStream());
            if (resp == null) {
                return false;
            }

        } else {
            //if (!this.override_host)
            host = rewriteMethodLine(workingContents);

            outboundSock = new Socket(host, port);

            outboundSock.getOutputStream().write(workingContents.toString().getBytes());
            this.resp = HttpResponse.create(outboundSock.getInputStream());

            if (resp == null) {
                return false;
            }
        }

        this.addContents(workingContents.toString());

        this.header = workingContents.substring(0, this.workingContents.indexOf("\r\n"));
        this.url = getUrlPath(header);

        this.version = getVersion(this.header);

    } catch (SocketException e) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, e);
        return false;
    } catch (javax.net.ssl.SSLHandshakeException e) {
        try {
            GizmoView.getView().setStatus("couldn't connect with ssl.. cert issues?");
            sock.close();
        } catch (IOException ex) {
            Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
        return false;
    } catch (IOException ex) {
        Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
        return false;
    } catch (FailedRequestException e) {
        GizmoView.getView().setStatus("malformed server response");
    } catch (Exception e) {
        try {
            Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, e);
            GizmoView.getView().setStatus("couldn't connect");
            this.sock.close();
            return false;
        } catch (IOException ex) {
            Logger.getLogger(HttpRequest.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    this.wakeupAndSend();

    resp.setRequest(this);
    return true;
}

From source file:org.hyperic.hq.bizapp.agent.client.SecureAgentConnection.java

@Override
protected Socket getSocket() throws IOException {
    SSLSocket socket;

    log.debug("Creating secure socket");

    try {/*from w w w.j  a  va2s  .co  m*/
        // Check for configured agent read timeout from System properties
        int readTimeout;

        try {
            readTimeout = Integer.parseInt(System.getProperty(PROP_READ_TIMEOUT));
        } catch (NumberFormatException e) {
            readTimeout = READ_TIMEOUT;
        }

        // Check for configured agent post handshake timeout
        // from System properties
        int postHandshakeTimeout;
        try {
            postHandshakeTimeout = Integer.parseInt(System.getProperty(PROP_POST_HANDSHAKE_TIMEOUT));
        } catch (NumberFormatException e) {
            postHandshakeTimeout = POST_HANDSHAKE_TIMEOUT;
        }

        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, acceptUnverifiedCertificate);

        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();

        // See the following links...
        // http://www.apache.org/dist/httpcomponents/httpcore/RELEASE_NOTES-4.1.x.txt
        // http://www-128.ibm.com/developerworks/forums/dw_thread.jsp?message=13695343&cat=10&thread=73546&treeDisplayType=threadmode1&forum=178#13695343
        // In any case, it would seem as though the bug has since been fixed in IBM's JRE, no need to work around it anymore...
        socket = (SSLSocket) factory.createSocket();

        // Make sure the InetAddress used to initialize the socket has a non-null hostname (empty string).
        // This prevents slow and unnecessary reverse DNS querying when the connection is opened.
        InetAddress withoutHost = InetAddress.getByName(this.agentAddress);
        InetAddress withHost = InetAddress.getByAddress("", withoutHost.getAddress());
        InetSocketAddress address = new InetSocketAddress(withHost, this.agentPort);

        socket.connect(address, readTimeout);

        // Set the socket timeout during the initial handshake to detect
        // connection issues with the agent.  
        socket.setSoTimeout(readTimeout);

        log.debug("Secure socket is connected to " + address + " - starting handshake.");

        socket.startHandshake();

        log.debug("SSL handshake complete");

        // [HHQ-3694] The timeout is set to a post handshake value.
        socket.setSoTimeout(postHandshakeTimeout);

    } catch (IOException exc) {
        IOException toThrow = new IOException(
                "Unable to connect to " + this.agentAddress + ":" + this.agentPort + ": " + exc.getMessage());
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    // Write our security settings
    try {
        DataOutputStream dOs;

        dOs = new DataOutputStream(socket.getOutputStream());
        dOs.writeUTF(this.authToken);
    } catch (IOException exc) {
        IOException toThrow = new IOException("Unable to write auth params to server");
        // call initCause instead of constructor to be java 1.5 compat
        toThrow.initCause(exc);
        throw toThrow;
    }

    return socket;
}