Example usage for javax.net.ssl SSLSocket getInputStream

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

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

From source file:org.globus.gsi.jsse.SSLConfiguratorTest.java

private SSLServerSocket startServer(SSLConfigurator config)
        throws GlobusSSLConfigurationException, IOException {
    SSLServerSocketFactory sslserversocketfactory = config.createServerFactory();
    final SSLServerSocket sslserversocket = (SSLServerSocket) sslserversocketfactory.createServerSocket(9991);

    ExecutorService executor = Executors.newFixedThreadPool(1);
    executor.execute(new Runnable() {
        /**/*  w w  w .j a v  a2s .c  o  m*/
         * When an object implementing interface <code>Runnable</code> is
         * used to create a thread, starting the thread causes the object's
         * <code>run</code> method to be called in that separately executing
         * thread.
         * <p/>
         * The general contract of the method <code>run</code> is that it
         * may take any action whatsoever.
         *
         * @see Thread#run()
         */
        public void run() {
            latch.countDown();
            try {
                SSLSocket sslsocket = (SSLSocket) sslserversocket.accept();
                InputStream inputstream = sslsocket.getInputStream();
                InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
                BufferedReader bufferedreader = new BufferedReader(inputstreamreader);
                String line;
                while ((line = bufferedreader.readLine()) != null) {
                    builder.append(line);
                }
                assertEquals(builder.toString().trim(), "hello");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    return sslserversocket;
}

From source file:org.apache.tomcat.util.net.jsse.JSSE14Support.java

/**
 * JSSE in JDK 1.4 has an issue/feature that requires us to do a
 * read() to get the client-cert.  As suggested by Andreas
 * Sterbenz/*from  w  w  w.  j a  v  a 2s.c  o m*/
 */
private void synchronousHandshake(SSLSocket socket) throws IOException {
    InputStream in = socket.getInputStream();
    int oldTimeout = socket.getSoTimeout();
    socket.setSoTimeout(1000);
    byte[] b = new byte[0];
    listener.reset();
    socket.startHandshake();
    int maxTries = 60; // 60 * 1000 = example 1 minute time out
    for (int i = 0; i < maxTries; i++) {
        if (logger.isTraceEnabled())
            logger.trace("Reading for try #" + i);
        try {
            int x = in.read(b);
        } catch (SSLException sslex) {
            logger.info("SSL Error getting client Certs", sslex);
            throw sslex;
        } catch (IOException e) {
            // ignore - presumably the timeout
        }
        if (listener.completed) {
            break;
        }
    }
    socket.setSoTimeout(oldTimeout);
    if (listener.completed == false) {
        throw new SocketException("SSL Cert handshake timeout");
    }
}

From source file:LoginClient.java

public LoginClient() {
    try {//from w  w  w.ja va  2s. co  m
        SSLSocketFactory socketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket socket = (SSLSocket) socketFactory.createSocket("localhost", 7070);
        PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
        String userName = "MyName";
        output.println(userName);
        String password = "MyPass";
        output.println(password);
        output.flush();
        BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String response = input.readLine();
        System.out.println(response);

        output.close();
        input.close();
        socket.close();
    } catch (IOException ioException) {
        ioException.printStackTrace();
    } finally {
        System.exit(0);
    }
}

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

protected void startTls() throws IOException {
    checkState(State.NOT_AUTHENTICATED);
    sendStartTls();/*from   w  ww .  j ava2s.  c om*/
    SSLSocket sock = newSSLSocket(socket);
    sock.startHandshake();
    initStreams(sock.getInputStream(), sock.getOutputStream());
}

From source file:org.binding.openhab.samsungac.communicator.AirConditioner.java

String readLine(SSLSocket socket) throws Exception {
    if (!isConnected()) {
        login();/*from www.j  a va2 s.  c  o  m*/
    }
    BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    try {
        return r.readLine();
    } catch (SocketTimeoutException e) {
        logger.debug("Got socket timeout exception ... ", e);
    } catch (SSLException e) {
        logger.debug("Got SSL Exception. Disconnecting...");
        disconnect();
    }
    return null;
}

From source file:test.integ.be.fedict.commons.eid.client.SSLTest.java

@Test
public void testMutualSSL() throws Exception {

    Security.addProvider(new BeIDProvider());

    final KeyPair serverKeyPair = generateKeyPair();
    final PrivateKey serverPrivateKey = serverKeyPair.getPrivate();
    final DateTime notBefore = new DateTime();
    final DateTime notAfter = notBefore.plusDays(1);
    final X509Certificate serverCertificate = generateCACertificate(serverKeyPair, "CN=Test", notBefore,
            notAfter);/* w ww .  j av a  2 s . c o m*/

    final KeyManager keyManager = new ServerTestX509KeyManager(serverPrivateKey, serverCertificate);
    final TrustManager trustManager = new ServerTestX509TrustManager();
    final SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(new KeyManager[] { keyManager }, new TrustManager[] { trustManager }, new SecureRandom());

    final SSLServerSocketFactory sslServerSocketFactory = sslContext.getServerSocketFactory();

    final int serverPort = 8443;
    final SSLServerSocket sslServerSocket = (SSLServerSocket) sslServerSocketFactory
            .createServerSocket(serverPort);

    sslServerSocket.setNeedClientAuth(true);

    final TestRunnable testRunnable = new TestRunnable(serverPort);
    final Thread thread = new Thread(testRunnable);
    thread.start();

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    LOG.debug("server accepted");
    InputStream inputStream = sslSocket.getInputStream();
    int result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(12, result);
    SSLSession sslSession = sslSocket.getSession();
    sslSession.invalidate();
    sslSocket = (SSLSocket) sslServerSocket.accept();
    inputStream = sslSocket.getInputStream();
    result = inputStream.read();
    LOG.debug("result: " + result);
    assertEquals(34, result);
}

From source file:org.openhab.binding.samsungac.internal.AirConditioner.java

String readLine(SSLSocket socket) throws Exception {
    if (!isConnected()) {
        login();//from w w w . j av a2 s. c  om
    }
    BufferedReader r = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    try {
        return r.readLine();
    } catch (SocketTimeoutException e) {
        logger.debug("Nothing more to read from AC");
    } catch (SSLException e) {
        logger.debug("Got SSL Exception. Disconnecting.");
        disconnect();
    }
    return null;
}

From source file:spade.resolver.Recursive.java

/**
 * Computes a result, or throws an exception if unable to do so.
 *
 * @return computed result/*from  w  w  w. ja  v  a 2s.  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:org.apache.http.HC4.conn.ssl.AbstractVerifier.java

@Override
public final void verify(final String host, final SSLSocket ssl) throws IOException {
    Args.notNull(host, "Host");
    SSLSession session = ssl.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 = ssl.getInputStream();
        in.available();/*from   w w w. j av a2 s  . c  o  m*/
        /*
          If you're looking at the 2 lines of code above because
          you're running into a problem, you probably have two
          options:
                
        #1.  Clean up the certificate chain that your server
             is presenting (e.g. edit "/etc/apache2/server.crt"
             or wherever it is your server's certificate chain
             is defined).
                
                                   OR
                
        #2.   Upgrade to an IBM 1.5.x or greater JVM, or switch
              to a non-IBM JVM.
        */

        // If ssl.getInputStream().available() didn't cause an
        // exception, maybe at least now the session is available?
        session = ssl.getSession();
        if (session == null) {
            // If it's still null, probably a startHandshake() will
            // unearth the real problem.
            ssl.startHandshake();

            // Okay, if we still haven't managed to cause an exception,
            // might as well go for the NPE.  Or maybe we're okay now?
            session = ssl.getSession();
        }
    }

    final Certificate[] certs = session.getPeerCertificates();
    final X509Certificate x509 = (X509Certificate) certs[0];
    verify(host, x509);
}

From source file:org.kuali.mobility.push.dao.DeviceFeedbackMonitor.java

/**
 * This is a private method that checks Apple's feedback service for devices that need to be removed. 
 * //from   w  w w .j  av  a 2  s. c  o m
 */
private void checkiOSDeviceFeedback() {
    LOG.info("Checking iOS Device Feedback");
    final int cFEEDBACKTUPLESIZE = 38;
    final int cBLOCKSIZE = 1024;
    final int cBYTEMASK = 0x000000FF;

    //      SSLSocket feedbackSocket = openAppleSocket(feedbackHost, feedbackPort);
    SSLSocket feedbackSocket = null;
    try {
        feedbackSocket = iOSFeedbackConnectionPool.borrowObject();
    } catch (Exception e) {
        LOG.info("Was unable to borrow SSQLSocket from Pool");
    }

    if (null == feedbackSocket) {
        LOG.info("APNS Feedback Socket is NOT connected.");
    } else {
        LOG.info("APNS Feedback Socket is connected. Checking Feedback.");
        try {
            InputStream in = feedbackSocket.getInputStream();

            // Read bytes        
            byte[] b = new byte[cBLOCKSIZE];
            ByteArrayOutputStream message = new ByteArrayOutputStream();
            int nbBytes = 0;
            // socketStream.available can return 0
            // http://forums.sun.com/thread.jspa?threadID=5428561
            while ((nbBytes = in.read(b, 0, cBLOCKSIZE)) != -1) {
                message.write(b, 0, nbBytes);
            }

            byte[] listOfDevices = message.toByteArray();
            int nbDevices = listOfDevices.length / cFEEDBACKTUPLESIZE;
            LOG.info(nbDevices + " devices had feedback.");

            for (int j = 0; j < nbDevices; j++) {
                int offset = j * cFEEDBACKTUPLESIZE;

                // Build date
                int index = 0;
                int firstByte = 0;
                int secondByte = 0;
                int thirdByte = 0;
                int fourthByte = 0;
                long anUnsignedInt = 0;

                firstByte = (cBYTEMASK & ((int) listOfDevices[offset]));
                secondByte = (cBYTEMASK & ((int) listOfDevices[offset + 1]));
                thirdByte = (cBYTEMASK);
                fourthByte = (cBYTEMASK & ((int) listOfDevices[offset + 3]));
                index = index + 4;
                anUnsignedInt = ((long) (firstByte << 24 | secondByte << 16 | thirdByte << 8 | fourthByte))
                        & 0xFFFFFFFFL;
                Timestamp timestamp = new Timestamp(anUnsignedInt * 1000);

                // Build device token length
                int deviceTokenLength = listOfDevices[offset + 4] << 8 | listOfDevices[offset + 5];

                // Build device token
                String deviceToken = "";
                int octet = 0;
                for (int k = 0; k < 32; k++) {
                    octet = (cBYTEMASK & ((int) listOfDevices[offset + 6 + k]));
                    deviceToken = deviceToken.concat(String.format("%02x", octet));
                }

                LOG.info(timestamp);
                LOG.info(deviceToken);
                Device dtoDelete = deviceService.findDeviceByRegId(deviceToken);
                if (deviceService.removeDevice(dtoDelete)) {
                    LOG.info("Deleted " + dtoDelete.getDeviceName());
                }
            }

        } catch (Exception e) {

        } finally {
            try {
                feedbackSocket.close();
            } catch (Exception e) {

            }
        }
    }
}