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:net.sf.cindy.impl.SimpleEventGenerator.java

protected void processKey(SelectionKey key) {
    SessionSpi session = (SessionSpi) key.attachment();

    if (key.isAcceptable())
        session.onEvent(Constants.EV_ACCEPTABLE, null);
    if (key.isConnectable())
        session.onEvent(Constants.EV_CONNECTABLE, null);
    if (key.isValid() && key.isReadable())
        session.onEvent(Constants.EV_READABLE, null);
    if (key.isValid() && key.isWritable())
        session.onEvent(Constants.EV_WRITABLE, null);
}

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

/**
 * Read data//from w  ww  .j  ava 2 s.  c  o m
 * 
 * @throws IOException
 */
private void processRead(SelectionKey sk) throws IOException {

    if (!sk.isValid())
        return;

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

    boolean keepAlive = false;

    keepAlive = connection.read();

    if (keepAlive) {
        sk.interestOps(connection.interrestOps());
    } else {
        cancel(sk);
    }
}

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

/**
 * Accept an icoming connection/*ww  w  .j a  v  a  2 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:de.kapsi.net.daap.nio.DaapServerNIO.java

/**
 * Write data/*from   w ww.j av a2 s.  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: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();
    /**//from w  ww .  j  a va 2  s.  com
     * 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();
    /**//  ww  w  .ja  v a2 s.c o 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();
        // 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: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();//from   w ww  .  j a v  a2 s  . com
        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();//from   w  w w  . j  a va2  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.l2jfree.network.mmocore.ReadWriteThread.java

private void finishConnection(SelectionKey key) {
    try {//  ww w .  j a v  a  2 s .  com
        ((SocketChannel) key.channel()).finishConnect();
    } catch (IOException e) {
        @SuppressWarnings("unchecked")
        T con = (T) key.attachment();
        closeConnectionImpl(con, true);
        return;
    }

    // key might have been invalidated on finishConnect()
    if (key.isValid()) {
        key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT);
    }
}

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

/**
 * Notify all clients about an update of the Library
 *//*from  w w  w.  jav  a2s . c o  m*/
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);
                }
            }
        }
    }
}