Example usage for java.nio.channels SelectionKey attachment

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

Introduction

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

Prototype

Object attachment

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

Click Source Link

Usage

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

protected void __doExceptionEvent(final SelectionKey key, final Throwable e) {
    final INioSession _session = (INioSession) key.attachment();
    if (_session == null) {
        try {//from   w w w  .j a va2  s  .co  m
            key.channel().close();
            key.cancel();
        } catch (Throwable ex) {
            _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(ex));
        }
    } else {
        _session.status(ISession.Status.ERROR);
    }
    __eventGroup.executorService().submit(new Runnable() {
        public void run() {
            try {
                __eventGroup.listener().onExceptionCaught(e, _session);
            } catch (Throwable ex) {
                _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(ex));
            }
        }
    });
    if (_session != null) {
        try {
            _session.close();
        } catch (Throwable ex) {
            _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(ex));
        }
    }
}

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

protected void __doConnectEvent(SelectionKey key) throws IOException {
    INioSession _session = (INioSession) key.attachment();
    if (_session != null) {
        SocketChannel _channel = (SocketChannel) key.interestOps(0).channel();
        if (_channel.finishConnect()) {
            _session.finishConnect();/* w w  w. j a  va2 s. c  o m*/
        }
        _session.selectionKey(key);
        _session.status(ISession.Status.CONNECTED);
        __eventGroup.listener().onSessionConnected(_session);
    }
}

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

protected void __doReadEvent(SelectionKey key) throws IOException {
    final INioSession _session = (INioSession) key.attachment();
    if (_session != null && _session.isConnected()) {
        _session.read();//from   w w  w  .  jav a2 s  .  co m
    }
}

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

protected void __doWriteEvent(SelectionKey key) throws IOException {
    INioSession _session = (INioSession) key.attachment();
    if (_session != null && _session.isConnected()) {
        _session.write();/*w ww.ja  v  a  2  s . c o  m*/
    }
}

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

/**
 * Remove an endpoint. This causes the corresponding UDP socket to be
 * closed.//from  w w w .  ja  v a  2s.c om
 * 
 * @param endpoint the endpoint description
 * @throws IOException if an error occurred when closing the socket
 */
public void removeEndpoint(final Endpoint endpoint) throws IOException {
    execute(new SelectorOperation() {
        @Override
        public void doExecute(Selector selector) throws IOException {
            Iterator<SelectionKey> it = selector.keys().iterator();
            while (it.hasNext()) {
                SelectionKey key = it.next();
                Endpoint endpointForKey = (Endpoint) key.attachment();
                if (endpoint == endpointForKey) {
                    key.cancel();
                    key.channel().close();
                    break;
                }
            }
        }
    });
}

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

/**
 * Run the I/O dispatcher.//from   w w  w  .j av  a2  s. c  o  m
 * This method contains the event loop that polls the selector, reads the incoming
 * packets and dispatches the work.
 * It only returns when {@link #stop()} is called.
 */
public void run() {
    while (true) {
        try {
            selector.select();
        } catch (IOException ex) {
            log.error("Exception in select; I/O dispatcher will be shut down", ex);
            return;
        }
        // Execute pending selector operations
        while (true) {
            SelectorOperation request = selectorOperationQueue.poll();
            if (request == null) {
                break;
            }
            request.execute(selector);
            if (!selector.isOpen()) {
                return;
            }
        }
        for (Iterator<SelectionKey> it = selector.selectedKeys().iterator(); it.hasNext();) {
            SelectionKey key = it.next();
            it.remove();
            if (key.isValid() && key.isReadable()) {
                receive((Endpoint) key.attachment(), (DatagramChannel) key.channel());
            }
        }
    }
}

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  w ww  . j  a  va 2s .  co m
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:org.apache.htrace.impl.PackedBufferManager.java

@Override
public void flush() throws IOException {
    SelectionKey sockKey = null;
    IOException ioe = null;/*from w  ww . ja  va  2s.c  o  m*/
    frameBuffer.position(0);
    prequel.getBuffer().position(0);
    spans.getBuffer().position(0);
    if (LOG.isTraceEnabled()) {
        LOG.trace("Preparing to flush " + numSpans + " spans to " + conf.endpointStr);
    }
    try {
        sockKey = doConnect();
        doSend(sockKey, new ByteBuffer[] { frameBuffer, prequel.getBuffer(), spans.getBuffer() });
        ByteBuffer response = prequel.getBuffer();
        readAndValidateResponseFrame(sockKey, response, 1, METHOD_ID_WRITE_SPANS);
    } catch (IOException e) {
        // This LOG message is only at debug level because we also log these
        // exceptions at error level inside HTracedReceiver.  The logging in
        // HTracedReceiver is rate-limited to avoid overwhelming the client log
        // if htraced goes down.  The debug and trace logging is not
        // rate-limited.
        if (LOG.isDebugEnabled()) {
            LOG.debug("Got exception during flush", e);
        }
        ioe = e;
    } finally {
        if (sockKey != null) {
            sockKey.cancel();
            try {
                SocketChannel sock = (SocketChannel) sockKey.attachment();
                sock.close();
            } catch (IOException e) {
                if (ioe != null) {
                    ioe.addSuppressed(e);
                }
            }
        }
    }
    if (ioe != null) {
        throw ioe;
    }
    if (LOG.isTraceEnabled()) {
        LOG.trace("Successfully flushed " + numSpans + " spans to " + conf.endpointStr);
    }
}

From source file:org.apache.htrace.impl.PackedBufferManager.java

private SelectionKey doConnect() throws IOException {
    SocketChannel sock = SocketChannel.open();
    SelectionKey sockKey = null;//  w w w  .  j a va 2 s .  co  m
    boolean success = false;
    try {
        if (sock.isBlocking()) {
            sock.configureBlocking(false);
        }
        InetSocketAddress resolvedEndpoint = new InetSocketAddress(conf.endpoint.getHostString(),
                conf.endpoint.getPort());
        resolvedEndpoint.getHostName(); // trigger DNS resolution
        sock.connect(resolvedEndpoint);
        sockKey = sock.register(selector, SelectionKey.OP_CONNECT, sock);
        long startMs = TimeUtil.nowMs();
        long remainingMs = conf.connectTimeoutMs;
        while (true) {
            selector.select(remainingMs);
            for (SelectionKey key : selector.keys()) {
                if (key.isConnectable()) {
                    SocketChannel s = (SocketChannel) key.attachment();
                    s.finishConnect();
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Successfully connected to " + conf.endpointStr + ".");
                    }
                    success = true;
                    return sockKey;
                }
            }
            remainingMs = updateRemainingMs(startMs, conf.connectTimeoutMs);
            if (remainingMs == 0) {
                throw new IOException("Attempt to connect to " + conf.endpointStr + " timed out after "
                        + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms.");
            }
        }
    } finally {
        if (!success) {
            if (sockKey != null) {
                sockKey.cancel();
            }
            sock.close();
        }
    }
}

From source file:org.apache.htrace.impl.PackedBufferManager.java

/**
 * Send the provided ByteBuffer objects.
 *
 * We use non-blocking I/O because Java does not provide write timeouts.
 * Without a write timeout, the socket could get hung and we'd never recover.
 * We also use the GatheringByteChannel#write method which calls the pread()
 * system call under the covers.  This ensures that even if TCP_NODELAY is on,
 * we send the minimal number of packets.
 *///  w w  w .  ja v a  2s  .  c o  m
private void doSend(SelectionKey sockKey, ByteBuffer[] bufs) throws IOException {
    long totalWritten = 0;
    sockKey.interestOps(SelectionKey.OP_WRITE);
    SocketChannel sock = (SocketChannel) sockKey.attachment();
    long startMs = TimeUtil.nowMs();
    long remainingMs = conf.ioTimeoutMs;
    while (true) {
        selector.select(remainingMs);
        int firstBuf = 0;
        for (SelectionKey key : selector.selectedKeys()) {
            if (key.isWritable()) {
                long written = sock.write(bufs, firstBuf, bufs.length - firstBuf);
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Sent " + written + " bytes to " + conf.endpointStr);
                }
                totalWritten += written;
            }
        }
        while (true) {
            if (firstBuf == bufs.length) {
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Finished sending " + totalWritten + " bytes to " + conf.endpointStr);
                }
                return;
            }
            if (bufs[firstBuf].remaining() > 0) {
                break;
            }
            firstBuf++;
        }
        remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs);
        if (remainingMs == 0) {
            throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after "
                    + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms.");
        }
    }
}