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:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Write data/* ww  w  .java2s  . c  o m*/
 * 
 * @throws IOException
 */
private void processWrite(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

    DaapConnectionNIO connection = (DaapConnectionNIO) sk.attachment();
    SocketChannel channel = (SocketChannel) sk.channel();

    boolean keepAlive = false;

    try {
        keepAlive = connection.write();
    } catch (DaapStreamException err) {

        // Broken pipe: User pressed Pause, fast-foward 
        // or whatever. Just close the connection and go 
        // ahead
        keepAlive = false;
        //LOG.error(err);
    }

    if (keepAlive) {
        sk.interestOps(connection.interrestOps());

    } else {
        cancel(sk);
    }
}

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

private final void processRead(SelectionKey key) throws Exception {

    // Read packet from socket channel
    sleep(100);/*ww w  .  java2 s.c o  m*/
    byte[] bytes = null;
    Object att = key.attachment();
    if (att != null && att instanceof byte[]) {
        bytes = (byte[]) att;
    }
    SocketChannel channel = (SocketChannel) key.channel();
    requestBuffer.clear();
    int len = channel.read(requestBuffer);
    if (len == -1) {
        throw new IOException();
    }
    if (len != 0) {
        requestBuffer.flip();
        byte[] packet = new byte[len];
        requestBuffer.get(packet, 0, len);
        if (bytes == null || bytes.length == 0) {
            bytes = packet;
            key.attach(bytes);
        } else {
            byte[] swap = new byte[bytes.length + packet.length];
            System.arraycopy(bytes, 0, swap, 0, bytes.length);
            System.arraycopy(packet, 0, swap, bytes.length, packet.length);
            bytes = swap;
            key.attach(bytes);
        }

        // Try to process packet
        LdapMessageContainer container = new LdapMessageContainer();
        try {
            ByteBuffer buffer = ByteBuffer.wrap(bytes);
            LdapDecoder decoder = new LdapDecoder();
            decoder.decode(buffer, container);
        } catch (DecoderException emptyStringException) {
            String msg = emptyStringException.getMessage();
            if (msg != null && (msg.indexOf("empty") != -1 || msg.indexOf("transition") != -1)) {
                // All contacts requested
                int id = container.getMessageId();
                SearchRequest search = new SearchRequest();
                search.setMessageId(id);
                LdapMessage ldap = new LdapMessage();
                ldap.setMessageId(id);
                ldap.setProtocolOP(search);
                container.setLdapMessage(ldap);
            } else {
                throw emptyStringException;
            }
        }

        // Process LDAP request
        ByteBuffer response = processRequest(container.getLdapMessage(), !container.isGrammarEndAllowed());
        key.attach(response);
        key.interestOps(SelectionKey.OP_WRITE);
    }
}

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

private boolean lookJVMBug(final long before, final int selected, final long wait) throws IOException {
    boolean seeing = false;
    final long now = System.currentTimeMillis();
    /**/*  www  . j  a va 2s  .co m*/
     * Bug?,(1)select0 (2)select?? (3)? (4)?wakenup
     */
    if (JVMBUG_THRESHHOLD > 0 && selected == 0 && wait > JVMBUG_THRESHHOLD && now - before < wait / 4
            && !this.wakenUp.get() /* waken up */
            && !Thread.currentThread().isInterrupted()/* Interrupted */) {
        this.jvmBug.incrementAndGet();
        // ?1?selector
        if (this.jvmBug.get() >= JVMBUG_THRESHHOLD2) {
            this.gate.lock();
            try {
                this.lastJVMBug = now;
                log.warn("JVM bug occured at " + new Date(this.lastJVMBug)
                        + ",http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933,reactIndex="
                        + this.reactorIndex);
                if (this.jvmBug1) {
                    log.debug("seeing JVM BUG(s) - recreating selector,reactIndex=" + this.reactorIndex);
                } else {
                    this.jvmBug1 = true;
                    log.info("seeing JVM BUG(s) - recreating selector,reactIndex=" + this.reactorIndex);
                }
                seeing = true;
                // selector
                final Selector new_selector = SystemUtils.openSelector();

                for (final SelectionKey k : this.selector.keys()) {
                    if (!k.isValid() || k.interestOps() == 0) {
                        continue;
                    }

                    final SelectableChannel channel = k.channel();
                    final Object attachment = k.attachment();
                    // ?interestOps>0channel
                    channel.register(new_selector, k.interestOps(), attachment);
                }

                this.selector.close();
                this.selector = new_selector;

            } finally {
                this.gate.unlock();
            }
            this.jvmBug.set(0);

        } else if (this.jvmBug.get() == JVMBUG_THRESHHOLD || this.jvmBug.get() == JVMBUG_THRESHHOLD1) {
            // BUG?0?interestedOps==0key
            if (this.jvmBug0) {
                log.debug("seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + this.reactorIndex);
            } else {
                this.jvmBug0 = true;
                log.info("seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + this.reactorIndex);
            }
            this.gate.lock();
            seeing = true;
            try {
                for (final SelectionKey k : this.selector.keys()) {
                    if (k.isValid() && k.interestOps() == 0) {
                        k.cancel();
                    }
                }
            } finally {
                this.gate.unlock();
            }
        }
    } else {
        this.jvmBug.set(0);
    }
    return seeing;
}

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

private boolean lookJVMBug(final long before, final int selected, final long wait) throws IOException {
    boolean seeing = false;
    final long now = System.currentTimeMillis();
    /**/*from   www . j  a  v  a 2 s.  c om*/
     * Bug,(1)select0 (2)select (3) (4)wakenup
     */
    if (JVMBUG_THRESHHOLD > 0 && selected == 0 && wait > JVMBUG_THRESHHOLD && now - before < wait / 4
            && !this.wakenUp.get() /* waken up */
            && !Thread.currentThread().isInterrupted()/* Interrupted */) {
        this.jvmBug.incrementAndGet();
        // 1selector
        if (this.jvmBug.get() >= JVMBUG_THRESHHOLD2) {
            this.gate.lock();
            try {
                this.lastJVMBug = now;
                log.warn("JVM bug occured at " + new Date(this.lastJVMBug)
                        + ",http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6403933,reactIndex="
                        + this.reactorIndex);
                if (this.jvmBug1) {
                    log.debug("seeing JVM BUG(s) - recreating selector,reactIndex=" + this.reactorIndex);
                } else {
                    this.jvmBug1 = true;
                    log.info("seeing JVM BUG(s) - recreating selector,reactIndex=" + this.reactorIndex);
                }
                seeing = true;
                // selector
                final Selector new_selector = SystemUtils.openSelector();

                for (final SelectionKey k : this.selector.keys()) {
                    if (!k.isValid() || k.interestOps() == 0) {
                        continue;
                    }

                    final SelectableChannel channel = k.channel();
                    final Object attachment = k.attachment();
                    // interestOps>0channel
                    channel.register(new_selector, k.interestOps(), attachment);
                }

                this.selector.close();
                this.selector = new_selector;

            } finally {
                this.gate.unlock();
            }
            this.jvmBug.set(0);

        } else if (this.jvmBug.get() == JVMBUG_THRESHHOLD || this.jvmBug.get() == JVMBUG_THRESHHOLD1) {
            // BUG0interestedOps==0key
            if (this.jvmBug0) {
                log.debug("seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + this.reactorIndex);
            } else {
                this.jvmBug0 = true;
                log.info("seeing JVM BUG(s) - cancelling interestOps==0,reactIndex=" + this.reactorIndex);
            }
            this.gate.lock();
            seeing = true;
            try {
                for (final SelectionKey k : this.selector.keys()) {
                    if (k.isValid() && k.interestOps() == 0) {
                        k.cancel();
                    }
                }
            } finally {
                this.gate.unlock();
            }
        }
    } else {
        this.jvmBug.set(0);
    }
    return seeing;
}

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

private final void processRead(SelectionKey key) throws Exception {

    // Read packet from socket channel
    sleep(100);//from ww  w. ja v a 2 s  .  co  m
    byte[] bytes = null;
    Object att = key.attachment();
    if (att != null && att instanceof byte[]) {
        bytes = (byte[]) att;
    }
    SocketChannel channel = (SocketChannel) key.channel();
    requestBuffer.clear();
    int len = channel.read(requestBuffer);
    if (len == -1) {
        throw new IOException();
    }
    if (len != 0) {
        requestBuffer.flip();
        byte[] packet = new byte[len];
        requestBuffer.get(packet, 0, len);
        if (bytes == null || bytes.length == 0) {
            bytes = packet;
            key.attach(bytes);
        } else {
            byte[] swap = new byte[bytes.length + packet.length];
            System.arraycopy(bytes, 0, swap, 0, bytes.length);
            System.arraycopy(packet, 0, swap, bytes.length, packet.length);
            bytes = swap;
            key.attach(bytes);
        }

        // Try to process packet
        LdapMessageContainer container = new LdapMessageContainer();
        try {
            ByteBuffer buffer = ByteBuffer.wrap(bytes);
            LdapDecoder decoder = new LdapDecoder();
            decoder.decode(buffer, container);
        } catch (DecoderException emptyStringException) {
            String msg = emptyStringException.getMessage();
            if (msg != null && (msg.indexOf("empty") != -1 || msg.indexOf("transition") != -1)) {

                // All contacts requested
                int id = container.getMessageId();
                SearchRequest search = new SearchRequest();
                search.setMessageId(id);
                LdapMessage ldap = new LdapMessage();
                ldap.setMessageId(id);
                ldap.setProtocolOP(search);
                container.setLdapMessage(ldap);
            } else {
                throw emptyStringException;
            }
        }

        // Process LDAP request
        ByteBuffer response = processRequest(container.getLdapMessage(), !container.isGrammarEndAllowed());
        key.attach(response);
        key.interestOps(SelectionKey.OP_WRITE);
    }
}

From source file:com.byteatebit.nbserver.simple.SelectorTask.java

protected void executeIoTasksOnSelectedKeys() {
    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
        SelectionKey selectionKey = iterator.next();
        iterator.remove();//from   ww w  . jav a  2  s.c om
        try {
            NioSelectionKeyEntry nioTaskEntry = (NioSelectionKeyEntry) selectionKey.attachment();
            if (nioTaskEntry == null) {
                LOG.error("The nio task is unexpectedly null for selectionKey " + selectionKey);
                return;
            }
            nioTaskEntry.executeTasks(selectionKey);
        } catch (Exception e) {
            LOG.error("Failed to execute the consumer attached to selectionKey " + selectionKey
                    + ".  Cancelling the key and closing the underlying channel", e);
            try {
                selectionKey.channel().close();
            } catch (IOException e1) {
                LOG.error("selection key channel error on close", e);
            }
            selectionKey.cancel();
        }
    }
}

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected void onConnectable() {
    lock.lock();//  w  w  w  . ja v a  2s.  c o m
    SocketChannel aSocketChannel = null;
    try {
        synchronized (selector) {
            selector.selectNow();
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isConnectable()) {
                aSocketChannel = (SocketChannel) selKey.channel();
                aSocketChannel.finishConnect();
                logger.trace("The channel for '{}' is connected", aSocketChannel.getRemoteAddress());
            }
        }
    } catch (IOException | NoConnectionPendingException e) {
        if (aSocketChannel != null) {
            logger.debug("Disconnecting '{}' because of a socket error : '{}'", getThing().getUID(),
                    e.getMessage(), e);
            try {
                aSocketChannel.close();
            } catch (IOException e1) {
                logger.debug("An exception occurred while closing the channel '{}': {}", socketChannel,
                        e1.getMessage());
            }
        }
    } finally {
        lock.unlock();
    }
}

From source file:ca.wumbo.doommanager.server.ServerManager.java

/**
 * Kills any connections that have not sent any messages for a period of
 * time.//  www.  j ava2  s. c  o m
 * 
 * @return
 *       True if there was no error, false if an error occured.
 */
private boolean killInactiveConnections() {
    // Go through each connection every so often to check for dead connections.
    if (System.currentTimeMillis() - lastTimeoutCheckMillis > TIMEOUT_FREQUENCY_CHECK_MILLIS) {
        lastTimeoutCheckMillis = System.currentTimeMillis();
        log.trace("Checking for timeouts... {}", System.currentTimeMillis());

        // We cannot do this if the selector is closed.
        if (selector.isOpen()) {
            // Go through each connection...
            for (SelectionKey key : selector.keys()) {
                // If the attachment has client info (which it always should)...
                if (key.attachment() instanceof ClientInfo) {
                    ClientInfo clientInfo = (ClientInfo) key.attachment();
                    // If the client hasn't responded for a certain amount of time, kill the connection.
                    if (clientInfo.hasReceivedMessageSince(TIMEOUT_CLIENT_MILLIS)) {
                        log.info("Client {} timed out, requesting connection termination.",
                                clientInfo.getIPAddress());
                        Channel channel = key.channel();
                        key.cancel();
                        try {
                            channel.close();
                        } catch (IOException e) {
                            log.error("Error closing a timed out client's channel: {}", e.getMessage());
                        }
                    }
                }
            }
        }
    }

    // Signal all is good.
    return true;
}

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected void onWritable(ByteBuffer buffer) {
    lock.lock();//w w w .  ja  v a  2s  .  c  om
    try {
        synchronized (selector) {
            try {
                selector.selectNow();
            } catch (IOException e) {
                logger.error("An exception occurred while selecting: {}", e.getMessage());
            }
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isWritable()) {
                SocketChannel aSocketChannel = (SocketChannel) selKey.channel();

                if (aSocketChannel.equals(socketChannel)) {
                    boolean error = false;

                    buffer.rewind();
                    try {
                        logger.trace("Sending '{}' on the channel '{}'->'{}'", new String(buffer.array()),
                                aSocketChannel.getLocalAddress(), aSocketChannel.getRemoteAddress());
                        aSocketChannel.write(buffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel,
                                e.getMessage());
                        if (!aSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (ClosedChannelException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel for '{}' is closed: {}", aSocketChannel, e.getMessage());
                        error = true;
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel,
                                e.getMessage());
                        error = true;
                    }

                    if (error) {
                        try {
                            aSocketChannel.close();
                        } catch (IOException e) {
                            logger.warn("An exception occurred while closing the channel '{}': {}",
                                    aSocketChannel, e.getMessage());
                        }
                    }
                }
            }
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected ByteBuffer onReadable(int bufferSize, boolean isSelective) {
    lock.lock();/*w  w w. j  a  va  2 s  .  c  om*/
    try {
        synchronized (selector) {
            try {
                selector.selectNow();
            } catch (IOException e) {
                logger.error("An exception occurred while selecting: {}", e.getMessage());
            }
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isReadable()) {
                SocketChannel aSocketChannel = (SocketChannel) selKey.channel();

                if ((aSocketChannel.equals(socketChannel) && isSelective) || !isSelective) {
                    ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize);
                    int numberBytesRead = 0;
                    boolean error = false;

                    try {
                        numberBytesRead = aSocketChannel.read(readBuffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel,
                                e.getMessage());
                        if (!aSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel,
                                e.getMessage());
                        error = true;
                    }

                    if (numberBytesRead == -1) {
                        error = true;
                    }

                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID());
                        try {
                            aSocketChannel.close();
                        } catch (IOException e1) {
                            logger.debug("An exception occurred while closing the channel '{}': {}",
                                    socketChannel, e1.getMessage());
                        }
                    } else {
                        readBuffer.flip();
                        return readBuffer;
                    }
                }
            }
        }

        return null;
    } finally {
        lock.unlock();
    }
}