Example usage for java.nio.channels SelectionKey OP_READ

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

Introduction

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

Prototype

int OP_READ

To view the source code for java.nio.channels SelectionKey OP_READ.

Click Source Link

Document

Operation-set bit for read operations.

Usage

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Accept an icoming connection// www .  j ava2 s .co m
 * 
 * @throws IOException
 */
private void processAccept(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    ServerSocketChannel ssc = (ServerSocketChannel) sk.channel();
    SocketChannel channel = ssc.accept();

    if (channel == null)
        return;

    if (channel.isOpen() && accept(channel.socket().getInetAddress())) {

        channel.configureBlocking(false);

        DaapConnection connection = new DaapConnectionNIO(this, channel);

        SelectionKey key = channel.register(selector, SelectionKey.OP_READ, connection);

    } else {
        try {
            channel.close();
        } catch (IOException err) {
            LOG.error("SocketChannel.close()", err);
        }
    }
}

From source file:org.openhab.binding.keba.handler.KeContactHandler.java

private void establishConnection() {
    lock.lock();//from ww  w.j  a  va  2  s .  com
    try {
        if (getThing().getStatusInfo().getStatusDetail() != ThingStatusDetail.CONFIGURATION_ERROR
                && getConfig().get(IP_ADDRESS) != null && !getConfig().get(IP_ADDRESS).equals("")) {

            try {
                datagramChannel = DatagramChannel.open();
            } catch (Exception e2) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                        "An exception occurred while opening a datagram channel");
            }

            try {
                datagramChannel.configureBlocking(false);
            } catch (IOException e2) {
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                        "An exception occurred while configuring a datagram channel");
            }

            synchronized (selector) {
                selector.wakeup();
                int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
                try {
                    datagramChannelKey = datagramChannel.register(selector, interestSet);
                } catch (ClosedChannelException e1) {
                    updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                            "An exception occurred while registering a selector");
                }

                InetSocketAddress remoteAddress = new InetSocketAddress((String) getConfig().get(IP_ADDRESS),
                        REMOTE_PORT_NUMBER);

                try {
                    logger.trace("Connecting the channel for {} ", remoteAddress);
                    datagramChannel.connect(remoteAddress);

                    onConnectionResumed();

                } catch (Exception e) {
                    logger.error("An exception occurred while connecting connecting to '{}:{}' : {}",
                            new Object[] { (String) getConfig().get(IP_ADDRESS), REMOTE_PORT_NUMBER,
                                    e.getMessage() });
                    updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                            "An exception occurred while connecting");
                }
            }
        } else {
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                    getThing().getStatusInfo().getDescription());
        }
    } finally {
        lock.unlock();
    }
}

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 www . ja v a 2 s  . co 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.limewire.mojito.io.MessageDispatcherImpl.java

/** 
 * Called to indicate an interest in reading something from
 * the Network. Override this method if you need this functionality!
 *///  w  ww.j a  v a 2s .co m
private void interestRead(boolean on) {
    interest(SelectionKey.OP_READ, on);
}

From source file:com.taobao.gecko.core.nio.impl.Reactor.java

final void dispatchEvent(final Set<SelectionKey> selectedKeySet) {
    final Iterator<SelectionKey> it = selectedKeySet.iterator();
    boolean skipOpRead = false; // 
    while (it.hasNext()) {
        final SelectionKey key = it.next();
        it.remove();//from   w ww.j a  v a2 s  . c  o  m
        if (!key.isValid()) {
            if (key.attachment() != null) {
                this.controller.closeSelectionKey(key);
            } else {
                key.cancel();
            }
            continue;
        }
        try {
            if (key.isAcceptable()) {
                this.controller.onAccept(key);
                continue;
            }
            if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                // Remove write interest
                key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                this.controller.onWrite(key);
                if (!this.controller.isHandleReadWriteConcurrently()) {
                    skipOpRead = true;
                }
            }
            if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                // read
                key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
                // 
                if (!this.controller.getStatistics().isReceiveOverFlow()) {
                    // Remove read interest

                    this.controller.onRead(key);// 
                    continue;
                } else {
                    key.interestOps(key.interestOps() // 
                            | SelectionKey.OP_READ);
                }

            }
            if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
                this.controller.onConnect(key);
                continue;
            }

        } catch (final RejectedExecutionException e) {
            // 
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.notifyException(e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        } catch (final CancelledKeyException e) {
            // ignore
        } catch (final Exception e) {
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.closeSelectionKey(key);
            this.controller.notifyException(e);
            log.error("Reactor dispatch events error", e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        }
    }
}

From source file:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Notify all clients about an update of the Library
 *///from  ww  w. j  ava 2s .  com
private void processUpdate() {

    Set keys = selector.keys();
    Iterator it = keys.iterator();
    while (it.hasNext()) {
        SelectionKey sk = (SelectionKey) it.next();
        SelectableChannel channel = (SelectableChannel) sk.channel();

        if (channel instanceof SocketChannel) {

            DaapConnection connection = (DaapConnection) sk.attachment();

            if (connection.isDaapConnection()) {
                try {
                    connection.update();
                    if (sk.isValid()) {
                        try {
                            sk.interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                        } catch (CancelledKeyException err) {
                            cancel(sk);
                            LOG.error("SelectionKey.interestOps()", err);
                        }
                    }
                } catch (ClosedChannelException err) {
                    cancel(sk);
                    LOG.error("DaapConnection.update()", err);
                } catch (IOException err) {
                    cancel(sk);
                    LOG.error("DaapConnection.update()", err);
                }
            }
        }
    }
}

From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java

final void dispatchEvent(final Set<SelectionKey> selectedKeySet) {
    final Iterator<SelectionKey> it = selectedKeySet.iterator();
    boolean skipOpRead = false; // ?
    while (it.hasNext()) {
        final SelectionKey key = it.next();
        it.remove();//  w  ww .j av  a  2s . c  o  m
        if (!key.isValid()) {
            if (key.attachment() != null) {
                this.controller.closeSelectionKey(key);
            } else {
                key.cancel();
            }
            continue;
        }
        try {
            if (key.isAcceptable()) {
                this.controller.onAccept(key);
                continue;
            }
            if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                // Remove write interest
                key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                this.controller.onWrite(key);
                if (!this.controller.isHandleReadWriteConcurrently()) {
                    skipOpRead = true;
                }
            }
            if (!skipOpRead && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                // read
                key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
                // ???
                if (!this.controller.getStatistics().isReceiveOverFlow()) {
                    // Remove read interest

                    this.controller.onRead(key);// ?
                    continue;
                } else {
                    key.interestOps(key.interestOps() // 
                            | SelectionKey.OP_READ);
                }

            }
            if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
                this.controller.onConnect(key);
                continue;
            }

        } catch (final RejectedExecutionException e) {
            // ???
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.notifyException(e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        } catch (final CancelledKeyException e) {
            // ignore
        } catch (final Exception e) {
            if (key.attachment() instanceof AbstractNioSession) {
                ((AbstractSession) key.attachment()).onException(e);
            }
            this.controller.closeSelectionKey(key);
            this.controller.notifyException(e);
            log.error("Reactor dispatch events error", e);
            if (this.selector.isOpen()) {
                continue;
            } else {
                break;
            }
        }
    }
}

From source file:x10.x10rt.yarn.ApplicationMaster.java

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {/*  w  w w .j  a  va  2  s .co m*/
            SelectionKey key;
            // check for previously unhandled events
            if (events != null && events.hasNext()) {
                key = events.next();
                events.remove();
            } else if (selector.select() == 0) // check for new events
                continue; // nothing to process, go back and block on select again
            else { // select returned some events
                events = selector.selectedKeys().iterator();
                key = events.next();
                events.remove();
            }

            // process the selectionkey
            if (key.isAcceptable()) {
                LOG.info("New connection from X10 detected");
                // accept any connections on the server socket, and look for things to read from it
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();

                ByteBuffer incomingMsg;
                if (pendingReads.containsKey(sc))
                    incomingMsg = pendingReads.remove(sc);
                else
                    incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder());

                LOG.info("Reading message from X10");
                try {
                    if (sc.read(incomingMsg) == -1) {
                        // socket closed
                        sc.close();
                        key.cancel();
                        pendingReads.remove(sc);
                    } else if (incomingMsg.hasRemaining()) {
                        LOG.info("Message header partially read. " + incomingMsg.remaining()
                                + " bytes remaining");
                        pendingReads.put(sc, incomingMsg);
                    } else { // buffer is full
                        if (incomingMsg.capacity() == headerLength) {
                            // check to see if there is a body associated with this message header
                            int datalen = incomingMsg.getInt(headerLength - 4);
                            //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen);
                            if (datalen == 0)
                                processMessage(incomingMsg, sc);
                            else { // create a larger array to hold the header+body
                                ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen)
                                        .order(ByteOrder.nativeOrder());
                                incomingMsg.rewind();
                                newBuffer.put(incomingMsg);
                                incomingMsg = newBuffer;
                                sc.read(incomingMsg); // read in the body, if available
                                if (incomingMsg.hasRemaining()) {
                                    LOG.info("Message partially read. " + incomingMsg.remaining()
                                            + " bytes remaining");
                                    pendingReads.put(sc, incomingMsg);
                                } else
                                    processMessage(incomingMsg, sc);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.warn("Error reading in message from socket channel", e);
                }
            }
        } catch (IOException e) {
            LOG.warn("Error handling X10 links", e);
        }
    }
}

From source file:Proxy.java

String printSelectionOps(SelectionKey key) {
    StringBuilder sb = new StringBuilder();
    if ((key.readyOps() & SelectionKey.OP_ACCEPT) != 0)
        sb.append("OP_ACCEPT ");
    if ((key.readyOps() & SelectionKey.OP_CONNECT) != 0)
        sb.append("OP_CONNECT ");
    if ((key.readyOps() & SelectionKey.OP_READ) != 0)
        sb.append("OP_READ ");
    if ((key.readyOps() & SelectionKey.OP_WRITE) != 0)
        sb.append("OP_WRITE ");
    return sb.toString();
}

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

private static final void processWrite(SelectionKey key) throws Exception {
    Object att = key.attachment();
    if (att == null) {
        Thread.sleep(100);//from  w  ww.  ja va2  s  . c om
        return;
    }
    if (att instanceof ByteBuffer) {
        ByteBuffer buffer = (ByteBuffer) att;
        if (!buffer.hasRemaining()) {
            key.attach(new byte[0]);
            key.interestOps(SelectionKey.OP_READ);
            return;
        }
        SocketChannel channel = (SocketChannel) key.channel();
        channel.write(buffer);
    }
}