Example usage for java.net Socket getInputStream

List of usage examples for java.net Socket getInputStream

Introduction

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

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream for this socket.

Usage

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    }
    return lReturn;
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

private void transferCheckpoint(Socket sock) {
    synchronized (this.fileSystemLock) {
        BufferedReader brSock = null, brFile = null;
        try {/*from w w  w.j av a  2  s  . c  o  m*/
            brSock = new BufferedReader(new InputStreamReader(sock.getInputStream()));
            // first and only line is request
            String request = brSock.readLine();
            if ((new File(request).exists())) {
                // request is filename
                brFile = new BufferedReader(new InputStreamReader(new FileInputStream(request)));
                // file successfully open if here
                OutputStream outStream = sock.getOutputStream();
                String line = null; // each line is a record
                while ((line = brFile.readLine()) != null)
                    outStream.write(line.getBytes(CHARSET));
                outStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (brSock != null)
                    brSock.close();
                if (brFile != null)
                    brFile.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.trigger_context.Main_Service.java

private void takeAction(String mac, InetAddress ip) {
    noti("comes to ", mac);

    SharedPreferences conditions = getSharedPreferences(mac, MODE_PRIVATE);
    Map<String, ?> cond_map = conditions.getAll();
    Set<String> key_set = cond_map.keySet();
    Main_Service.main_Service.noti(cond_map.toString(), "");
    if (key_set.contains("SmsAction")) {
        String number = conditions.getString("SmsActionNumber", null);
        String message = conditions.getString("SmsActionMessage", null);

        try {/*from  www  .  j av a  2  s  . c o  m*/
            SmsManager smsManager = SmsManager.getDefault();
            smsManager.sendTextMessage(number, null, message, null, null);
            noti("Sms Sent To : ", "" + number);
        } catch (Exception e) {
            noti("Sms Sending To ", number + "Failed");
        }
    }
    if (key_set.contains("OpenWebsiteAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Open_Url.class);
        dialogIntent.putExtra("urlAction", (String) cond_map.get("urlAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);

    }
    if (key_set.contains("ToggleAction")) {
        if (key_set.contains("bluetoothAction") && conditions.getBoolean("bluetoothAction", false)) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.enable();
        } else if (key_set.contains("bluetoothAction")) {
            final BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            bluetoothAdapter.disable();
        }
        if (key_set.contains("wifiAction") && conditions.getBoolean("wifiAction", false)) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(true);
        } else if (key_set.contains("wifiAction")) {
            final WifiManager wm = (WifiManager) getSystemService(Context.WIFI_SERVICE);
            wm.setWifiEnabled(false);
        }
    }
    if (key_set.contains("TweetAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Post_Tweet.class);
        dialogIntent.putExtra("tweetTextAction", (String) cond_map.get("tweetTextAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }

    if (key_set.contains("EmailAction")) {
        Intent dialogIntent = new Intent(getBaseContext(), Action_Email_Client.class);
        dialogIntent.putExtra("toAction", (String) cond_map.get("toAction"));
        dialogIntent.putExtra("subjectAction", (String) cond_map.get("subjectAction"));
        dialogIntent.putExtra("emailMessageAction", (String) cond_map.get("emailMessageAction"));
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        getApplication().startActivity(dialogIntent);
    }
    if (key_set.contains("RemoteServerCmd")) {

        String text = conditions.getString("cmd", null);
        new Thread(new SendData("224.0.0.1", 9876, text)).start();
    }
    // network activities from here.
    // in all network actions send username first
    if (key_set.contains("FileTransferAction"))

    {
        String path = conditions.getString("filePath", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 1
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(1);
            sendFile(out, path);

            noti("Sent " + path + " file to :",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    if (key_set.contains("ccfMsgAction"))

    {
        String msg = conditions.getString("ccfMsg", null);
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 2 is msg
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataOutputStream out = null;
            out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(2);
            out.writeUTF(msg);

            noti("Sent msg : '" + msg + "'", "to : "
                    + getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (key_set.contains("sync")) {
        SharedPreferences my_data = getSharedPreferences(Main_Service.MY_DATA, MODE_PRIVATE);
        String usrName = my_data.getString("name", "userName");
        // type 3 is sync
        try {
            Socket socket = new Socket(ip, COMM_PORT);
            DataInputStream in = new DataInputStream(socket.getInputStream());
            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            out.writeUTF(usrName);
            out.writeInt(3);
            senderSync(in, out, Environment.getExternalStorageDirectory().getPath() + "/TriggerSync/");

            noti("Synced with:",
                    getSharedPreferences(Main_Service.USERS, MODE_PRIVATE).getString("name", "userName"));

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

From source file:edu.umass.cs.reconfiguration.SQLReconfiguratorDB.java

/**
 * Helper function for getRemoteCheckpoint above that actually fetches the
 * reads from the socket and writes to a local file.
 * /* w ww.  j  av a 2 s  .  c om*/
 * @param rcGroupName
 * @param sockAddr
 * @param remoteFilename
 * @param fileSize
 * @return
 */
private String getRemoteCheckpoint(String rcGroupName, InetSocketAddress sockAddr, String remoteFilename,
        long fileSize) {
    synchronized (this.fileSystemLock) {
        String request = remoteFilename + "\n";
        Socket sock = null;
        FileOutputStream fos = null;
        String localCPFilename = null;
        try {
            sock = new Socket(sockAddr.getAddress(), sockAddr.getPort());
            sock.getOutputStream().write(request.getBytes(CHARSET));
            InputStream inStream = (sock.getInputStream());
            if (!this.createCheckpointFile(localCPFilename = this.getCheckpointFile(rcGroupName)))
                return null;
            fos = new FileOutputStream(new File(localCPFilename));
            byte[] buf = new byte[1024];
            int nread = 0;
            int nTotalRead = 0;
            // read from sock, write to file
            while ((nread = inStream.read(buf)) >= 0) {
                /* Need to ensure that the read won't block forever if the
                 * remote endpoint crashes ungracefully and there is no
                 * exception triggered here. But this method itself is
                 * currently unused. */
                nTotalRead += nread;
                fos.write(buf, 0, nread);
            }
            // check exact expected file size
            if (nTotalRead != fileSize)
                localCPFilename = null;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null)
                    fos.close();
                if (sock != null)
                    sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return localCPFilename;
    }
}

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;/* www  .jav 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) {
                                    //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:ProcessRequest.java

public JSONObject getWeight(final String host, final int port, final int numChars, final int weightBeginPos,
        final int weightEndPos, final int termChar, final int statusBeginPos, final int statusEndPos,
        final int normalChar, final int motionChar, int timeout, final String overcapacity) {
    //Thread socketThread = new Thread() {
    //   public void run() {
    //cannot run in thread
    Socket connection = null;
    JSONObject returnObject = new JSONObject();
    try {//  w ww. j a  va 2s.c o m
        System.out.println("opening socket");
        connection = new Socket(host, port);
        System.out.println("getting stream");
        InputStreamReader reader = new InputStreamReader(connection.getInputStream());
        System.out.println("creating character buffer");
        boolean success = false;
        java.util.Date beginDate = new java.util.Date();
        java.util.Date endDate = (java.util.Date) beginDate.clone();
        endDate.setSeconds(endDate.getSeconds() + timeout);
        while (!success) {
            beginDate = new java.util.Date();
            if (beginDate.after(endDate)) {
                returnObject.put("error", "the operation timed out");
                //out.println(returnObject.toString(5));
                return returnObject;
            }
            String string = new String();
            int count = 0;
            while (reader.read() != (char) (termChar)) {
                if (count > 5000) {
                    break;
                }
                count++;
            }
            if (count > 5000) {
                returnObject.put("error",
                        "termchar was not found in the stream.  are you sure the scale is set up correctly?");
                //out.println(returnObject.toString(5));
                return returnObject;
            }
            for (int i = 0; i < numChars; i++) {
                string += (char) (reader.read());
            }
            //get negative marker also
            String weight = string.substring(weightBeginPos - 1, weightEndPos);
            String status = string.substring(statusBeginPos - 1, statusEndPos);
            String uom = string.substring(9, 11);
            System.out.println("weight: '" + weight + "'");
            System.out.println("status: '" + status + "'");
            System.out.println("uom   : '" + uom + "'");

            if (string.contains(overcapacity)) {
                returnObject.put("error", "Over Capacity!");
                return returnObject;
            } else {
                System.out.println("extracting weight value");
                returnObject.put("weight", new Integer(weight).toString());
                System.out.println("checking motion");
                if (status.charAt(0) == ((char) (normalChar))) {
                    returnObject.put("motion", false);
                } else if (status.charAt(0) == ((char) (motionChar))) {
                    returnObject.put("motion", true);
                } else {
                    returnObject.put("error", "Invalid Motion Char!\n(check web service settings)");
                }
                System.out.println("checking uom");
                if (uom.equals("LB")) {
                    returnObject.put("uom", "lbs");
                } else if (uom.equals("KG")) {
                    returnObject.put("uom", "kg");
                } else {
                    //unknown weight type, no cause for error here.
                }
            }
            System.out.println("sending resultant json");
            //out.println(returnObject.toString(5));
            success = true;
        }
    } catch (Exception e) {
        System.out.println("ERROR");
        System.out.println("ERROR: could not connect to scale: " + e.toString());
        try {
            returnObject.put("error", "could not connect to scale: " + e.toString());
            return returnObject;
            //out.println(returnObject.toString(5));
        } catch (Exception je) {
            //out.println("parser error?");
            returnObject.put("error", je.toString());
            return returnObject;
        }
    } finally {
        try {
            connection.close();
        } catch (Exception e) {
            //don't care at this point.
        }
        return returnObject;
    }
    //   }
    //};

    //socketThread.start();
}

From source file:com.lfv.lanzius.server.LanziusServer.java

private void groupRemoteControlListener(final int port) {
    new Thread("RemoteControlThread") {
        public void run() {
            try {
                ServerSocket serverSocket = new ServerSocket(port);
                Socket socket = null;
                boolean listening = true;
                String inputLine;
                while (listening) {
                    socket = serverSocket.accept();
                    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    inputLine = in.readLine();
                    log.debug("Remote control thread received: " + inputLine);
                    try {
                        String arglist[];
                        arglist = inputLine.split(" ");
                        String command = arglist[0];

                        if (command.equals("play")) {
                            String newtime;
                            String comment;

                            if (arglist.length >= 2)
                                newtime = arglist[1];
                            else
                                newtime = null;
                            menuChoiceGroupStart(1, false, newtime);
                            if (arglist.length >= 3)
                                comment = arglist[2];
                            else
                                comment = null;

                            if (comment != null) {
                                ServerLogger logger = loggerMap.get(1);
                                if (logger != null) {
                                    logger.print(comment);
                                }//from ww w. j  a va 2  s .co  m
                            }
                        } else if (command.equals("stop")) {
                            menuChoiceGroupStop(1, false);
                        } else if (command.equals("pause")) {
                            String comment;
                            if (arglist.length >= 2)
                                comment = arglist[1];
                            else
                                comment = null;
                            if (comment != null) {
                                ServerLogger logger = loggerMap.get(1);
                                if (logger != null) {
                                    logger.print(comment);
                                }
                            }
                            menuChoiceGroupPause(1);
                        } else if (inputLine.startsWith("logpath")) {
                            String newlogPath;
                            newlogPath = inputLine.substring(inputLine.indexOf(' ') + 1);
                            ServerLogger logger = loggerMap.get(1);
                            if (logger != null) {
                                log.debug("ServerLogger.logpath=" + logger.getLogPath() + " new path="
                                        + newlogPath);
                                if (newlogPath != logger.getLogPath()) {
                                    log.debug("ServerLogger.logpath changed!!!!");

                                    loggerMap.remove(1);
                                    logger.print("GROUP STOP id[1]");
                                    logger.close();
                                    ServerLogger newlogger = new ServerLogger(1, newlogPath);
                                    loggerMap.put(1, newlogger);
                                    newlogger.print("GROUP START id[1]");
                                }
                            } else {
                                log.debug("No active logger for group 1");
                            }

                            if ((logPath != null) && (!(newlogPath.equals(logPath)))) {
                                log.debug("logPath changed, stopping Groups");
                            }
                            logPath = newlogPath;
                            log.debug("logPath set to " + logPath);
                        }
                    } catch (Exception e) {
                        log.debug("Remote control action failed");
                    }
                    socket.close();
                }
                serverSocket.close();
            } catch (IOException e) {
                log.error("Failed to start Remote Control listener thread!");
                log.error(e.getMessage());
            }
        }
    }.start();
    log.info("Group remote control listening on port " + port + ".");
}

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  ww  w  .  j a  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.msopentech.thali.utilities.universal.HttpKeySocksProxyClientConnOperator.java

@Override
public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local,
        final HttpContext context, final HttpParams params) throws IOException {
    Socket socket = null;
    Socket sslSocket = null;/*from  w  w  w .java 2s . com*/
    try {
        if (conn == null || target == null || params == null) {
            throw new IllegalArgumentException("Required argument may not be null");
        }
        if (conn.isOpen()) {
            throw new IllegalStateException("Connection must not be open");
        }

        // The original NetCipher code uses a SchemeSocketFactory class that isn't supported by the version
        // of Apache that ships standard with Android. It also doesn't support the layered socket factory
        // interface either. We work around this later on but for now we just get our HttpKeySSLSocketFactory
        Scheme scheme = schemeRegistry.getScheme(target.getSchemeName());
        HttpKeySSLSocketFactory httpKeySSLSocketFactory = (HttpKeySSLSocketFactory) scheme.getSocketFactory();

        int port = scheme.resolvePort(target.getPort());
        String host = target.getHostName();

        // Perform explicit SOCKS4a connection request. SOCKS4a supports remote host name resolution
        // (i.e., Tor resolves the hostname, which may be an onion address).
        // The Android (Apache Harmony) Socket class appears to support only SOCKS4 and throws an
        // exception on an address created using INetAddress.createUnresolved() -- so the typical
        // technique for using Java SOCKS4a/5 doesn't appear to work on Android:
        // https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/net/PlainSocketImpl.java
        // See also: http://www.mit.edu/~foley/TinFoil/src/tinfoil/TorLib.java, for a similar implementation

        // From http://en.wikipedia.org/wiki/SOCKS#SOCKS4a:
        //
        // field 1: SOCKS version number, 1 byte, must be 0x04 for this version
        // field 2: command code, 1 byte:
        //     0x01 = establish a TCP/IP stream connection
        //     0x02 = establish a TCP/IP port binding
        // field 3: network byte order port number, 2 bytes
        // field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00
        // field 5: the user ID string, variable length, terminated with a null (0x00)
        // field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00)

        socket = new Socket();
        conn.opening(socket, target);
        socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        socket.connect(proxy.address(), CONNECT_TIMEOUT_MILLISECONDS);

        DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
        outputStream.write((byte) 0x04);
        outputStream.write((byte) 0x01);
        outputStream.writeShort((short) port);
        outputStream.writeInt(0x01);
        outputStream.write((byte) 0x00);
        outputStream.write(host.getBytes());
        outputStream.write((byte) 0x00);

        DataInputStream inputStream = new DataInputStream(socket.getInputStream());
        if (inputStream.readByte() != (byte) 0x00 || inputStream.readByte() != (byte) 0x5a) {
            throw new IOException("SOCKS4a connect failed");
        }
        inputStream.readShort();
        inputStream.readInt();

        // In the NetCipher code we cast to SchemeLayeredSocketFactory and call createLayeredSocket which amongst
        // other things takes 'params' as an argument. But none of this is supported in Android. When I looked in
        // Java at what createLayeredSocket was actually doing it was just calling createSocket with exactly the
        // arguments used below (it ignored params completely). So we should be good.
        sslSocket = ((HttpKeySSLSocketFactory) httpKeySSLSocketFactory).createSocket(socket, host, port, true);
        conn.opening(sslSocket, target);
        sslSocket.setSoTimeout(READ_TIMEOUT_MILLISECONDS);
        prepareSocket(sslSocket, context, params);
        conn.openCompleted(httpKeySSLSocketFactory.isSecure(sslSocket), params);
        // TODO: clarify which connection throws java.net.SocketTimeoutException?
    } catch (IOException e) {
        try {
            if (sslSocket != null) {
                sslSocket.close();
            }
            if (socket != null) {
                socket.close();
            }
        } catch (IOException ioe) {
        }
        throw e;
    }
}