Example usage for java.nio.channels SelectionKey channel

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

Introduction

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

Prototype

public abstract SelectableChannel channel();

Source Link

Document

Returns the channel for which this key was created.

Usage

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//w w  w.  jav  a 2 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:me.schiz.jmeter.ring.udp.EventLoopRunnable.java

@Override
public void run() {
    log.info("EventLoop started in " + Thread.currentThread().getName());
    int events_count, register_count;
    while (true) {
        try {//  w ww.  j  a v  a2  s  .  co m
            if (!selector.isOpen())
                break;
            try {
                events_count = selector.select(POLL_TIMEOUT);
            } catch (ClosedSelectorException e) {
                log.error("Selector is closed", e);
                break;
            }
            register_count = registerQueue.size();
            if (register_count > 0)
                registerCallback(register_count);
            if (events_count == 0)
                continue;

            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                DatagramChannel dc = (DatagramChannel) key.channel();

                try {
                    if (key.isReadable())
                        readCallback(dc);
                } catch (CancelledKeyException e) {
                    log.error("cancelled key exception", e);
                    Token t = ring.get(dc);
                    if (t != null) {
                        t.lock.lock();
                        ring.reset(t.id);
                        t.lock.unlock();
                    }
                }
                it.remove();
            }
        } catch (IOException e) {
            log.error("IOException", e);
            break;
        }
    }
    byteBuffer.clear();
    log.info("EventLoop in " + Thread.currentThread().getName() + " has stopped");
}

From source file:net.ymate.platform.serv.nio.support.NioEventProcessor.java

protected void __doAcceptEvent(SelectionKey key) throws IOException {
    SocketChannel _channel = ((ServerSocketChannel) key.channel()).accept();
    _channel.configureBlocking(false);/* www . ja  va2 s .c  om*/
    INioSession _session = new NioSession<LISTENER>(__eventGroup, _channel);
    _session.selectionKey(key);
    _session.status(ISession.Status.CONNECTED);
    __eventGroup.listener().onSessionAccepted(_session);
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

private SelectionKey selectFirstConnectedSocketChannel(Selector selector) throws IOException {
    log.trace("selectFirstConnectedSocketChannel()");

    while (!selector.keys().isEmpty()) {
        if (selector.select(connectTimeout) == 0) { // Block until something happens
            return null;
        }//ww w .java  2s .co  m

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey key = it.next();
            if (key.isValid() && key.isConnectable()) {
                SocketChannel channel = (SocketChannel) key.channel();
                try {
                    if (channel.finishConnect()) {
                        return key;
                    }
                } catch (Exception e) {
                    key.cancel();
                    closeQuietly(channel);

                    log.trace("Error connecting socket channel: {}", e);
                }
            }

            it.remove();
        }
    }

    return null;
}

From source file:net.socket.nio.TimeClientHandle.java

private void handleInput(SelectionKey key) throws IOException {

    if (key.isValid()) {
        // ??/*from w ww  . j  a va  2  s. c  om*/
        SocketChannel sc = (SocketChannel) key.channel();
        if (key.isConnectable()) {
            if (sc.finishConnect()) {
                sc.register(selector, SelectionKey.OP_READ);
                doWrite(sc);
            } else {
                System.exit(1);// 
            }
        }
        if (key.isReadable()) {
            ByteBuffer readBuffer = ByteBuffer.allocate(1024);
            int readBytes = sc.read(readBuffer);
            if (readBytes > 0) {
                readBuffer.flip();
                byte[] bytes = new byte[readBuffer.remaining()];
                readBuffer.get(bytes);
                String body = new String(bytes, "UTF-8");
                System.out.println("Now is : " + body);
                this.stop = true;
            } else if (readBytes < 0) {
                // 
                key.cancel();
                sc.close();
            } else {
                ; // 0
            }
        }
    }

}

From source file:org.apache.catalina.cluster.tcp.TcpReplicationThread.java

/**
 * The actual code which drains the channel associated with
 * the given key.  This method assumes the key has been
 * modified prior to invocation to turn off selection
 * interest in OP_READ.  When this method completes it
 * re-enables OP_READ and calls wakeup() on the selector
 * so the selector will resume watching this channel.
 *///from ww  w  .j a va 2s  .c om
private void drainChannel(SelectionKey key) throws Exception {
    boolean packetReceived = false;
    SocketChannel channel = (SocketChannel) key.channel();
    int count;
    buffer.clear(); // make buffer empty
    ObjectReader reader = (ObjectReader) key.attachment();
    // loop while data available, channel is non-blocking
    while ((count = channel.read(buffer)) > 0) {
        buffer.flip(); // make buffer readable
        int pkgcnt = reader.append(buffer.array(), 0, count);
        buffer.clear(); // make buffer empty
    }
    //check to see if any data is available
    int pkgcnt = reader.execute();
    while (pkgcnt > 0) {
        if (synchronous) {
            sendAck(key, channel);
        } //end if
        pkgcnt--;
    }
    if (count < 0) {
        // close channel on EOF, invalidates the key
        channel.close();
        return;
    }
    // resume interest in OP_READ, OP_WRITE
    key.interestOps(key.interestOps() | SelectionKey.OP_READ);
    // cycle the selector so this key is active again
    key.selector().wakeup();
}

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

private void doRead(SelectionKey key) {

    final SocketChannel socketChannel = (SocketChannel) key.channel();
    final OutgoingConnection outgoingConnection = (OutgoingConnection) key.attachment();
    final ByteBuffer buf = ByteBuffer.allocate(8);

    try {//from   www . j a  va  2 s .c  o  m

        if (socketChannel.read(buf) == -1) {
            outgoingConnection.reportTransmissionProblem(new IOException("Read unexpected EOF from channel"));
        } else {
            LOG.error("Outgoing connection read real data from channel");
        }
    } catch (IOException ioe) {
        outgoingConnection.reportTransmissionProblem(ioe);
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

SocketInfo select() throws IOException {
    log.trace("select()");

    Selector selector = Selector.open();

    SocketInfo selectedSocket = initConnections(selector);
    if (selectedSocket != null) {
        return selectedSocket;
    }//from w w w  .  j  ava2s  .  c om

    URI selectedAddress = null;
    SocketChannel channel = null;
    try {
        SelectionKey key = selectFirstConnectedSocketChannel(selector);
        if (key == null) {
            return null;
        }

        channel = (SocketChannel) key.channel();
        selectedAddress = (URI) key.attachment();
    } finally {
        try {
            closeSelector(selector, channel);
        } catch (Exception e) {
            log.error("Error while closing selector", e);
        }
    }

    if (channel != null) {
        channel.configureBlocking(true);
        return new SocketInfo(selectedAddress, channel.socket());
    }

    return null;
}

From source file:org.apache.axis2.transport.udp.IODispatcher.java

/**
 * Stop the dispatcher./* w w w.  ja  v  a  2  s. c  o m*/
 * This method closes all sockets and causes the execution of the
 * {@link #run()} method to stop.
 * 
 * @throws IOException
 */
public void stop() throws IOException {
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            IOException exception = null;
            for (SelectionKey key : selector.keys()) {
                try {
                    key.channel().close();
                } catch (IOException ex) {
                    if (exception == null) {
                        exception = ex;
                    }
                }
            }
            try {
                selector.close();
            } catch (IOException ex) {
                if (exception == null) {
                    exception = ex;
                }
            }
            if (exception != null) {
                throw exception;
            }
        }
    });
}

From source file:com.cloudbees.jenkins.plugins.sshagent.jna.AgentServer.java

public void close() {
    selectable = false;/*from ww  w.java 2s .  c om*/
    selector.wakeup();

    // forcibly close remaining sockets
    for (SelectionKey key : selector.keys()) {
        if (key != null) {
            safelyClose(key.channel());
        }
    }

    safelyClose(selector);
    safelyClose(agent);
    safelyClose(channel);
    if (authSocket != null) {
        FileUtils.deleteQuietly(new File(authSocket));
    }
}