Example usage for java.net Socket getOutputStream

List of usage examples for java.net Socket getOutputStream

Introduction

In this page you can find the example usage for java.net Socket getOutputStream.

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream for this socket.

Usage

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * @param message//from w  ww  .j a  v a  2s  .c  om
 *            the message as a string, that should send.
 * @return the result of the call
 * @throws UnknownHostException
 * @throws IOException
 */
private boolean sendMessage(String message) {

    StringBuilder result = new StringBuilder();

    try {
        Socket client = getSocket();

        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println(message);
        LOGGER.info("Send message to AUT:" + message);
        os.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8));

        int c;
        while ((c = in.read()) != -1) {
            result.append((char) c);
        }
        String myMessage = result.toString();
        if (myMessage.indexOf("ERROR ") > -1) {
            LOGGER.error("Fails: " + myMessage);
            throw new RuntimeException("Message: " + message + " fails with: " + myMessage);
        }

        client.close();

    } catch (UnknownHostException e) {
        LOGGER.error("SendMessage Host not Found", e);
    } catch (IOException e) {
        LOGGER.error("Send Message IOException ", e);
    }
    if (result.toString().startsWith("true")) {
        return true;
    }
    return false;
}

From source file:org.testeditor.fixture.swt.SwtBotFixture.java

/**
 * Returns true if the application is launched.
 * //from  w w  w.  j  a  va2  s.co m
 * @return true, if the server is ready.
 */
private boolean isLaunched() {
    try {
        Socket client = getSocket();
        LOGGER.info("Is server ready for " + testName + "?");
        PrintStream os = new PrintStream(client.getOutputStream(), false, CHARSET_UTF_8);
        os.println("isLaunched");
        os.flush();
        BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream(), CHARSET_UTF_8));
        String s = in.readLine();
        LOGGER.info(s);
        client.close();
        return Boolean.valueOf(s);
    } catch (UnknownHostException e) {
        LOGGER.error("isLaunched UnknownHostException: ", e);
    } catch (ConnectException e) {
        LOGGER.trace("Server not available.");
    } catch (IOException e) {
        LOGGER.error("isLaunched IOException: ", e);
    }
    return false;
}

From source file:com.jcraft.weirdx.WeirdX.java

public void weirdx_start(Container container) throws ConnectException {
    if (xdmcpmode != null) {
        LOG.debug("XDMC Mode = " + xdmcpmode);
        if (xdmcpmode.equals("query")) {
            xdmcp = new XDMCP(xdmcpaddr, myAddress, displayNumber);
        } else if (xdmcpmode.equals("broadcast")) {
            xdmcp = new XDMCP(XDMCP.BroadcastQuery, xdmcpaddr, myAddress, displayNumber);
        } else if (xdmcpmode.equals("indirect")) {
            xdmcp = new XDMCP(XDMCP.IndirectQuery, xdmcpaddr, myAddress, displayNumber);
        }/* w ww  .j  a  v a  2s  .c o m*/
    }

    if (sxrexec != null && sxrexec.equals("yes")) {
        xrexec = new XRexec(myAddress, displayNumber);
    }

    weirdx_init(container);

    InputStream in;
    OutputStream out;

    InputOutput client = null;

    if (xdmcp != null) {
        Client.addListener((ClientListener) xdmcp);
        xdmcp.start();
    }

    if (jdxpc != null) {
        (new SpawnJDxpc(this)).start();
    }
    if (ssshrexec != null) {
        if (ssshrexec.equals("yes")) {
            (new SpawnSSHRexec(this)).start();
        }
    }

    byte[] byte_order = new byte[1];
    try {
        Socket socket = null;
        while (true && weirdx != null) {
            try {
                socket = displaysocket.accept();
            } catch (Exception e) {
                LOG.error(e);
                if (e instanceof NullPointerException) {
                    weirdx = null;
                    break;
                }
                continue;
            }

            if (!Acl.check(socket.getInetAddress())) {
                LOG.error("ACL warning: unauthorized access from " + socket.getInetAddress());
                try {
                    socket.close();
                } catch (Exception e) {
                }
                ;
                continue;
            }

            try {
                socket.setTcpNoDelay(true);
            } catch (Exception eeee) {
                //System.out.println(eeee+" tcpnodelay");
            }

            client = null;

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

            try {
                in.read(byte_order, 0, 1);
            } catch (Exception e) {
                continue;
            }

            // 0x6c LSB
            // 0x42 MSB
            if (byte_order[0] == 0x6c) {
                client = new IOLSB();
            } else if (byte_order[0] == 0x42) {
                client = new IOMSB();
            } else {
                LOG.warn("protocol: error " + Integer.toHexString(byte_order[0]));
                continue;
            }

            client.setInputStream(in);
            client.setOutputStream(out);

            Client foo = new Client(client);
            if (foo.index != -1) {
                foo.start();
            } else {
                // System.err.println("running over clients table");
            }
        }
    } catch (IOException e) {
        LOG.error("IO Error: " + e.getLocalizedMessage());
    }
    // stop(); // ??
}

From source file:io.undertow.server.handlers.sse.ServerSentEventTestCase.java

@Test
public void testConnectionFail() throws IOException, InterruptedException {

    final Socket socket = new Socket(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"));
    final CountDownLatch latch = new CountDownLatch(1);
    final CountDownLatch connected = new CountDownLatch(1);
    DefaultServer.setRootHandler(new ServerSentEventHandler(new ServerSentEventConnectionCallback() {
        @Override/* w w w.j a  v  a  2 s  .c  o m*/
        public void connected(final ServerSentEventConnection connection, final String lastEventId) {
            final XnioIoThread thread = (XnioIoThread) Thread.currentThread();
            connected.countDown();
            thread.execute(new Runnable() {
                @Override
                public void run() {
                    connection.send("hello", new ServerSentEventConnection.EventCallback() {
                        @Override
                        public void done(ServerSentEventConnection connection, String data, String event,
                                String id) {
                        }

                        @Override
                        public void failed(ServerSentEventConnection connection, String data, String event,
                                String id, IOException e) {
                            latch.countDown();
                        }
                    });
                    if (latch.getCount() > 0) {
                        WorkerUtils.executeAfter(thread, this, 100, TimeUnit.MILLISECONDS);
                    }
                }
            });
        }
    }));
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    out.write(("GET / HTTP/1.1\r\nHost:" + DefaultServer.getHostAddress() + "\r\n\r\n").getBytes());
    out.flush();
    if (!connected.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
    out.close();
    in.close();
    if (!latch.await(10, TimeUnit.SECONDS)) {
        Assert.fail();
    }
}

From source file:NanoHTTPD.java

/**
 * Start the server.//from   www.  j a v a2 s .c  o  m
 *
 * @throws IOException if the socket is in use.
 */
public void start() throws IOException {
    myServerSocket = new ServerSocket();
    myServerSocket
            .bind((hostname != null) ? new InetSocketAddress(hostname, myPort) : new InetSocketAddress(myPort));

    myThread = new Thread(new Runnable() {
        @Override
        public void run() {
            do {
                try {
                    final Socket finalAccept = myServerSocket.accept();
                    registerConnection(finalAccept);
                    finalAccept.setSoTimeout(SOCKET_READ_TIMEOUT);
                    final InputStream inputStream = finalAccept.getInputStream();
                    asyncRunner.exec(new Runnable() {
                        @Override
                        public void run() {
                            OutputStream outputStream = null;
                            try {
                                outputStream = finalAccept.getOutputStream();
                                TempFileManager tempFileManager = tempFileManagerFactory.create();
                                HTTPSession session = new HTTPSession(tempFileManager, inputStream,
                                        outputStream, finalAccept.getInetAddress());
                                while (!finalAccept.isClosed()) {
                                    session.execute();
                                }
                            } catch (Exception e) {
                                // When the socket is closed by the client, we throw our own SocketException
                                // to break the  "keep alive" loop above.
                                if (!(e instanceof SocketException
                                        && "NanoHttpd Shutdown".equals(e.getMessage()))) {
                                    e.printStackTrace();
                                }
                            } finally {
                                safeClose(outputStream);
                                safeClose(inputStream);
                                safeClose(finalAccept);
                                unRegisterConnection(finalAccept);
                            }
                        }
                    });
                } catch (IOException e) {
                }
            } while (!myServerSocket.isClosed());
        }
    });
    myThread.setDaemon(true);
    myThread.setName("NanoHttpd Main Listener");
    myThread.start();
}

From source file:com.connectsdk.service.netcast.NetcastHttpServer.java

public void start() {
    //TODO: this method is too complex and should be refactored
    if (running)//from w  w w.j  a v  a  2s  . c o m
        return;

    running = true;

    try {
        welcomeSocket = new ServerSocket(this.port);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    while (running) {
        if (welcomeSocket == null || welcomeSocket.isClosed()) {
            stop();
            break;
        }

        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;

        try {
            connectionSocket = welcomeSocket.accept();
        } catch (IOException ex) {
            ex.printStackTrace();
            // this socket may have been closed, so we'll stop
            stop();
            return;
        }

        String str = null;
        int c;
        StringBuilder sb = new StringBuilder();

        try {
            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            while ((str = inFromClient.readLine()) != null) {
                if (str.equals("")) {
                    break;
                }
            }

            while ((c = inFromClient.read()) != -1) {
                sb.append((char) c);
                String temp = sb.toString();

                if (temp.endsWith("</envelope>"))
                    break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        String body = sb.toString();

        Log.d(Util.T, "got message body: " + body);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(calendar.getTime());
        String androidOSVersion = android.os.Build.VERSION.RELEASE;

        PrintWriter out = null;

        try {
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            out = new PrintWriter(outToClient);
            out.println("HTTP/1.1 200 OK");
            out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1");
            out.println("Cache-Control: no-store, no-cache, must-revalidate");
            out.println("Date: " + date);
            out.println("Connection: Close");
            out.println("Content-Length: 0");
            out.println();
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inFromClient.close();
                out.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream stream = null;

        try {
            stream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }

        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();

        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(stream, handler);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

        if (body.contains("ChannelChanged")) {
            ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject());

            Log.d(Util.T, "Channel Changed: " + channel.getNumber());

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, channel);
                    }
                }
            }
        } else if (body.contains("KeyboardVisible")) {
            boolean focused = false;

            TextInputStatusInfo keyboard = new TextInputStatusInfo();
            keyboard.setRawData(handler.getJSONObject());

            try {
                JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget");
                focused = (Boolean) currentWidget.get("focus");
                keyboard.setFocused(focused);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.d(Util.T, "KeyboardFocused?: " + focused);

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, keyboard);
                    }
                }
            }
        } else if (body.contains("TextEdited")) {
            System.out.println("TextEdited");

            String newValue = "";

            try {
                newValue = handler.getJSONObject().getString("value");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

            Util.postSuccess(textChangedListener, newValue);
        } else if (body.contains("3DMode")) {
            try {
                String enabled = (String) handler.getJSONObject().get("value");
                boolean bEnabled;

                bEnabled = enabled.equalsIgnoreCase("true");

                for (URLServiceSubscription<?> sub : subscriptions) {
                    if (sub.getTarget().equalsIgnoreCase("3DMode")) {
                        for (int i = 0; i < sub.getListeners().size(); i++) {
                            @SuppressWarnings("unchecked")
                            ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                    .get(i);
                            Util.postSuccess(listener, bEnabled);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.connectsdk.device.netcast.NetcastHttpServer.java

public void start() {
    if (running)//from w w w  .  j a v  a2 s  . c o m
        return;

    running = true;

    try {
        welcomeSocket = new ServerSocket(this.port);
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    while (running) {
        if (welcomeSocket == null || welcomeSocket.isClosed()) {
            stop();
            break;
        }

        Socket connectionSocket = null;
        BufferedReader inFromClient = null;
        DataOutputStream outToClient = null;

        try {
            connectionSocket = welcomeSocket.accept();
        } catch (IOException ex) {
            ex.printStackTrace();
            // this socket may have been closed, so we'll stop
            stop();
            return;
        }

        String str = null;
        int c;
        StringBuilder sb = new StringBuilder();

        try {
            inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));

            while ((str = inFromClient.readLine()) != null) {
                if (str.equals("")) {
                    break;
                }
            }

            while ((c = inFromClient.read()) != -1) {
                sb.append((char) c);
                String temp = sb.toString();

                if (temp.endsWith("</envelope>"))
                    break;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        String body = sb.toString();

        Log.d("Connect SDK", "got message body: " + body);

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = dateFormat.format(calendar.getTime());
        String androidOSVersion = android.os.Build.VERSION.RELEASE;

        PrintWriter out = null;

        try {
            outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            out = new PrintWriter(outToClient);
            out.println("HTTP/1.1 200 OK");
            out.println("Server: Android/" + androidOSVersion + " UDAP/2.0 ConnectSDK/1.2.1");
            out.println("Cache-Control: no-store, no-cache, must-revalidate");
            out.println("Date: " + date);
            out.println("Connection: Close");
            out.println("Content-Length: 0");
            out.flush();
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            try {
                inFromClient.close();
                out.close();
                outToClient.close();
                connectionSocket.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        InputStream stream = null;

        try {
            stream = new ByteArrayInputStream(body.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException ex) {
            ex.printStackTrace();
        }

        NetcastPOSTRequestParser handler = new NetcastPOSTRequestParser();

        SAXParser saxParser;
        try {
            saxParser = saxParserFactory.newSAXParser();
            saxParser.parse(stream, handler);
        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }

        if (body.contains("ChannelChanged")) {
            ChannelInfo channel = NetcastChannelParser.parseRawChannelData(handler.getJSONObject());

            Log.d("Connect SDK", "Channel Changed: " + channel.getNumber());

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("ChannelChanged")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, channel);
                    }
                }
            }
        } else if (body.contains("KeyboardVisible")) {
            boolean focused = false;

            TextInputStatusInfo keyboard = new TextInputStatusInfo();
            keyboard.setRawData(handler.getJSONObject());

            try {
                JSONObject currentWidget = (JSONObject) handler.getJSONObject().get("currentWidget");
                focused = (Boolean) currentWidget.get("focus");
                keyboard.setFocused(focused);
            } catch (JSONException e) {
                e.printStackTrace();
            }

            Log.d("Connect SDK", "KeyboardFocused?: " + focused);

            for (URLServiceSubscription<?> sub : subscriptions) {
                if (sub.getTarget().equalsIgnoreCase("KeyboardVisible")) {
                    for (int i = 0; i < sub.getListeners().size(); i++) {
                        @SuppressWarnings("unchecked")
                        ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                .get(i);
                        Util.postSuccess(listener, keyboard);
                    }
                }
            }
        } else if (body.contains("TextEdited")) {
            System.out.println("TextEdited");

            String newValue = "";

            try {
                newValue = handler.getJSONObject().getString("value");
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

            Util.postSuccess(textChangedListener, newValue);
        } else if (body.contains("3DMode")) {
            try {
                String enabled = (String) handler.getJSONObject().get("value");
                boolean bEnabled;

                if (enabled.equalsIgnoreCase("true"))
                    bEnabled = true;
                else
                    bEnabled = false;

                for (URLServiceSubscription<?> sub : subscriptions) {
                    if (sub.getTarget().equalsIgnoreCase("3DMode")) {
                        for (int i = 0; i < sub.getListeners().size(); i++) {
                            @SuppressWarnings("unchecked")
                            ResponseListener<Object> listener = (ResponseListener<Object>) sub.getListeners()
                                    .get(i);
                            Util.postSuccess(listener, bEnabled);
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.irccloud.android.GingerbreadImageProxy.java

private void processRequest(HttpRequest request, Socket client) throws IllegalStateException, IOException {
    if (request == null) {
        return;/* w w w .j  av a  2 s . co  m*/
    }
    URL url = new URL(request.getRequestLine().getUri());

    HttpURLConnection conn = null;

    Proxy proxy = null;
    String host = null;
    int port = -1;

    if (Build.VERSION.SDK_INT < 11) {
        Context ctx = IRCCloudApplication.getInstance().getApplicationContext();
        if (ctx != null) {
            host = android.net.Proxy.getHost(ctx);
            port = android.net.Proxy.getPort(ctx);
        }
    } else {
        host = System.getProperty("http.proxyHost", null);
        try {
            port = Integer.parseInt(System.getProperty("http.proxyPort", "8080"));
        } catch (NumberFormatException e) {
            port = -1;
        }
    }

    if (host != null && host.length() > 0 && !host.equalsIgnoreCase("localhost")
            && !host.equalsIgnoreCase("127.0.0.1") && port > 0) {
        InetSocketAddress proxyAddr = new InetSocketAddress(host, port);
        proxy = new Proxy(Proxy.Type.HTTP, proxyAddr);
    }

    if (url.getProtocol().toLowerCase().equals("https")) {
        conn = (HttpsURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    } else {
        conn = (HttpURLConnection) ((proxy != null) ? url.openConnection(proxy)
                : url.openConnection(Proxy.NO_PROXY));
    }

    conn.setConnectTimeout(30000);
    conn.setReadTimeout(30000);
    conn.setUseCaches(true);

    if (!isRunning)
        return;

    try {
        client.getOutputStream().write(
                ("HTTP/1.0 " + conn.getResponseCode() + " " + conn.getResponseMessage() + "\n\n").getBytes());

        if (conn.getResponseCode() == 200 && conn.getInputStream() != null) {
            byte[] buff = new byte[8192];
            int readBytes;
            while (isRunning && (readBytes = conn.getInputStream().read(buff, 0, buff.length)) != -1) {
                client.getOutputStream().write(buff, 0, readBytes);
            }
        }
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        client.close();
    }

    conn.disconnect();
    stop();
}

From source file:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

private void runSimultaneousDataExchange(boolean useTunnel, int nclients)
        throws IOException, InterruptedException, NoSuchAlgorithmException {
    long t0 = System.currentTimeMillis();
    final int nMsgs = 50;
    final Map<String, MessageDigest> digestMsgsRecvdAtServer = new HashMap<String, MessageDigest>();
    final Map<String, MessageDigest> digestMsgsSentByClients = new HashMap<String, MessageDigest>();
    final Map<String, MessageDigest> digestMsgsRecvdAtClients = new HashMap<String, MessageDigest>();
    for (int c = 0; c < nclients; c++) {
        digestMsgsRecvdAtServer.put(Integer.toString(c), MessageDigest.getInstance("MD5"));
        digestMsgsSentByClients.put(Integer.toString(c), MessageDigest.getInstance("MD5"));
        digestMsgsRecvdAtClients.put(Integer.toString(c), MessageDigest.getInstance("MD5"));
    }//w w w . j  a v  a2 s  .  co  m
    final MessageDigest digestMsgsSentByServer = MessageDigest.getInstance("MD5");
    for (int i = 0; i < nMsgs; i++) {
        digestMsgsSentByServer.update(TalkPastServer.generateMsgFromServer(i).getBytes());
    }
    String hashOfMsgsSentByServer = Hex.encodeHexString(digestMsgsSentByServer.digest());

    MockServer talkPastServer = startTalkPastServer(nMsgs, digestMsgsRecvdAtServer);

    int targetPort = talkPastServer.getServerSocketPort();
    Tunnel tunnel = null;
    MockServer proxyServer = null;
    if (useTunnel) {
        proxyServer = startConnectProxyServer();
        tunnel = Tunnel.build("localhost", talkPastServer.getServerSocketPort(), "localhost",
                proxyServer.getServerSocketPort());
        targetPort = tunnel.getPort();
    }

    try {
        List<EasyThread> clientThreads = new ArrayList<EasyThread>();
        final int portToUse = targetPort;
        for (int c = 0; c < nclients; c++) {
            final int clientId = c;
            clientThreads.add(new EasyThread() {
                @Override
                void runQuietly() throws Exception {
                    long t = System.currentTimeMillis();
                    LOG.info("\t" + clientId + ": Client starting");
                    final MessageDigest digestMsgsRecvdAtClient = digestMsgsRecvdAtClients
                            .get(Integer.toString(clientId));
                    //final SocketChannel client = SocketChannel.open(); // tunnel test hangs for some reason with SocketChannel
                    final Socket client = new Socket();
                    client.connect(new InetSocketAddress("localhost", portToUse));
                    EasyThread serverReaderThread = new EasyThread() {
                        @Override
                        public void runQuietly() {
                            try {
                                BufferedReader clientIn = new BufferedReader(
                                        new InputStreamReader(client.getInputStream()));
                                String line = clientIn.readLine();
                                while (line != null && !line.equals("Goodbye")) {
                                    //LOG.info("\t" + clientId + ": Server said [" + line.substring(0, 32) + "... ]");
                                    digestMsgsRecvdAtClient.update(line.getBytes());
                                    digestMsgsRecvdAtClient.update("\n".getBytes());
                                    line = clientIn.readLine();
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            LOG.info("\t" + clientId + ": Client done reading");
                        }
                    }.startThread();

                    MessageDigest hashMsgsFromClient = digestMsgsSentByClients.get(Integer.toString(clientId));
                    BufferedOutputStream clientOut = new BufferedOutputStream(client.getOutputStream());
                    for (int i = 0; i < nMsgs; i++) {
                        String msg = clientId + ":" + i + " " + StringUtils.repeat("Blahhh Blahhh ", 10000)
                                + "\n";
                        //LOG.info(clientId + " sending " + msg.length() + " bytes");
                        byte[] bytes = msg.getBytes();
                        hashMsgsFromClient.update(bytes);
                        clientOut.write(bytes);
                        MockServer.sleepQuietly(2);
                    }
                    clientOut.write(("Goodbye\n".getBytes()));
                    clientOut.flush();
                    LOG.info("\t" + clientId + ": Client done writing in " + (System.currentTimeMillis() - t)
                            + " ms");
                    serverReaderThread.join();
                    LOG.info("\t" + clientId + ": Client done in " + (System.currentTimeMillis() - t) + " ms");
                    client.close();
                }
            }.startThread());
        }
        for (Thread clientThread : clientThreads) {
            clientThread.join();
        }
        LOG.info("All data transfer done in " + (System.currentTimeMillis() - t0) + " ms");
    } finally {
        talkPastServer.stopServer();
        if (tunnel != null) {
            proxyServer.stopServer();
            tunnel.close();
            assertFalse(tunnel.isTunnelThreadAlive());
            assertEquals(proxyServer.getNumConnects(), nclients);
        }

        Map<String, String> hashOfMsgsRecvdAtServer = new HashMap<String, String>();
        Map<String, String> hashOfMsgsSentByClients = new HashMap<String, String>();
        Map<String, String> hashOfMsgsRecvdAtClients = new HashMap<String, String>();
        for (int c = 0; c < nclients; c++) {
            String client = Integer.toString(c);
            hashOfMsgsRecvdAtServer.put(client,
                    Hex.encodeHexString(digestMsgsRecvdAtServer.get(client).digest()));
            hashOfMsgsSentByClients.put(client,
                    Hex.encodeHexString(digestMsgsSentByClients.get(client).digest()));
            hashOfMsgsRecvdAtClients.put(client,
                    Hex.encodeHexString(digestMsgsRecvdAtClients.get(client).digest()));
        }

        LOG.info("\tComparing client sent to server received");
        assertEquals(hashOfMsgsSentByClients, hashOfMsgsRecvdAtServer);

        LOG.info("\tComparing server sent to client received");
        for (String hashOfMsgsRecvdAtClient : hashOfMsgsRecvdAtClients.values()) {
            assertEquals(hashOfMsgsSentByServer, hashOfMsgsRecvdAtClient);
        }
        LOG.info("\tDone");
    }
}

From source file:com.symbian.driver.core.controller.tasks.TEFTask.java

/**
 * @param aVisitor/*from w w  w .jav a2 s  . co m*/
 * @param aTestExecuteScript
 * @param lExecuteOnDevice
 * @param aTask
 * @return The last execption raised when running UCC.
 * @throws JStatException
 */
private boolean runUCC(List<String> aArgs, Task aTask) {
    boolean lReturn = true;
    Socket lUccSocket = null;
    DataOutputStream lSocketOut = null;
    DataInputStream lSocketIn = null;
    int lRunNumber = 0;
    int lUccPort = -1;
    String lUccAddress = null;
    IDeviceComms.ISymbianProcess lProcess = null;

    try {
        String[] lUccSplit = TDConfig.getInstance().getPreference(TDConfig.UCC_IP_ADDRESS).split(":");
        lRunNumber = TDConfig.getInstance().getPreferenceInteger(TDConfig.RUN_NUMBER);

        lUccAddress = lUccSplit[0];
        lUccPort = Integer.parseInt(lUccSplit[1]);
    } catch (ParseException lParseException) {
        LOGGER.log(Level.SEVERE, "Could not get configuration for UCC.", lParseException);
        iExceptions.put(lParseException, ESeverity.ERROR);
        lReturn = false;
    } catch (NumberFormatException lNumberFormatException) {
        LOGGER.log(Level.SEVERE, "Could not parse the port number for UCC.", lNumberFormatException);
        iExceptions.put(lNumberFormatException, ESeverity.ERROR);
        lReturn = false;
    }

    if (lUccAddress == null || lUccAddress.equals("") || lUccPort < 0) {
        iExceptions.put(
                new UnknownHostException("Please specify a valid UCC address for example 192.168.0.1:3000"),
                ESeverity.ERROR);
        return false;
    }

    // Run the test
    try {
        LOGGER.info("Running UCC with:\n\tAddress: " + lUccAddress + "\n\tUCC Port:" + lUccPort);

        lUccSocket = new Socket(lUccAddress, lUccPort);
        lSocketOut = new DataOutputStream(lUccSocket.getOutputStream());
        lSocketIn = new DataInputStream(lUccSocket.getInputStream());

        LOGGER.fine("Starting UCC while still polling");
        lProcess = iDeviceProxy.createSymbianProcess();
        if (lProcess != null) {
            // run and don't wait
            if (!lProcess.runCommand(TEST_EXECUTE, aArgs, aTask.getTimeout() * 1000, false)) {
                iExceptions.put(new Exception("Failed to run TEF for UCC."), ESeverity.ERROR);
                lReturn = false;
            }

            // Tell UCC that the test has started.
            LOGGER.fine("Writing to UCC socket: " + lRunNumber);
            lSocketOut.writeInt(lRunNumber);
            lSocketOut.flush();

            int lUCCReply = lSocketIn.readInt();
            LOGGER.fine("UCC Reply: " + lUCCReply);
        }

    } catch (UnknownHostException lUnknownHostException) {
        LOGGER.log(Level.SEVERE, "Could not find UCC host", lUnknownHostException);
        iExceptions.put(lUnknownHostException, ESeverity.ERROR);
        return false;
    } catch (IOException lIOException) {
        LOGGER.log(Level.SEVERE,
                "IO Exception during UCC testing: " + lIOException.getMessage() + (lUccSocket != null
                        ? "\nUcc Socket Connected: " + lUccSocket.isConnected() + "\nUcc Socket InputShutdown: "
                                + lUccSocket.isInputShutdown() + "\nUcc Socket OutputShutdown:"
                                + lUccSocket.isOutputShutdown() + "\nUcc Socket Bound: " + lUccSocket.isBound()
                        : "\nUcc Socket is NULL"),
                lIOException);
        iExceptions.put(lIOException, ESeverity.ERROR);
        return false;
    } finally {

        // Close UCC
        if (lSocketOut != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket Out.");
                lUccSocket.shutdownInput();
                lUccSocket.shutdownOutput();
                lSocketOut.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC Out socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lSocketIn != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket In.");
                lSocketIn.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC In socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }
        if (lUccSocket != null) {
            try {
                LOGGER.log(Level.FINE, "Closing Socket UCC.");
                lUccSocket.close();
            } catch (IOException lIOException) {
                LOGGER.log(Level.SEVERE, "Could not close UCC socket.", lIOException);
                iExceptions.put(lIOException, ESeverity.ERROR);
            }
        }

        if (!lUccSocket.isClosed()) {
            LOGGER.warning("Could not close the UCC sockets properly.");
        }

        lSocketOut = null;
        lSocketIn = null;
        lUccSocket = null;

        // Poll TEF Test
        if (!lProcess.join()) {
            iExceptions.put(new Exception("Coud not join UCC-TEF Process"), ESeverity.ERROR);
            lReturn = false;
        }

    }
    return lReturn;
}