Example usage for java.nio.channels SelectionKey readyOps

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

Introduction

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

Prototype

public abstract int readyOps();

Source Link

Document

Retrieves this key's ready-operation set.

Usage

From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteFailed() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String message = "hi\n";
    when(socket.write(any(ByteBuffer.class))).thenThrow(new IOException("write failed"));
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();/*from ww  w .  jav  a2  s .  com*/
    List<String> callbackInvoked = new ArrayList<>();
    List<Exception> exceptionHandlerInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = exceptionHandlerInvoked::add;
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(0, messageStream.size());
    Assert.assertEquals(0, callbackInvoked.size());
    Assert.assertEquals(1, exceptionHandlerInvoked.size());
}

From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteCompleteMessage() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String message = "hi\n";
    when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() {
        @Override//w w w  .ja  va 2 s  .  c o  m
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            while (buffer.hasRemaining())
                messageStream.write(buffer.get());
            return buffer.position();
        }
    });
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();
    List<String> callbackInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage());
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8));
    Assert.assertEquals(1, callbackInvoked.size());
}

From source file:com.byteatebit.nbserver.task.TestWriteMessageTask.java

@Test
public void testWriteMessageInParts() throws IOException {
    SocketChannel socket = mock(SocketChannel.class);
    ByteArrayOutputStream messageStream = new ByteArrayOutputStream();
    String messagePart1 = "messagePart1 ";
    String messagePart2 = "messagePart2";
    String message = messagePart1 + messagePart2;
    when(socket.write(any(ByteBuffer.class))).then(new Answer<Integer>() {
        @Override//from   w  w  w.j  av a2 s  . c  o  m
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            for (int i = 0; i < messagePart1.length(); i++)
                messageStream.write(buffer.get());
            return messagePart1.length();
        }
    }).then(new Answer<Integer>() {
        @Override
        public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
            ByteBuffer buffer = (ByteBuffer) invocationOnMock.getArguments()[0];
            for (int i = 0; i < messagePart2.length(); i++)
                messageStream.write(buffer.get());
            return messagePart2.length();
        }
    });
    INbContext nbContext = mock(INbContext.class);
    SelectionKey selectionKey = mock(SelectionKey.class);
    when(selectionKey.channel()).thenReturn(socket);
    when(selectionKey.isValid()).thenReturn(true);
    when(selectionKey.readyOps()).thenReturn(SelectionKey.OP_WRITE);

    WriteMessageTask writeTask = WriteMessageTask.Builder.builder().withByteBuffer(ByteBuffer.allocate(100))
            .build();
    List<String> callbackInvoked = new ArrayList<>();
    Runnable callback = () -> callbackInvoked.add("");
    Consumer<Exception> exceptionHandler = e -> Assert.fail(e.getMessage());
    writeTask.writeMessage(message.getBytes(StandardCharsets.UTF_8), nbContext, socket, callback,
            exceptionHandler);
    verify(nbContext, times(1)).register(any(SocketChannel.class), eq(SelectionKey.OP_WRITE), any(), any());
    // simulate first write
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(0)).interestOps(0);
    // simulate second write
    writeTask.write(selectionKey, callback, exceptionHandler);
    verify(selectionKey, times(1)).interestOps(0);

    Assert.assertEquals(message, messageStream.toString(StandardCharsets.UTF_8));
    Assert.assertEquals(1, callbackInvoked.size());
}

From source file:org.reunionemu.jreunion.server.Network.java

@Override
public void run() {
    logger.info("network thread starting");
    while (true) {
        try {/* ww  w .  j a v a 2  s  . c om*/
            // See if we've had any activity -- either an incoming connection,
            // or incoming data on an existing connection
            int num = selector.select();
            if (num == 0) {
                // we need synchronize here otherwise we might block again before we were able to change the selector
                synchronized (this) {
                    continue;
                }
            }

            // If we don't have any activity, loop around and wait again
            // Get the keys corresponding to the activity
            // that has been detected, and process them one by one

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                // Get a key representing one of bits of I/O activity
                SelectionKey key = it.next();
                if (!key.isValid())
                    continue;

                SelectableChannel selectableChannel = key.channel();
                // What kind of activity is it?
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

                    // It's an incoming connection.
                    // Register this socket with the Selector
                    // so we can listen for input on it                  

                    SocketChannel clientSocketChannel = ((ServerSocketChannel) selectableChannel).accept();

                    processAccept(clientSocketChannel);

                } else {
                    SocketChannel socketChannel = (SocketChannel) selectableChannel;

                    if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                        // It's incoming data on a connection, so process it
                        boolean ok = processInput(socketChannel);

                        // If the connection is dead, then remove it
                        // from the selector and close it
                        if (!ok) {
                            LoggerFactory.getLogger(Network.class).info("Client Connection Lost");
                            key.cancel();
                            disconnect(socketChannel);
                        }

                    } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {

                        boolean ok = processOutput(socketChannel);
                        if (ok) {
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                }
            }
            // We remove the selected keys, because we've dealt with them.
            keys.clear();

        } catch (Exception e) {
            if (e instanceof ClosedSelectorException || e instanceof InterruptedException)
                return;
            LoggerFactory.getLogger(Network.class).error("Error in network", e);
        }
    }

}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

@Override
protected void handle(SelectionKey key) {
    System.out.println("ReadWriteThread.handle() " + describeInterestOps(key.interestOps()) + ", ready: "
            + describeInterestOps(key.readyOps()));
    switch (key.readyOps()) {
    case SelectionKey.OP_CONNECT:
        finishConnection(key);//from   w  ww  .j  a  v a  2 s .  c  o m
        break;
    case SelectionKey.OP_READ:
        readPacket(key);
        break;
    case SelectionKey.OP_WRITE:
        writePacket(key);
        break;
    case SelectionKey.OP_READ | SelectionKey.OP_WRITE:
        writePacket(key);
        // key might have been invalidated on writePacket
        if (key.isValid())
            readPacket(key);
        break;
    default:
        System.err.println("Unknown readyOps: " + key.readyOps() + " for " + key.attachment());
        break;
    }
}

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: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();/*  ww  w .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: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();/*  www . ja  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:org.bonmassar.crappydb.server.io.TestPoolThreadExecutor.java

private List<SelectionKey> getKeys() {
    List<SelectionKey> keys = new ArrayList<SelectionKey>();
    for (int i = 0; i < 1000; i++) {
        SelectionKey key = mock(FakeSelectionKey.class);
        when(key.readyOps()).thenReturn(0);
        keys.add(key);/*from   www  .j  a v a  2s  .  com*/
    }

    return keys;
}