Example usage for java.net Socket close

List of usage examples for java.net Socket close

Introduction

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

Prototype

public synchronized void close() throws IOException 

Source Link

Document

Closes this socket.

Usage

From source file:com.app.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;/*from   w  ww . j  a  v  a 2  s. c om*/
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //log.info(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //log.info(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //log.info("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //log.info("In read obect");
                                    object = ois.readObject();
                                    //log.info("Class Cast");
                                    //log.info("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //log.info("readObject");
                                    //log.info("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //log.info("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //log.info(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //log.info(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap.get(deployDirectory
                                                + "/" + serviceRegistry[0] + "/" + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // log.info("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // log.info("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * log.info(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //log.info("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //log.info("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //log.info(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //log.info("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //log.info(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //log.info("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //log.info("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;
                                    Enumeration<NodeResourceInfo> noderesourceInfos = addressmap.elements();
                                    NodeResourceInfo noderesourceinfo = null;
                                    String ip = "";
                                    int port = 1000;
                                    long memavailable = 0;
                                    long memcurr = 0;
                                    if (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            ip = noderesourceinfo.getHost();
                                            port = Integer.parseInt(noderesourceinfo.getPort());
                                            memavailable = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            ;
                                        }
                                    }

                                    while (noderesourceInfos.hasMoreElements()) {
                                        noderesourceinfo = noderesourceInfos.nextElement();
                                        if (noderesourceinfo.getMax() != null) {
                                            memcurr = Long.parseLong(noderesourceinfo.getMax())
                                                    - Long.parseLong(noderesourceinfo.getUsed());
                                            if (memavailable <= memcurr) {
                                                ip = noderesourceinfo.getHost();
                                                port = Integer.parseInt(noderesourceinfo.getPort());
                                                memavailable = memcurr;
                                            }
                                        }
                                    }
                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket(ip, port);
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //log.info("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   log.info("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //log.info("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //log.info("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //log.info(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //log.info("In write1");
                                numberOfServicesRequests++;
                                //log.info("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        log.error("Error in executing the executor services thread", ex);
                        //ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {
                log.error("Error in executing the executor services thread", ex);
                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        log.error("Error in executing the executor services thread", ex);
    }
}

From source file:net.demilich.metastone.bahaviour.ModifiedMCTS.MCTSCritique.java

public void sendCaffeData(double[][] data2, double[][] labels2, double[][] weights, String name,
        boolean ordered, boolean file) {
    double[][] data = new double[data2.length][];
    double[][] labels = new double[data2.length][];
    if (!ordered) {
        for (int i = 0; i < data2.length; i++) {
            data[i] = data2[i].clone();//w w  w  .j a  va 2  s  . c  om
            labels[i] = labels2[i].clone();
        }
    } else {
        data = data2;
        labels = labels2;
    }
    try {
        String sentence;
        String modifiedSentence;
        Random generator = new Random();
        //set up our socket server

        BufferedReader inFromServer = null;
        DataOutputStream outToServer = null;
        Socket clientSocket = null;

        //add in data in a random order
        if (!file) {
            System.err.println("starting to send on socket");
            clientSocket = new Socket("localhost", 5004);
            clientSocket.setTcpNoDelay(false);
            outToServer = new DataOutputStream(clientSocket.getOutputStream());
            inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            outToServer.writeBytes(name + "\n");

            outToServer.writeBytes((data.length + " " + data[0].length + " " + labels[0].length) + "\n");
            try {
                Thread.sleep(10000);
            } catch (Exception e) {
            }
        } else {
            outToServer = new DataOutputStream((OutputStream) new FileOutputStream(name));
        }
        StringBuffer wholeMessage = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            if (i % 1000 == 0) {
                System.err.println("(constructed) i is " + i);
            }
            String features = "";
            int randomIndex = generator.nextInt(data.length - i);

            if (!ordered) {
                swap(data, i, i + randomIndex);
                swap(labels, i, i + randomIndex);
            }
            for (int a = 0; a < data[i].length; a++) {
                wholeMessage.append(data[i][a] + " ");
            }
            wholeMessage.append("\n");
            String myLabels = "";
            for (int a = 0; a < labels[i].length; a++) {
                wholeMessage.append(labels[i][a] + " ");
            }
            wholeMessage.append("\n");
            wholeMessage.append(weights[i][0] + "");
            wholeMessage.append("\n");
            outToServer.writeBytes(wholeMessage.toString());
            wholeMessage = new StringBuffer();

        }
        System.err.println("total message size is " + wholeMessage.toString().length());

        //outToServer.writeBytes(wholeMessage.toString());
        if (!file) {
            System.err.println("sending done");
            outToServer.writeBytes("done\n");
            System.err.println("waiting for ack...");
            inFromServer.readLine();
            System.err.println("got the ack!");
            clientSocket.close();
        }

    } catch (Exception e) {
        e.printStackTrace();
        System.err.println("server wasn't waiting");
    }
    System.err.println("hey i sent somethin!");

}

From source file:org.alfresco.filesys.config.ServerConfigurationBean.java

/**
 * Process the CIFS server configuration
 *//*  w ww  . ja  va2s.  com*/
protected void processCIFSServerConfig() {
    // If the configuration section is not valid then CIFS is disabled

    if (cifsConfigBean == null) {
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Check if the server has been disabled
    if (!cifsConfigBean.getServerEnabled()) {
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Before we go any further, let's make sure there's a compatible authenticator in the authentication chain.
    ICifsAuthenticator authenticator = cifsConfigBean.getAuthenticator();
    if (authenticator == null
            || authenticator instanceof ActivateableBean && !((ActivateableBean) authenticator).isActive()) {
        logger.error("No enabled CIFS authenticator found in authentication chain. CIFS Server disabled");
        removeConfigSection(CIFSConfigSection.SectionName);
        return;
    }

    // Create the CIFS server configuration section

    CIFSConfigSection cifsConfig = new CIFSConfigSection(this);

    try {
        // Check if native code calls should be disabled on Windows
        if (cifsConfigBean.getDisableNativeCode()) {
            // Disable native code calls so that the JNI DLL is not required

            cifsConfig.setNativeCodeDisabled(true);
            m_disableNativeCode = true;

            // Warning

            logger.warn("CIFS server native calls disabled, JNI code will not be used");
        }

        // Get the network broadcast address
        //
        // Note: We need to set this first as the call to getLocalDomainName() may use a NetBIOS
        // name lookup, so the broadcast mask must be set before then.

        String broadcastAddess = cifsConfigBean.getBroadcastAddress();
        if (broadcastAddess != null && broadcastAddess.length() > 0) {

            // Check if the broadcast mask is a valid numeric IP address

            if (IPAddress.isNumericAddress(broadcastAddess) == false) {
                throw new AlfrescoRuntimeException("CIFS Invalid broadcast mask, must be n.n.n.n format");
            }

            // Set the network broadcast mask

            cifsConfig.setBroadcastMask(broadcastAddess);
        }

        // Get the terminal server address

        List<String> terminalServerList = cifsConfigBean.getTerminalServerList();
        if (terminalServerList != null && terminalServerList.size() > 0) {
            // Check if the terminal server address is a valid numeric IP address
            for (String terminalServerAddress : terminalServerList) {
                if (IPAddress.isNumericAddress(terminalServerAddress) == false)
                    throw new AlfrescoRuntimeException(
                            "Invalid terminal server address, must be n.n.n.n format");
            }
            // Set the terminal server address

            cifsConfig.setTerminalServerList(terminalServerList);
        }

        // Get the load balancer address

        List<String> loadBalancerList = cifsConfigBean.getLoadBalancerList();
        if (loadBalancerList != null && loadBalancerList.size() > 0) {
            // Check if the load balancer address is a valid numeric IP address
            for (String loadBalancerAddress : loadBalancerList) {
                if (IPAddress.isNumericAddress(loadBalancerAddress) == false)
                    throw new AlfrescoRuntimeException("Invalid load balancer address, must be n.n.n.n format");
            }
            // Set the terminal server address

            cifsConfig.setLoadBalancerList(loadBalancerList);
        }

        // Get the host configuration

        String hostName = cifsConfigBean.getServerName();
        if (hostName == null || hostName.length() == 0) {
            throw new AlfrescoRuntimeException("CIFS Host name not specified or invalid");
        }

        // Get the local server name

        String srvName = getLocalServerName(true);

        // Check if the host name contains the local name token

        int pos = hostName.indexOf(TokenLocalName);
        if (pos != -1) {
            // Rebuild the host name substituting the token with the local server name

            StringBuilder hostStr = new StringBuilder();

            hostStr.append(hostName.substring(0, pos));
            hostStr.append(srvName);

            pos += TokenLocalName.length();
            if (pos < hostName.length()) {
                hostStr.append(hostName.substring(pos));
            }

            hostName = hostStr.toString();
        }

        // Make sure the CIFS server name does not match the local server name

        if (hostName.toUpperCase().equals(srvName.toUpperCase())
                && getPlatformType() == Platform.Type.WINDOWS) {
            throw new AlfrescoRuntimeException("CIFS server name must be unique");
        }

        // Check if the host name is longer than 15 characters. NetBIOS only allows a maximum of 16 characters in
        // the
        // server name with the last character reserved for the service type.

        if (hostName.length() > 15) {
            // Truncate the CIFS server name

            hostName = hostName.substring(0, 15);

            // Output a warning

            logger.warn("CIFS server name is longer than 15 characters, truncated to " + hostName);
        }

        // Set the CIFS server name

        cifsConfig.setServerName(hostName.toUpperCase());
        setServerName(hostName.toUpperCase());

        // Get the domain/workgroup name

        String domain = cifsConfigBean.getDomainName();
        if (domain != null && domain.length() > 0) {
            // Set the domain/workgroup name

            cifsConfig.setDomainName(domain.toUpperCase());
        } else {
            // Get the local domain/workgroup name

            String localDomain = getLocalDomainName();

            if (localDomain == null && (getPlatformType() != Platform.Type.WINDOWS || isNativeCodeDisabled())) {
                // Use a default domain/workgroup name

                localDomain = "WORKGROUP";

                // Output a warning
                logger.warn("CIFS, Unable to get local domain/workgroup name, using default of " + localDomain
                        + ". This may be due to firewall settings or incorrect <broadcast> setting)");
            }

            // Set the local domain/workgroup that the CIFS server belongs to

            cifsConfig.setDomainName(localDomain);
        }

        // Check for a server comment

        String comment = cifsConfigBean.getServerComment();
        if (comment != null && comment.length() > 0) {
            cifsConfig.setComment(comment);
        }

        // Set the maximum virtual circuits per session

        if (cifsConfigBean.getMaximumVirtualCircuits() < VirtualCircuitList.MinCircuits
                || cifsConfigBean.getMaximumVirtualCircuits() > VirtualCircuitList.MaxCircuits)
            throw new AlfrescoRuntimeException("Invalid virtual circuits value, valid range is "
                    + VirtualCircuitList.MinCircuits + " - " + VirtualCircuitList.MaxCircuits);
        else
            cifsConfig.setMaximumVirtualCircuits(cifsConfigBean.getMaximumVirtualCircuits());

        // Check for a bind address

        // Check if the network adapter name has been specified
        String bindToAdapter = cifsConfigBean.getBindToAdapter();
        String bindTo;

        if (bindToAdapter != null && bindToAdapter.length() > 0) {

            // Get the IP address for the adapter

            InetAddress bindAddr = parseAdapterName(bindToAdapter);

            // Set the bind address for the server

            cifsConfig.setSMBBindAddress(bindAddr);
        } else if ((bindTo = cifsConfigBean.getBindToAddress()) != null && bindTo.length() > 0
                && !bindTo.equals(BIND_TO_IGNORE)) {

            // Validate the bind address
            try {
                // Check the bind address

                InetAddress bindAddr = InetAddress.getByName(bindTo);

                // Set the bind address for the server

                cifsConfig.setSMBBindAddress(bindAddr);
            } catch (UnknownHostException ex) {
                throw new AlfrescoRuntimeException("CIFS Unable to bind to address :" + bindTo, ex);
            }
        }

        // Get the authenticator

        if (authenticator != null) {
            cifsConfig.setAuthenticator(authenticator);
        } else {
            throw new AlfrescoRuntimeException("CIFS authenticator not specified");
        }

        // Check if the host announcer has been disabled

        if (!cifsConfigBean.getHostAccouncerEnabled()) {
            // Switch off the host announcer

            cifsConfig.setHostAnnouncer(false);

            // Log that host announcements are not enabled

            logger.info("CIFS Host announcements not enabled");
        } else {
            // Check for an announcement interval

            Integer interval = cifsConfigBean.getHostAccounceInterval();
            if (interval != null) {
                cifsConfig.setHostAnnounceInterval(interval);
            }

            // Check if the domain name has been set, this is required if the
            // host announcer is enabled

            if (cifsConfig.getDomainName() == null) {
                throw new AlfrescoRuntimeException(
                        "CIFS Domain name must be specified if host announcement is enabled");
            }

            // Enable host announcement

            cifsConfig.setHostAnnouncer(true);
        }

        // Check if NetBIOS SMB is enabled
        NetBIOSSMBConfigBean netBIOSSMBConfigBean = cifsConfigBean.getNetBIOSSMB();
        if (netBIOSSMBConfigBean != null) {
            // Check if NetBIOS over TCP/IP is enabled for the current platform

            String platformsStr = netBIOSSMBConfigBean.getPlatforms();
            boolean platformOK = false;

            if (platformsStr != null && platformsStr.length() > 0) {
                // Parse the list of platforms that NetBIOS over TCP/IP is to be enabled for and
                // check if the current platform is included

                EnumSet<Platform.Type> enabledPlatforms = parsePlatformString(platformsStr);
                if (enabledPlatforms.contains(getPlatformType()))
                    platformOK = true;
            } else {
                // No restriction on platforms

                platformOK = true;
            }

            // Enable the NetBIOS SMB support, if enabled for this platform

            cifsConfig.setNetBIOSSMB(platformOK);

            // Parse/check NetBIOS settings, if enabled

            if (cifsConfig.hasNetBIOSSMB()) {
                // Check if the broadcast mask has been specified

                if (cifsConfig.getBroadcastMask() == null) {
                    throw new AlfrescoRuntimeException("CIFS Network broadcast mask not specified");
                }

                // Check for a bind address

                String bindto = netBIOSSMBConfigBean.getBindTo();
                if (bindto != null && bindto.length() > 0 && !bindto.equals(BIND_TO_IGNORE)) {

                    // Validate the bind address

                    try {

                        // Check the bind address

                        InetAddress bindAddr = InetAddress.getByName(bindto);

                        // Set the bind address for the NetBIOS name server

                        cifsConfig.setNetBIOSBindAddress(bindAddr);
                    } catch (UnknownHostException ex) {
                        throw new AlfrescoRuntimeException("CIFS Invalid NetBIOS bind address:" + bindto, ex);
                    }
                } else if (cifsConfig.hasSMBBindAddress()) {

                    // Use the SMB bind address for the NetBIOS name server

                    cifsConfig.setNetBIOSBindAddress(cifsConfig.getSMBBindAddress());
                } else {
                    // Get a list of all the local addresses

                    InetAddress[] addrs = null;

                    try {
                        // Get the local server IP address list

                        addrs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
                    } catch (UnknownHostException ex) {
                        logger.error("CIFS Failed to get local address list", ex);
                    }

                    // Check the address list for one or more valid local addresses filtering out the loopback
                    // address

                    int addrCnt = 0;

                    if (addrs != null) {
                        for (int i = 0; i < addrs.length; i++) {

                            // Check for a valid address, filter out '127.0.0.1' and '0.0.0.0' addresses

                            if (addrs[i].getHostAddress().equals("127.0.0.1") == false
                                    && addrs[i].getHostAddress().equals("0.0.0.0") == false)
                                addrCnt++;
                        }
                    }

                    // Check if any addresses were found

                    if (addrCnt == 0) {
                        // Enumerate the network adapter list

                        Enumeration<NetworkInterface> niEnum = null;

                        try {
                            niEnum = NetworkInterface.getNetworkInterfaces();
                        } catch (SocketException ex) {
                        }

                        if (niEnum != null) {
                            while (niEnum.hasMoreElements()) {
                                // Get the current network interface

                                NetworkInterface ni = niEnum.nextElement();

                                // Enumerate the addresses for the network adapter

                                Enumeration<InetAddress> niAddrs = ni.getInetAddresses();
                                if (niAddrs != null) {
                                    // Check for any valid addresses

                                    while (niAddrs.hasMoreElements()) {
                                        InetAddress curAddr = niAddrs.nextElement();

                                        if (curAddr.getHostAddress().equals("127.0.0.1") == false
                                                && curAddr.getHostAddress().equals("0.0.0.0") == false)
                                            addrCnt++;
                                    }
                                }
                            }

                            // DEBUG

                            if (addrCnt > 0 && logger.isDebugEnabled())
                                logger.debug("Found valid IP address from interface list");
                        }

                        // Check if we found any valid network addresses

                        if (addrCnt == 0) {
                            // Log the available IP addresses

                            if (logger.isDebugEnabled()) {
                                logger.debug("Local address list dump :-");
                                if (addrs != null) {
                                    for (int i = 0; i < addrs.length; i++)
                                        logger.debug("  Address: " + addrs[i]);
                                } else {
                                    logger.debug("  No addresses");
                                }
                            }

                            // Throw an exception to stop the CIFS/NetBIOS name server from starting

                            throw new AlfrescoRuntimeException(
                                    "Failed to get IP address(es) for the local server, check hosts file and/or DNS setup");
                        }
                    }
                }

                // Check if the session port has been specified

                Integer portNum = netBIOSSMBConfigBean.getSessionPort();
                if (portNum != null) {
                    cifsConfig.setSessionPort(portNum);
                    if (cifsConfig.getSessionPort() <= 0 || cifsConfig.getSessionPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS session port out of valid range");
                }

                // Check if the name port has been specified

                portNum = netBIOSSMBConfigBean.getNamePort();
                if (portNum != null) {
                    cifsConfig.setNameServerPort(portNum);
                    if (cifsConfig.getNameServerPort() <= 0 || cifsConfig.getNameServerPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS name port out of valid range");
                }

                // Check if the datagram port has been specified

                portNum = netBIOSSMBConfigBean.getDatagramPort();
                if (portNum != null) {
                    cifsConfig.setDatagramPort(portNum);
                    if (cifsConfig.getDatagramPort() <= 0 || cifsConfig.getDatagramPort() >= 65535)
                        throw new AlfrescoRuntimeException("NetBIOS datagram port out of valid range");
                }

                // Check for a bind address

                String attr = netBIOSSMBConfigBean.getBindTo();
                if (attr != null && attr.length() > 0 && !attr.equals(BIND_TO_IGNORE)) {

                    // Validate the bind address

                    try {

                        // Check the bind address

                        InetAddress bindAddr = InetAddress.getByName(attr);

                        // Set the bind address for the NetBIOS name server

                        cifsConfig.setNetBIOSBindAddress(bindAddr);
                    } catch (UnknownHostException ex) {
                        throw new InvalidConfigurationException(ex.toString());
                    }
                }

                // Check for a bind address using the adapter name

                else if ((attr = netBIOSSMBConfigBean.getAdapter()) != null && attr.length() > 0) {

                    // Get the bind address via the network adapter name

                    InetAddress bindAddr = parseAdapterName(attr);
                    cifsConfig.setNetBIOSBindAddress(bindAddr);
                } else if (cifsConfig.hasSMBBindAddress()) {

                    // Use the SMB bind address for the NetBIOS name server

                    cifsConfig.setNetBIOSBindAddress(cifsConfig.getSMBBindAddress());
                }

            }
        } else {

            // Disable NetBIOS SMB support

            cifsConfig.setNetBIOSSMB(false);
        }

        // Check if TCP/IP SMB is enabled

        TcpipSMBConfigBean tcpipSMBConfigBean = cifsConfigBean.getTcpipSMB();
        if (tcpipSMBConfigBean != null) {

            // Check if native SMB is enabled for the current platform

            String platformsStr = tcpipSMBConfigBean.getPlatforms();
            boolean platformOK = false;

            if (platformsStr != null) {
                // Parse the list of platforms that native SMB is to be enabled for and
                // check if the current platform is included

                EnumSet<Platform.Type> enabledPlatforms = parsePlatformString(platformsStr);
                if (enabledPlatforms.contains(getPlatformType()))
                    platformOK = true;
            } else {
                // No restriction on platforms

                platformOK = true;
            }

            // Enable the TCP/IP SMB support, if enabled for this platform

            cifsConfig.setTcpipSMB(platformOK);

            // Check if the port has been specified

            Integer portNum = tcpipSMBConfigBean.getPort();
            if (portNum != null) {
                cifsConfig.setTcpipSMBPort(portNum);
                if (cifsConfig.getTcpipSMBPort() <= 0 || cifsConfig.getTcpipSMBPort() >= 65535)
                    throw new AlfrescoRuntimeException("TCP/IP SMB port out of valid range");
            }

            // Check if IPv6 support should be enabled

            if (tcpipSMBConfigBean.getIpv6Enabled()) {
                try {
                    // Use the IPv6 bind all address

                    cifsConfig.setSMBBindAddress(InetAddress.getByName("::"));

                    // DEBUG

                    if (logger.isInfoEnabled()) {
                        logger.info("Enabled CIFS IPv6 bind address for native SMB");

                    }
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException(
                            "CIFS Failed to enable IPv6 bind address, " + ex.getMessage());
                }
            }

        } else {

            // Disable TCP/IP SMB support

            cifsConfig.setTcpipSMB(false);
        }

        // Check if Win32 NetBIOS is enabled

        Win32NetBIOSConfigBean win32NetBIOSConfigBean = cifsConfigBean.getWin32NetBIOS();
        if (win32NetBIOSConfigBean != null) {

            // Check if the Win32 NetBIOS server name has been specified

            String win32Name = win32NetBIOSConfigBean.getName();
            if (win32Name != null && win32Name.length() > 0) {

                // Validate the name

                if (win32Name.length() > 16)
                    throw new AlfrescoRuntimeException("Invalid Win32 NetBIOS name, " + win32Name);

                // Set the Win32 NetBIOS file server name

                cifsConfig.setWin32NetBIOSName(win32Name);
            }

            // Check if the Win32 NetBIOS LANA has been specified

            String lanaStr = win32NetBIOSConfigBean.getLana();
            if (lanaStr != null && lanaStr.length() > 0) {
                // Check if the LANA has been specified as an IP address or adapter name

                int lana = -1;

                if (IPAddress.isNumericAddress(lanaStr)) {

                    // Convert the IP address to a LANA id

                    lana = Win32NetBIOS.getLANAForIPAddress(lanaStr);
                    if (lana == -1)
                        throw new AlfrescoRuntimeException(
                                "Failed to convert IP address " + lanaStr + " to a LANA");
                } else if (lanaStr.length() > 1 && Character.isLetter(lanaStr.charAt(0))) {

                    // Convert the network adapter to a LANA id

                    lana = Win32NetBIOS.getLANAForAdapterName(lanaStr);
                    if (lana == -1)
                        throw new AlfrescoRuntimeException(
                                "Failed to convert network adapter " + lanaStr + " to a LANA");
                } else {

                    try {
                        lana = Integer.parseInt(lanaStr);
                    } catch (NumberFormatException ex) {
                        throw new AlfrescoRuntimeException("Invalid win32 NetBIOS LANA specified");
                    }
                }

                // LANA should be in the range 0-255

                if (lana < 0 || lana > 255)
                    throw new AlfrescoRuntimeException("Invalid Win32 NetBIOS LANA number, " + lana);

                // Set the LANA number

                cifsConfig.setWin32LANA(lana);
            }

            // Check if the native NetBIOS interface has been specified, either 'winsock' or 'netbios'

            String nativeAPI = win32NetBIOSConfigBean.getApi();
            if (nativeAPI != null && nativeAPI.length() > 0) {
                // Validate the API type

                boolean useWinsock = true;

                if (nativeAPI.equalsIgnoreCase("netbios"))
                    useWinsock = false;
                else if (nativeAPI.equalsIgnoreCase("winsock") == false)
                    throw new AlfrescoRuntimeException(
                            "Invalid NetBIOS API type, spefify 'winsock' or 'netbios'");

                // Set the NetBIOS API to use

                cifsConfig.setWin32WinsockNetBIOS(useWinsock);
            }

            // Force the older NetBIOS API code to be used on 64Bit Windows

            if (cifsConfig.useWinsockNetBIOS() == true && X64.isWindows64()) {
                // Debug

                if (logger.isDebugEnabled())
                    logger.debug("Using older Netbios() API code");

                // Use the older NetBIOS API code

                cifsConfig.setWin32WinsockNetBIOS(false);
            }

            // Check if the current operating system is supported by the Win32
            // NetBIOS handler

            String osName = System.getProperty("os.name");
            if (osName.startsWith("Windows") && (osName.endsWith("95") == false
                    && osName.endsWith("98") == false && osName.endsWith("ME") == false)
                    && isNativeCodeDisabled() == false) {

                // Call the Win32NetBIOS native code to make sure it is initialized

                if (Win32NetBIOS.LanaEnumerate() != null) {
                    // Enable Win32 NetBIOS

                    cifsConfig.setWin32NetBIOS(true);
                } else {
                    logger.warn("No NetBIOS LANAs available");
                }
            } else {

                // Win32 NetBIOS not supported on the current operating system

                cifsConfig.setWin32NetBIOS(false);
            }
        } else {

            // Disable Win32 NetBIOS

            cifsConfig.setWin32NetBIOS(false);
        }

        // Check if the Win32 host announcer has been disabled

        if (!cifsConfigBean.getWin32HostAnnouncerEnabled()) {
            // Switch off the Win32 host announcer

            cifsConfig.setWin32HostAnnouncer(false);

            // Log that host announcements are not enabled

            logger.info("Win32 host announcements not enabled");
        } else {
            // Check for an announcement interval
            Integer interval = cifsConfigBean.getWin32HostAnnounceInterval();
            if (interval != null) {
                cifsConfig.setWin32HostAnnounceInterval(interval);
            }

            // Check if the domain name has been set, this is required if the
            // host announcer is enabled

            if (cifsConfig.getDomainName() == null)
                throw new AlfrescoRuntimeException(
                        "Domain name must be specified if host announcement is enabled");

            // Enable Win32 NetBIOS host announcement

            cifsConfig.setWin32HostAnnouncer(true);
        }

        // Check if NetBIOS and/or TCP/IP SMB have been enabled

        if (cifsConfig.hasNetBIOSSMB() == false && cifsConfig.hasTcpipSMB() == false
                && cifsConfig.hasWin32NetBIOS() == false)
            throw new AlfrescoRuntimeException("NetBIOS SMB, TCP/IP SMB or Win32 NetBIOS must be enabled");

        // Check if WINS servers are configured

        WINSConfigBean winsConfigBean = cifsConfigBean.getWINSConfig();

        if (winsConfigBean != null && !winsConfigBean.isAutoDetectEnabled()) {

            // Get the primary WINS server

            String priWins = winsConfigBean.getPrimary();

            if (priWins == null || priWins.length() == 0)
                throw new AlfrescoRuntimeException("No primary WINS server configured");

            // Validate the WINS server address

            InetAddress primaryWINS = null;

            try {
                primaryWINS = InetAddress.getByName(priWins);
            } catch (UnknownHostException ex) {
                throw new AlfrescoRuntimeException("Invalid primary WINS server address, " + priWins);
            }

            // Check if a secondary WINS server has been specified

            String secWins = winsConfigBean.getSecondary();
            InetAddress secondaryWINS = null;

            if (secWins != null && secWins.length() > 0) {

                // Validate the secondary WINS server address

                try {
                    secondaryWINS = InetAddress.getByName(secWins);
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException("Invalid secondary WINS server address, " + secWins);
                }
            }

            // Set the WINS server address(es)

            cifsConfig.setPrimaryWINSServer(primaryWINS);
            if (secondaryWINS != null)
                cifsConfig.setSecondaryWINSServer(secondaryWINS);

            // Pass the setting to the NetBIOS session class

            NetBIOSSession.setDefaultWINSServer(primaryWINS);
        }

        // Check if WINS is configured, if we are running on Windows and socket based NetBIOS is enabled

        else if (cifsConfig.hasNetBIOSSMB() && getPlatformType() == Platform.Type.WINDOWS
                && !isNativeCodeDisabled()) {
            // Get the WINS server list

            String winsServers = Win32NetBIOS.getWINSServerList();

            if (winsServers != null) {
                // Use the first WINS server address for now

                StringTokenizer tokens = new StringTokenizer(winsServers, ",");
                String addr = tokens.nextToken();

                try {
                    // Convert to a network address and check if the WINS server is accessible

                    InetAddress winsAddr = InetAddress.getByName(addr);

                    Socket winsSocket = new Socket();
                    InetSocketAddress sockAddr = new InetSocketAddress(winsAddr, RFCNetBIOSProtocol.NAME_PORT);

                    winsSocket.connect(sockAddr, 3000);
                    winsSocket.close();

                    // Set the primary WINS server address

                    cifsConfig.setPrimaryWINSServer(winsAddr);

                    // Debug

                    if (logger.isDebugEnabled())
                        logger.debug("Configuring to use WINS server " + addr);
                } catch (UnknownHostException ex) {
                    throw new AlfrescoRuntimeException("Invalid auto WINS server address, " + addr);
                } catch (IOException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Failed to connect to auto WINS server " + addr);
                }
            }
        }

        // Check for session debug flags

        String flags = cifsConfigBean.getSessionDebugFlags();

        int sessDbg = 0;

        if (flags != null && flags.length() > 0) {

            // Parse the flags

            flags = flags.toUpperCase();
            StringTokenizer token = new StringTokenizer(flags, ",");

            while (token.hasMoreTokens()) {
                // Get the current debug flag token

                String dbg = token.nextToken().trim();

                // Find the debug flag name

                int idx = 0;

                while (idx < m_sessDbgStr.length && m_sessDbgStr[idx].equalsIgnoreCase(dbg) == false)
                    idx++;

                if (idx > m_sessDbgStr.length)
                    throw new AlfrescoRuntimeException("Invalid session debug flag, " + dbg);

                // Set the debug flag

                sessDbg += 1 << idx;
            }
        }

        // Set the session debug flags

        cifsConfig.setSessionDebugFlags(sessDbg);

        // Check if NIO based socket code should be disabled

        if (cifsConfigBean.getDisableNIO()) {

            // Disable NIO based code

            cifsConfig.setDisableNIOCode(true);

            // DEBUG

            if (logger.isDebugEnabled())
                logger.debug("NIO based code disabled for CIFS server");
        }

        // Check if a session timeout is configured

        Integer tmo = cifsConfigBean.getSessionTimeout();
        if (tmo != null) {

            // Validate the session timeout value

            cifsConfigBean.validateSessionTimeout(tmo);

            // Convert the session timeout to milliseconds

            cifsConfig.setSocketTimeout(tmo * 1000);
        }
    } catch (InvalidConfigurationException ex) {
        throw new AlfrescoRuntimeException(ex.getMessage());
    }
}

From source file:net.carlh.toast.Client.java

public void start(final String hostName, final int port)
        throws java.net.UnknownHostException, java.io.IOException {

    /* Thread to read stuff from the server */
    readThread = new Thread(new Runnable() {

        private byte[] getData(Socket socket, int length) {
            byte[] d = new byte[length];
            int offset = 0;
            while (offset < length) {
                try {
                    int t = socket.getInputStream().read(d, offset, length - offset);
                    if (t == -1) {
                        break;
                    }/*from w w  w . j  a  va 2s .co m*/
                    offset += t;
                } catch (SocketException e) {
                    /* This is probably because the socket has been closed in order to make
                       this thread terminate.
                    */
                    Log.e("Toast", "SocketException in client.getData", e);
                    break;
                } catch (IOException e) {
                    Log.e("Toast", "IOException in Client.getData()", e);
                    break;
                }
            }

            return java.util.Arrays.copyOf(d, offset);
        }

        public void run() {
            while (!stop.get()) {
                try {
                    synchronized (mutex) {
                        /* Connect */
                        socket = new Socket(hostName, port);
                        socket.setSoTimeout(timeout);
                    }

                    /* Keep going until there is a problem on read */

                    while (true) {
                        byte[] b = getData(socket, 4);

                        if (b.length != 4) {
                            break;
                        }

                        int length = ((b[0] & 0xff) << 24) | ((b[1] & 0xff) << 16) | ((b[2] & 0xff) << 8)
                                | (b[3] & 0xff);
                        if (length < 0 || length > (256 * 1024)) {
                            /* Don't like the sound of that */
                            Log.e("Toast", "Strange length " + length);
                            break;
                        }

                        byte[] d = getData(socket, length);

                        if (d.length != length) {
                            break;
                        }

                        try {
                            handler(new JSONObject(new String(d)));
                        } catch (JSONException e) {
                            Log.e("Toast", "Exception " + e.toString());
                        }
                    }

                    synchronized (mutex) {
                        /* Close the socket and go back round to connect again */
                        socket.close();
                        socket = null;
                    }

                } catch (ConnectException e) {
                    Log.e("Toast", "ConnectException");
                } catch (UnknownHostException e) {
                    Log.e("Toast", "UnknownHostException");
                } catch (IOException e) {
                    Log.e("Client", "IOException");
                } finally {
                    try {
                        Thread.sleep(timeout);
                    } catch (java.lang.InterruptedException e) {

                    }
                }
            }
        }
    });

    readThread.start();

    /* Thread to send stuff to the server */
    writeThread = new Thread(new Runnable() {

        public void run() {

            while (!stop.get()) {

                lock.lock();
                try {
                    while (toWrite.size() == 0 && !stop.get()) {
                        writeCondition.await();
                    }
                } catch (InterruptedException e) {

                } finally {
                    lock.unlock();
                }

                String s = null;
                lock.lock();
                if (toWrite.size() > 0) {
                    s = toWrite.get(0);
                    toWrite.remove(0);
                }
                lock.unlock();

                synchronized (mutex) {
                    try {
                        if (socket != null && s != null) {
                            socket.getOutputStream().write((s.length() >> 24) & 0xff);
                            socket.getOutputStream().write((s.length() >> 16) & 0xff);
                            socket.getOutputStream().write((s.length() >> 8) & 0xff);
                            socket.getOutputStream().write((s.length() >> 0) & 0xff);
                            socket.getOutputStream().write(s.getBytes());
                        }
                    } catch (IOException e) {
                        Log.e("Toast", "IOException in write");
                    }
                }
            }
        }
    });

    writeThread.start();

    /* Thread to send pings every so often */
    pingThread = new Thread(new Runnable() {
        public void run() {
            while (!stop.get()) {
                if (ping.get() == true && pong.get() == false) {
                    for (Handler h : handlers) {
                        h.sendEmptyMessage(0);
                    }
                    setConnected(false);
                }
                pong.set(false);
                try {
                    JSONObject json = new JSONObject();
                    json.put("type", "ping");
                    send(json);
                    ping.set(true);
                    Thread.sleep(pingInterval);
                } catch (JSONException e) {
                } catch (InterruptedException e) {
                }

            }
        }
    });

    pingThread.start();
}

From source file:com.web.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;/*from w  w  w.ja v a  2 s.  c  o  m*/
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //System.out.println(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //System.out.println(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //System.out.println("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //System.out.println("In read obect");
                                    object = ois.readObject();
                                    //System.out.println("Class Cast");
                                    //System.out.println("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //System.out.println("readObject");
                                    //System.out.println("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //System.out.println("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //System.out.println(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //System.out.println(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap
                                                .get(earServicesDirectory + "/" + serviceRegistry[0] + "/"
                                                        + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(jarservicesDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // System.out.println("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // System.out.println("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * System.out.println(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //System.out.println("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //System.out.println("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //System.out.println(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //System.out.println("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //System.out.println(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //System.out.println("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //System.out.println("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;

                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket("0.0.0.0",
                                            Integer.parseInt(nodesport[random.nextInt(nodesport.length)]));
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //System.out.println("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   System.out.println("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //System.out.println("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //System.out.println("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //System.out.println(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //System.out.println("In write1");
                                numberOfServicesRequests++;
                                //System.out.println("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {

                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        //ex.printStackTrace();
    }
}

From source file:com.tasktop.c2c.server.ssh.server.commands.AbstractInteractiveProxyCommand.java

protected void performCommand(Environment env, ProjectService service, String projectId, String path,
        String requestPath, RequestHeadersSupport headers) throws CommandException {
    String internalProxyUri = service.computeInternalProxyBaseUri(false);
    if (internalProxyUri == null) {
        throw new IllegalStateException();
    }/*from w w  w  . j  ava 2  s  .c o  m*/
    URI targetUri;
    try {
        if (!internalProxyUri.endsWith("/")) {
            internalProxyUri += "/";
        }
        internalProxyUri += getName() + '/' + path;

        targetUri = new URI(internalProxyUri);
    } catch (URISyntaxException e) {
        throw new RuntimeException(e);
    }
    String host = targetUri.getHost();
    int port = targetUri.getPort();
    if (port < 0) {
        port = 80;
    }
    if (targetUri.getScheme() == null || !targetUri.getScheme().equalsIgnoreCase("http")) {
        throw new IllegalStateException("scheme " + targetUri.getScheme() + " is not supported");
    }
    HeaderGroup headerGroup = computeHeaders(targetUri);
    for (Entry<String, List<String>> headerEntry : headers.getRequestHeaders().entrySet()) {
        for (String value : headerEntry.getValue()) {
            headerGroup.addHeader(new Header(headerEntry.getKey(), value));
        }
    }
    getLogger().info("Proxying " + getName() + " to " + targetUri);
    try {
        Socket socket = socketFactory.openConnection(host, port);
        try {
            // initiate an HTTP request with Transfer-Encoding: chunked
            OutputStream proxyOut = socket.getOutputStream();
            emitHttpRequestLine(proxyOut, targetUri);
            emitHeaders(proxyOut, headerGroup);

            proxyOut.flush();

            List<Callable<Void>> tasks = new ArrayList<Callable<Void>>(3);
            FlushingChunkedOutputStream chunkedRequestOut = new FlushingChunkedOutputStream(proxyOut);
            tasks.add(new InputPipe(in, chunkedRequestOut, bufferSize, Thread.currentThread()).flush(true));

            // start these pipes
            ExecutorService executor = Executors.newFixedThreadPool(tasks.size());
            try {
                for (Callable<Void> task : tasks) {
                    executor.submit(task);
                }

                InputStream proxyInput = socket.getInputStream();
                try {
                    readHttpResponse(proxyInput);
                    MultiplexingInputStream input = new MultiplexingInputStream(
                            new ChunkedInputStream(proxyInput));
                    for (;;) {
                        PacketType packetType = input.getPacketType();
                        if (packetType == null) {
                            break;
                        }
                        int length = input.getPacketLength();

                        processData(input, packetType, length);
                    }
                } finally {
                    try {
                        executor.shutdown();
                        executor.awaitTermination(1000L, TimeUnit.MILLISECONDS);
                    } catch (InterruptedException e) {
                        // ignore
                    }
                }
            } finally {
                executor.shutdownNow();
                try {
                    executor.awaitTermination(3000L, TimeUnit.MILLISECONDS);
                } catch (InterruptedException e) {
                    // ignore
                }
                Thread.interrupted();

                try {
                    // attempt to close the chunked output, since this will make us a well-behaved client
                    // by sending the closing chunk.
                    chunkedRequestOut.close();
                } catch (Throwable t) {
                    // ignore
                }
            }
        } finally {
            socket.close();
        }
    } catch (ConnectException e) {
        getLogger().error(e.getMessage(), e);
        throw new CommandException(-1, "Service temporarily unavailable");
    } catch (IOException e) {
        getLogger().warn(e.getMessage(), e);
        throw new CommandException(-1, e.getMessage());
    }
}

From source file:com.twinflag.coofiletouch.AuthorityChecking.java

private void fetchLicenseFromInternet() {
    Log.i(TAG, "===fetchLicenseFromInternet !");
    new Thread() {
        public void run() {
            try {
                JSONObject json = new JSONObject();
                try {
                    int readLength = 0;
                    int sendSize = 0;
                    json.put("command", "checkLicense");
                    json.put("hardinfo", DeviceUtil.getDeviceInfo());

                    Socket socket = new Socket("192.168.13.95", 60000);

                    // ?
                    OutputStream os = socket.getOutputStream();
                    String jsonStr = json.toString();
                    byte[] buffer = jsonStr.getBytes("UTF-8");
                    sendSize = buffer.length;
                    byte[] array = new byte[4];
                    array[3] = (byte) (0xff & sendSize);
                    array[2] = (byte) ((0xff00 & sendSize) >> 8);
                    array[1] = (byte) ((0xff0000 & sendSize) >> 16);
                    array[0] = (byte) (0xff000000 & sendSize >> 24);
                    os.write(array);//from   www  . j av a 2  s.  c  o m
                    os.flush();
                    os.write(buffer);
                    os.flush();

                    // ;
                    InputStream inputStream = socket.getInputStream();
                    byte[] length = new byte[4];
                    byte[] temp = new byte[4];
                    byte oneByte;
                    try {
                        inputStream.read(length);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    for (int i = 0; i < 4; i++) {
                        temp[3 - i] = length[i];
                    }
                    for (int j = 0; j < 4; j++) {
                        oneByte = temp[j];
                        readLength += (oneByte & 0xFF) << (8 * j);
                    }

                    System.out.println(readLength + "?");

                    if (readLength == 0) {
                        System.out.println("readLength == 0");
                        Message msg = Message.obtain();
                        msg.what = MSG_GET_LINCENSE_FROM_INTERNET;
                        msg.obj = null;
                        mHandler.sendMessageDelayed(msg, 100);
                    }
                    // ??0
                    else {
                        System.out.println("readLength == " + readLength);
                        buffer = new byte[readLength];
                        try {
                            String receivedContent = null;
                            inputStream.read(buffer, 0, readLength);
                            receivedContent = new String(buffer, "UTF-8");

                            Message msg = Message.obtain();
                            msg.what = MSG_GET_LINCENSE_FROM_INTERNET;
                            msg.obj = receivedContent;
                            mHandler.sendMessageDelayed(msg, 100);

                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    socket.close();

                } catch (JSONException exception) {
                    exception.printStackTrace();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }.start();

}

From source file:com.smartmarmot.dbforbix.config.Config.java

/**
 * Send request to Zabbix Server:/*from  w  ww. ja  v a 2 s .  c  om*/
 * @param host - Zabbix Server
 * @param port - Zabbix Server Port
 * @param json - body of request in json format
 * @return - body of response in json format
 */
public String requestZabbix(String host, int port, String json) {
    byte[] response = new byte[2048];
    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    byte[] data = null;
    String resp = new String();

    try {
        zabbix = new Socket();
        //TODO socket timeout has to be read from config file
        zabbix.setSoTimeout(30000);

        zabbix.connect(new InetSocketAddress(host, port));
        OutputStream os = zabbix.getOutputStream();

        data = getRequestToZabbixServer(json);

        //send request
        os.write(data);
        os.flush();

        //read response
        in = zabbix.getInputStream();

        //convert response to string (expecting json)
        int pos1 = 13;
        int bRead = 0;
        while (true) {
            bRead = in.read(response);
            //LOG.debug("read="+read+"\nresponse="+new String(response));
            if (bRead <= 0)
                break;
            //remove binary header
            resp += new String(Arrays.copyOfRange(response, pos1, bRead));
            pos1 = 0;
        }
        //LOG.debug("requestZabbix(): resp: "+ resp);
        //resp=resp.substring(13);//remove binary header
        if (resp.isEmpty())
            throw new ZBXBadResponseException("Zabbix Server (" + host + ":" + port
                    + ") has returned empty response for request:\n" + json);

    } catch (ZBXBadResponseException respEx) {
        LOG.error(respEx.getLocalizedMessage());
    } catch (Exception ex) {
        LOG.error("Error getting data from Zabbix server (" + host + ":" + port + "): " + ex.getMessage());
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
        if (out != null)
            try {
                out.close();
            } catch (IOException e) {
            }
        if (zabbix != null)
            try {
                zabbix.close();
            } catch (IOException e) {
            }
    }

    return resp;
}

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"));
    }//from ww  w.  ja v a 2 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");
    }
}