Example usage for java.nio.channels SelectionKey isWritable

List of usage examples for java.nio.channels SelectionKey isWritable

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey isWritable.

Prototype

public final boolean isWritable() 

Source Link

Document

Tests whether this key's channel is ready for writing.

Usage

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }//from  w  w w  .  java  2  s  .  c  om
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

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 www  . jav  a2 s.co  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.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;/*  w  ww  . j a va 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:net.ymate.platform.serv.nio.support.NioEventProcessor.java

@Override
public void run() {
    try {//  w  w  w.j av  a2s  .  com
        while (__flag) {
            __selector.select(5 * DateTimeUtils.SECOND);
            __doRegisterEvent();
            Iterator<SelectionKey> _keyIterator = __selector.selectedKeys().iterator();
            while (_keyIterator.hasNext()) {
                SelectionKey _selectionKey = _keyIterator.next();
                _keyIterator.remove();
                if (_selectionKey.isValid()) {
                    Object _attachment = _selectionKey.attachment();
                    if (_attachment instanceof INioSession) {
                        ((INioSession) _attachment).touch();
                    }
                    try {
                        if (_selectionKey.isAcceptable()) {
                            __doAcceptEvent(_selectionKey);
                        } else if (_selectionKey.isConnectable()) {
                            __doConnectEvent(_selectionKey);
                        } else if (_selectionKey.isReadable()) {
                            __doReadEvent(_selectionKey);
                        } else if (_selectionKey.isWritable()) {
                            __doWriteEvent(_selectionKey);
                        }
                    } catch (Throwable e) {
                        __doExceptionEvent(_selectionKey, e);
                    }
                }
            }
            __doClosedEvent();
        }
    } catch (IOException e) {
        if (__flag) {
            _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e));
        } else {
            _LOG.debug(e.getMessage(), RuntimeUtils.unwrapThrow(e));
        }
    }
}

From source file:org.apache.htrace.impl.PackedBufferManager.java

/**
 * Send the provided ByteBuffer objects.
 *
 * We use non-blocking I/O because Java does not provide write timeouts.
 * Without a write timeout, the socket could get hung and we'd never recover.
 * We also use the GatheringByteChannel#write method which calls the pread()
 * system call under the covers.  This ensures that even if TCP_NODELAY is on,
 * we send the minimal number of packets.
 *//*from w  w  w .  j a  v a  2 s .  c om*/
private void doSend(SelectionKey sockKey, ByteBuffer[] bufs) throws IOException {
    long totalWritten = 0;
    sockKey.interestOps(SelectionKey.OP_WRITE);
    SocketChannel sock = (SocketChannel) sockKey.attachment();
    long startMs = TimeUtil.nowMs();
    long remainingMs = conf.ioTimeoutMs;
    while (true) {
        selector.select(remainingMs);
        int firstBuf = 0;
        for (SelectionKey key : selector.selectedKeys()) {
            if (key.isWritable()) {
                long written = sock.write(bufs, firstBuf, bufs.length - firstBuf);
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Sent " + written + " bytes to " + conf.endpointStr);
                }
                totalWritten += written;
            }
        }
        while (true) {
            if (firstBuf == bufs.length) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Finished sending " + totalWritten + " bytes to " + conf.endpointStr);
                }
                return;
            }
            if (bufs[firstBuf].remaining() > 0) {
                break;
            }
            firstBuf++;
        }
        remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs);
        if (remainingMs == 0) {
            throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after "
                    + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms.");
        }
    }
}

From source file:org.cloudata.core.commitlog.WorkerPool.java

private void dispatchSelectedKeys() {
    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();

    while (iter.hasNext()) {
        SelectionKey key = iter.next();
        iter.remove();//w ww .  jav  a  2s . c  om

        if (key.isValid()) {
            if (key.isReadable()) {
                handleData(key);
            } else if (key.isConnectable()) {
                handleConnection(key);
            } else if (key.isWritable()) {
                handleWrite(key);
            }
        }
    }
}

From source file:org.commoncrawl.io.internal.NIOSocketSelector.java

/** poll method  - poll the registered socket for events and potentially block for IO for the 
 *  specified timeout value /* www  .  j a v  a  2  s .  c  o  m*/
 *  
 *  @param timeoutValue - amount of time in MS to wait (block) for IO 
 *  
 *  */
@SuppressWarnings("unchecked")
public int poll(long timeoutValue, TimeUsageDetail timeUsageDetailOut) throws IOException {

    long timeStart = System.currentTimeMillis();

    if (_lastPollTime != -1 && (timeStart - _lastPollTime) >= 30000) {
        LOG.error("POLL Delta Too Long:" + (timeStart - _lastPollTime));
    }
    _lastPollTime = timeStart;

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime = 0;
        timeUsageDetailOut.unblockedTime = 0;
    }

    if (_selector == null || !_selector.isOpen()) {
        IOException e = new IOException("Selector NULL or Selector is Not Open!");
        LOG.error(e);
        throw e;
    }

    processPendingRegistrations();
    long timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (timeEnd - timeStart);
    }

    /*
    if (timeoutWatchSet.size() != 0) { 
      // We have a timeout pending, so calculate the time until then and select appropriately
      long nextTimeout = timeoutWatchSet.first().getTimeoutTimestamp();
      long selectTime = nextTimeout - System.currentTimeMillis();
      if (selectTime < timeoutValue) {
        timeoutValue = Math.max(selectTime,0);
      }
    }
    */
    timeStart = System.currentTimeMillis();

    int count = 0;
    if (timeoutValue <= 0) {
        count = _selector.selectNow();
    } else {
        if (timeoutValue == Long.MAX_VALUE)
            timeoutValue = 0;
        count = _selector.select(timeoutValue);
    }
    timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime += (timeEnd - timeStart);
    }

    long unblockedTimeStart = System.currentTimeMillis();

    // if (count != 0 ) { 

    Set<SelectionKey> selectionSet = _selector.selectedKeys();

    for (Iterator<SelectionKey> i = selectionSet.iterator(); i.hasNext();) {

        SelectionKey selectionKey = i.next();

        i.remove();

        if (selectionKey.isValid()) {

            Object attachment = selectionKey.attachment();
            /*
            if (attachment instanceof TAsyncMethodCall) {
              transitionThriftMethod((TAsyncMethodCall)attachment,selectionKey);
            }
            */
            if (attachment instanceof NIOSocket) {
                NIOSocket theSocket = (NIOSocket) selectionKey.attachment();

                if (theSocket != null && theSocket.getListener() != null) {

                    // reset interest ops 
                    selectionKey.interestOps(0);

                    // process events in key ... 
                    if (selectionKey.isConnectable()) {

                        boolean connected = false;
                        Exception disconnectException = null;
                        try {
                            if (((NIOClientSocket) theSocket).finishConnect()) {
                                connected = true;
                                // log it ... 
                                // LOG.info("Connected to:"+((NIOClientSocket)theSocket).getSocketAddress());
                                // reset the selection key's ops.. otherwise, select keeps returning on an already connected socket (since we have registered for CONNECT)
                                System.out.println(
                                        "Connected to:" + ((NIOClientSocket) theSocket).getSocketAddress());
                                timeStart = System.currentTimeMillis();
                                ((NIOClientSocketListener) theSocket.getListener())
                                        .Connected((NIOClientSocket) theSocket);
                                if (timeUsageDetailOut != null) {
                                    timeUsageDetailOut.timeInConnectedEvt += System.currentTimeMillis()
                                            - timeStart;
                                }
                            } else {
                                //LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() + " - finishConnect returned false");
                                theSocket.close();
                            }
                        } catch (IOException e) {
                            //LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() + " with Exception:"+e);
                            theSocket.close();
                            disconnectException = e;
                        } catch (RuntimeException e) {
                            LOG.error("Caught Runtime Exception in Connected Event:"
                                    + StringUtils.stringifyException(e));
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Excepted((NIOClientSocket) theSocket, e);
                            theSocket.close();
                            disconnectException = e;
                            //KILL THE SERVER 
                            //throw e;
                        }

                        // if we were unable to properly establish the connection, trigger the Disconnected notification ... 
                        if (!connected) {
                            //LOG.error("Failed to Complete Connection in Finish Connect- Calling Disconnected");
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Disconnected((NIOClientSocket) theSocket, disconnectException);
                            // continue to the next socket ... 
                            continue;
                        }
                    }

                    // now always set the socket to readable state ... 
                    if ((theSocket instanceof NIOClientSocket) && selectionKey.isValid()) {
                        selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ);
                    }

                    if (selectionKey.isValid() && selectionKey.isReadable()) {
                        int bytesRead = -1;

                        try {

                            timeStart = System.currentTimeMillis();
                            // track the number of actual bytes read in the callback ... 
                            bytesRead = ((NIOClientSocketListener) theSocket.getListener())
                                    .Readable((NIOClientSocket) theSocket);
                            //System.out.println("Readable Took:" + (System.currentTimeMillis() - timeStart));
                            if (timeUsageDetailOut != null) {
                                timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart;
                            }

                            if (bytesRead == -1) {
                                // log it ... 
                                // LOG.error("Abnormal Disconnect Detected on Socket:"+ ((NIOClientSocket)theSocket).getSocketAddress());
                                // trigger a disconnect event ...
                                ((NIOClientSocketListener) theSocket.getListener())
                                        .Disconnected((NIOClientSocket) theSocket, null);
                                // close the socket ... 
                                theSocket.close();
                            }
                        } catch (RuntimeException e) {
                            LOG.error("Caught Runtime Exception in Readable Event:"
                                    + StringUtils.stringifyException(e));
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Excepted((NIOClientSocket) theSocket, e);
                            theSocket.close();
                            //KILL THE SERVER 
                            // throw e;
                        }
                        // if bytesRead == -1 then this means that the underlying connection has gone bad ... 
                    }

                    if (selectionKey.isValid() && selectionKey.isWritable()) {
                        try {

                            timeStart = System.currentTimeMillis();
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Writeable((NIOClientSocket) theSocket);
                            // System.out.println("Writable Took:" + (System.currentTimeMillis() - timeStart));
                            if (timeUsageDetailOut != null) {
                                timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart;
                            }
                        } catch (RuntimeException e) {
                            LOG.error("Caught Runtime Exception in Readable Event:"
                                    + StringUtils.stringifyException(e));
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Excepted((NIOClientSocket) theSocket, e);
                            theSocket.close();
                            //KILL THE SERVER ? 
                            //throw e;
                        }

                    }

                    if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                        ((NIOServerSocket) theSocket).acceptable();
                        // re-register for accept on this socket 
                        selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_ACCEPT);
                    }
                }
            }
            // exernally managed socket (thrift client socket)
            else if (attachment instanceof NIOClientSocketListener) {
                NIOClientSocketListener listener = (NIOClientSocketListener) attachment;
                // reset interest ops 
                selectionKey.interestOps(0);
                // now always set the socket to readable state ... 
                selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ);

                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    int bytesRead = -1;

                    try {

                        timeStart = System.currentTimeMillis();
                        // track the number of actual bytes read in the callback ... 
                        bytesRead = listener.Readable(null);
                        //System.out.println("Readable Took:" + (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart;
                        }

                        if (bytesRead == -1) {
                            // log it ... 
                            // LOG.error("Abnormal Disconnect Detected on Socket:"+ ((NIOClientSocket)theSocket).getSocketAddress());
                            // trigger a disconnect event ...
                            listener.Disconnected(null, null);
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        listener.Excepted(null, e);
                    }
                    // if bytesRead == -1 then this means that the underlying connection has gone bad ... 
                }

                if (selectionKey.isValid() && selectionKey.isWritable()) {
                    try {

                        timeStart = System.currentTimeMillis();
                        listener.Writeable(null);
                        // System.out.println("Writable Took:" + (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart;
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        listener.Excepted(null, e);
                    }
                }
            }
        } else {
            LOG.error("Invalid Socket Detected. Calling Disconnect");
            NIOSocket theSocket = (NIOSocket) selectionKey.attachment();
            if (theSocket != null && theSocket.getListener() != null) {
                theSocket.getListener().Disconnected(theSocket, null);
            }
        }
    }
    //timeoutThriftMethods();
    //startPendingThriftMethods();      

    long unblockedTimeEnd = System.currentTimeMillis();
    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (unblockedTimeEnd - unblockedTimeStart);
    }

    // }
    return count;
}

From source file:org.commoncrawl.io.NIOSocketSelector.java

/**
 * poll method - poll the registered socket for events and potentially block
 * for IO for the specified timeout value
 * /*w ww  .j  av  a  2  s  .  c  o m*/
 * @param timeoutValue
 *          - amount of time in MS to wait (block) for IO
 * 
 * */
public int poll(long timeoutValue, TimeUsageDetail timeUsageDetailOut) throws IOException {

    long timeStart = System.currentTimeMillis();

    if (_lastPollTime != -1 && (timeStart - _lastPollTime) >= 30000) {
        LOG.error("POLL Delta Too Long:" + (timeStart - _lastPollTime));
    }
    _lastPollTime = timeStart;

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime = 0;
        timeUsageDetailOut.unblockedTime = 0;
    }

    if (_selector == null || !_selector.isOpen()) {
        IOException e = new IOException("Selector NULL or Selector is Not Open!");
        LOG.error(e);
        throw e;
    }

    processPendingRegistrations();
    long timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (timeEnd - timeStart);
    }

    timeStart = System.currentTimeMillis();
    int count = _selector.select(timeoutValue);
    timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime += (timeEnd - timeStart);
    }

    long unblockedTimeStart = System.currentTimeMillis();

    // if (count != 0 ) {

    Set<SelectionKey> selectionSet = _selector.selectedKeys();

    for (Iterator<SelectionKey> i = selectionSet.iterator(); i.hasNext();) {

        SelectionKey selectionKey = i.next();

        i.remove();

        if (selectionKey.isValid()) {

            NIOSocket theSocket = (NIOSocket) selectionKey.attachment();

            if (theSocket != null && theSocket.getListener() != null) {

                // reset interest ops
                selectionKey.interestOps(0);

                // process events in key ...
                if (selectionKey.isConnectable()) {

                    boolean connected = false;
                    Exception disconnectException = null;
                    try {
                        if (((NIOClientSocket) theSocket).finishConnect()) {
                            connected = true;
                            // log it ...
                            // LOG.info("Connected to:"+((NIOClientSocket)theSocket).getSocketAddress());
                            // reset the selection key's ops.. otherwise, select keeps
                            // returning on an already connected socket (since we have
                            // registered for CONNECT)
                            System.out.println(
                                    "Connected to:" + ((NIOClientSocket) theSocket).getSocketAddress());
                            timeStart = System.currentTimeMillis();
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Connected((NIOClientSocket) theSocket);
                            if (timeUsageDetailOut != null) {
                                timeUsageDetailOut.timeInConnectedEvt += System.currentTimeMillis() - timeStart;
                            }
                        } else {
                            // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress()
                            // + " - finishConnect returned false");
                            theSocket.close();
                        }
                    } catch (IOException e) {
                        // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress()
                        // + " with Exception:"+e);
                        theSocket.close();
                        disconnectException = e;
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Connected Event:"
                                + StringUtils.stringifyException(e));
                        ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e);
                        theSocket.close();
                        disconnectException = e;
                        // KILL THE SERVER
                        throw e;
                    }

                    // if we were unable to properly establish the connection, trigger
                    // the Disconnected notification ...
                    if (!connected) {
                        // LOG.error("Failed to Complete Connection in Finish Connect- Calling Disconnected");
                        ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket,
                                disconnectException);
                        // continue to the next socket ...
                        continue;
                    }
                }

                // now always set the socket to readable state ...
                if ((theSocket instanceof NIOClientSocket) && selectionKey.isValid()) {
                    selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ);
                }

                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    int bytesRead = -1;

                    try {

                        timeStart = System.currentTimeMillis();
                        // track the number of actual bytes read in the callback ...
                        bytesRead = ((NIOClientSocketListener) theSocket.getListener())
                                .Readable((NIOClientSocket) theSocket);
                        // System.out.println("Readable Took:" +
                        // (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart;
                        }

                        if (bytesRead == -1) {
                            // log it ...
                            // LOG.error("Abnormal Disconnect Detected on Socket:"+
                            // ((NIOClientSocket)theSocket).getSocketAddress());
                            // trigger a disconnect event ...
                            ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket, null);
                            // close the socket ...
                            theSocket.close();
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e);
                        theSocket.close();
                        // KILL THE SERVER
                        throw e;
                    }
                    // if bytesRead == -1 then this means that the underlying connection
                    // has gone bad ...
                }

                if (selectionKey.isValid() && selectionKey.isWritable()) {
                    try {

                        timeStart = System.currentTimeMillis();
                        ((NIOClientSocketListener) theSocket.getListener())
                                .Writeable((NIOClientSocket) theSocket);
                        // System.out.println("Writable Took:" +
                        // (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart;
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e);
                        theSocket.close();
                        // KILL THE SERVER
                        throw e;
                    }

                }

                if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                    ((NIOServerSocket) theSocket).acceptable();
                    // re-register for accept on this socket
                    selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_ACCEPT);
                }
            }
        } else {
            LOG.error("Invalid Socket Detected. Calling Disconnect");
            NIOSocket theSocket = (NIOSocket) selectionKey.attachment();
            if (theSocket != null && theSocket.getListener() != null) {
                theSocket.getListener().Disconnected(theSocket, null);
            }
        }
    }

    long unblockedTimeEnd = System.currentTimeMillis();
    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (unblockedTimeEnd - unblockedTimeStart);
    }

    // }
    return count;
}

From source file:org.eclipse.smarthome.binding.lifx.internal.LifxLightDiscovery.java

private boolean sendPacket(Packet packet, InetSocketAddress address, SelectionKey selectedKey) {

    boolean result = false;

    try {/*from w w  w  . j  a  v  a  2 s.  c  om*/
        boolean sent = false;

        while (!sent) {
            try {
                selector.selectNow();
            } catch (IOException e) {
                logger.error("An exception occurred while selecting: {}", e.getMessage());
            }

            Set<SelectionKey> selectedKeys = selector.selectedKeys();

            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();

                if (key.isValid() && key.isWritable() && key.equals(selectedKey)) {
                    SelectableChannel channel = key.channel();
                    try {
                        if (channel instanceof DatagramChannel) {
                            logger.trace(
                                    "Discovery : Sending packet type '{}' from '{}' to '{}' for '{}' with sequence '{}' and source '{}'",
                                    new Object[] { packet.getClass().getSimpleName(),
                                            ((InetSocketAddress) ((DatagramChannel) channel).getLocalAddress())
                                                    .toString(),
                                            address.toString(), packet.getTarget().getHex(),
                                            packet.getSequence(), Long.toString(packet.getSource(), 16) });
                            ((DatagramChannel) channel).send(packet.bytes(), address);

                            sent = true;
                            result = true;
                        } else if (channel instanceof SocketChannel) {
                            ((SocketChannel) channel).write(packet.bytes());
                        }
                    } catch (Exception e) {
                        logger.error("An exception occurred while writing data : '{}'", e.getMessage());
                    }
                }
            }
        }

    } catch (Exception e) {
        logger.error("An exception occurred while communicating with the light : '{}'", e.getMessage());
    }

    return result;
}

From source file:org.eclipsetrader.directa.internal.core.BrokerConnector.java

@Override
public void run() {
    Selector socketSelector;// w w  w. j  a  v a2 s  . c om
    ByteBuffer dst = ByteBuffer.wrap(new byte[2048]);
    List<Position> positions = new ArrayList<Position>();

    try {
        // Create a non-blocking socket channel
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        socketChannel.socket().setReceiveBufferSize(32768);
        socketChannel.socket().setSoLinger(true, 1);
        socketChannel.socket().setSoTimeout(0x15f90);
        socketChannel.socket().setReuseAddress(true);

        // Kick off connection establishment
        socketChannel.connect(new InetSocketAddress(server, port));

        // Create a new selector
        socketSelector = SelectorProvider.provider().openSelector();

        // Register the server socket channel, indicating an interest in
        // accepting new connections
        socketChannel.register(socketSelector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to orders monitor", //$NON-NLS-1$
                e);
        Activator.log(status);
        return;
    }

    for (;;) {
        try {
            if (socketSelector.select(30 * 1000) == 0) {
                logger.trace(">" + HEARTBEAT); //$NON-NLS-1$
                socketChannel.write(ByteBuffer.wrap(new String(HEARTBEAT + "\r\n").getBytes())); //$NON-NLS-1$
            }
        } catch (Exception e) {
            break;
        }

        // Iterate over the set of keys for which events are available
        Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
            SelectionKey key = selectedKeys.next();
            selectedKeys.remove();

            if (!key.isValid()) {
                continue;
            }

            try {
                // Check what event is available and deal with it
                if (key.isConnectable()) {
                    // Finish the connection. If the connection operation failed
                    // this will raise an IOException.
                    try {
                        socketChannel.finishConnect();
                    } catch (IOException e) {
                        // Cancel the channel's registration with our selector
                        key.cancel();
                        return;
                    }

                    // Register an interest in writing on this channel
                    key.interestOps(SelectionKey.OP_WRITE);
                }
                if (key.isWritable()) {
                    logger.trace(">" + LOGIN + WebConnector.getInstance().getUser()); //$NON-NLS-1$
                    socketChannel.write(ByteBuffer.wrap(
                            new String(LOGIN + WebConnector.getInstance().getUser() + "\r\n").getBytes())); //$NON-NLS-1$

                    // Register an interest in reading on this channel
                    key.interestOps(SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    dst.clear();
                    int readed = socketChannel.read(dst);
                    if (readed > 0) {
                        String[] s = new String(dst.array(), 0, readed).split("\r\n"); //$NON-NLS-1$
                        for (int i = 0; i < s.length; i++) {
                            logger.trace("<" + s[i]); //$NON-NLS-1$

                            if (s[i].endsWith(";" + WebConnector.getInstance().getUser() + ";")) { //$NON-NLS-1$ //$NON-NLS-2$
                                logger.trace(">" + UNKNOWN70); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN70 + "\r\n").getBytes())); //$NON-NLS-1$
                                logger.trace(">" + UNKNOWN55); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN55 + "\r\n").getBytes())); //$NON-NLS-1$
                            }

                            if (s[i].indexOf(";6;5;") != -1 || s[i].indexOf(";8;0;") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
                                try {
                                    OrderMonitor monitor = parseOrderLine(s[i]);

                                    OrderDelta[] delta;
                                    synchronized (orders) {
                                        if (!orders.contains(monitor)) {
                                            orders.add(monitor);
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_ADDED, monitor) };
                                        } else {
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_UPDATED, monitor) };
                                        }
                                    }
                                    fireUpdateNotifications(delta);

                                    if (monitor.getFilledQuantity() != null
                                            && monitor.getAveragePrice() != null) {
                                        Account account = WebConnector.getInstance().getAccount();
                                        account.updatePosition(monitor);
                                    }
                                } catch (ParseException e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";6;0;") != -1) { //$NON-NLS-1$
                                updateStatusLine(s[i]);
                            }
                            if (s[i].indexOf(";7;0;") != -1) { //$NON-NLS-1$
                                try {
                                    positions.add(new Position(s[i]));
                                } catch (Exception e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";7;9;") != -1) { //$NON-NLS-1$
                                Account account = WebConnector.getInstance().getAccount();
                                account.setPositions(positions.toArray(new Position[positions.size()]));
                                positions.clear();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Connection error", e); //$NON-NLS-1$
                Activator.log(status);
            }
        }
    }
}