Example usage for java.nio.channels SelectionKey isValid

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

Introduction

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

Prototype

public abstract boolean isValid();

Source Link

Document

Tells whether or not this key is valid.

Usage

From source file:org.apache.nifi.processor.util.listen.dispatcher.DatagramChannelDispatcher.java

@Override
public void run() {
    final ByteBuffer buffer = bufferPool.poll();
    while (!stopped) {
        try {//w ww .ja  v  a2 s .c o  m
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    DatagramChannel channel = (DatagramChannel) key.channel();
                    SocketAddress socketAddress;
                    buffer.clear();
                    while (!stopped && (socketAddress = channel.receive(buffer)) != null) {
                        String sender = "";
                        if (socketAddress instanceof InetSocketAddress) {
                            sender = ((InetSocketAddress) socketAddress).getAddress().toString();
                        }

                        // create a byte array from the buffer
                        buffer.flip();
                        byte bytes[] = new byte[buffer.limit()];
                        buffer.get(bytes, 0, buffer.limit());

                        final Map<String, String> metadata = EventFactoryUtil.createMapWithSender(sender);
                        final E event = eventFactory.create(bytes, metadata, null);
                        events.offer(event);

                        buffer.clear();
                    }
                }
            }
        } catch (InterruptedException e) {
            stopped = true;
            Thread.currentThread().interrupt();
        } catch (IOException e) {
            logger.error("Error reading from DatagramChannel", e);
        }
    }

    if (buffer != null) {
        try {
            bufferPool.put(buffer);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public void run() {
    while (!stopped) {
        try {/*from w w  w. j  av a 2s  .  c  o m*/
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // Handle new connections coming in
                        final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        final SocketChannel socketChannel = channel.accept();
                        // Check for available connections
                        if (currentConnections.incrementAndGet() > maxConnections) {
                            currentConnections.decrementAndGet();
                            logger.warn("Rejecting connection from {} because max connections has been met",
                                    new Object[] { socketChannel.getRemoteAddress().toString() });
                            IOUtils.closeQuietly(socketChannel);
                            continue;
                        }
                        logger.debug("Accepted incoming connection from {}",
                                new Object[] { socketChannel.getRemoteAddress().toString() });
                        // Set socket to non-blocking, and register with selector
                        socketChannel.configureBlocking(false);
                        SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);

                        // Prepare the byte buffer for the reads, clear it out
                        ByteBuffer buffer = bufferPool.poll();
                        buffer.clear();
                        buffer.mark();

                        // If we have an SSLContext then create an SSLEngine for the channel
                        SSLSocketChannel sslSocketChannel = null;
                        if (sslContext != null) {
                            final SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(false);

                            switch (clientAuth) {
                            case REQUIRED:
                                sslEngine.setNeedClientAuth(true);
                                break;
                            case WANT:
                                sslEngine.setWantClientAuth(true);
                                break;
                            case NONE:
                                sslEngine.setNeedClientAuth(false);
                                sslEngine.setWantClientAuth(false);
                                break;
                            }

                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }

                        // Attach the buffer and SSLSocketChannel to the key
                        SocketChannelAttachment attachment = new SocketChannelAttachment(buffer,
                                sslSocketChannel);
                        readKey.attach(attachment);
                    } else if (key.isReadable()) {
                        // Clear out the operations the select is interested in until done reading
                        key.interestOps(0);
                        // Create a handler based on the protocol and whether an SSLEngine was provided or not
                        final Runnable handler;
                        if (sslContext != null) {
                            handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events,
                                    logger);
                        } else {
                            handler = handlerFactory.createHandler(key, this, charset, eventFactory, events,
                                    logger);
                        }

                        // run the handler
                        executor.execute(handler);
                    }
                }
            }
            // Add back all idle sockets to the select
            SelectionKey key;
            while ((key = keyQueue.poll()) != null) {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            logger.error("Error accepting connection from SocketChannel", e);
        }
    }
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public int getPort() {
    // Return the port for the key listening for accepts
    for (SelectionKey key : selector.keys()) {
        if (key.isValid()) {
            final Channel channel = key.channel();
            if (channel instanceof ServerSocketChannel) {
                return ((ServerSocketChannel) channel).socket().getLocalPort();
            }/*from w  ww . j a  v  a2  s .c  o  m*/
        }
    }
    return 0;
}

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

public void run() {
    SocketChannel socketChannel = null;

    try {/*w  w w .  j av a 2s  .  c om*/
        if (selector.select(5000) > 0) {
            Iterator<SelectionKey> iter = selector.selectedKeys().iterator();

            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                if (key.isValid() && key.isAcceptable()) {
                    socketChannel = ssc.accept();

                    transfer(channelList, socketChannel);
                }

                iter.remove();
            }
        } else {
            LOG.warn("No responses from client asking to transfter file for 5 sec");
        }
    } catch (IOException e) {
        LOG.warn("transfering file is fail", e);
    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.socket().close();
                socketChannel.close();
            } catch (IOException e) { /* ignored */
            }
        }
    }

    LOG.debug("File transfer thread is done");
}

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();/*from   w  ww  . ja  v  a 2  s.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 /*from   ww w. ja va2  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 w w.  j ava 2s . 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   www  .  ja v  a2s  .co  m
        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;/*www . j  a v  a  2  s .  co  m*/
    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);
            }
        }
    }
}

From source file:org.gcaldaemon.core.ldap.LDAPListener.java

public final void run() {
    log.info("LDAP server started successfully.");

    // Create variables
    SelectionKey key, newKey;
    SocketChannel channel;/*from   w w  w .  j  a v  a  2 s .com*/
    Socket socket = null;
    Iterator keys;
    int n;

    // Server loop
    for (;;) {
        try {

            // Select sockets
            try {
                socket = null;
                n = selector.select();
            } catch (NullPointerException closedError) {

                // Ignore Selector bug - client socket closed
                if (log.isDebugEnabled()) {
                    log.debug("Socket closed.", closedError);
                }
                continue;
            } catch (ClosedSelectorException interrupt) {
                break;
            } catch (Exception selectError) {

                // Unknown exception - stop server
                log.warn("Unable to select sockets!", selectError);
                break;
            }

            if (n != 0) {

                // Get an iterator over the set of selected keys
                keys = selector.selectedKeys().iterator();
                if (keys == null) {
                    continue;
                }

                // Look at each key in the selected set
                while (keys.hasNext()) {
                    key = (SelectionKey) keys.next();
                    keys.remove();

                    // Nothing to do
                    if (key == null) {
                        continue;
                    }

                    // Check key status
                    if (key.isValid()) {

                        // Accept new incoming connection
                        if (key.isAcceptable()) {
                            channel = serverChannel.accept();
                            if (channel != null) {

                                // Register new socket connection
                                socket = channel.socket();
                                channel.configureBlocking(false);
                                newKey = channel.register(selector, SelectionKey.OP_READ);
                                processAccept(newKey);
                            }
                        } else {
                            if (key.isReadable()) {

                                // Read from socket connection
                                socket = ((SocketChannel) key.channel()).socket();
                                processRead(key);
                            } else {

                                // Write to socket connection
                                if (key.isWritable()) {
                                    socket = ((SocketChannel) key.channel()).socket();
                                    processWrite(key);
                                }
                            }
                        }
                    }
                }
            }
        } catch (InterruptedException interrupt) {
            closeSocket(socket);
            break;
        } catch (IOException socketClosed) {
            closeSocket(socket);
            continue;
        } catch (Exception processingException) {
            closeSocket(socket);
            log.warn(processingException.getMessage(), processingException);
        }
    }
    log.info("LDAP server stopped.");
}