Example usage for java.nio.channels SelectionKey cancel

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

Introduction

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

Prototype

public abstract void cancel();

Source Link

Document

Requests that the registration of this key's channel with its selector be cancelled.

Usage

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpMultiplexer.java

private void closeSocketChannel(AbstractSelectableChannel channel, Selector selector) {
    try {/*from  www. j  ava 2s .c  o m*/
        SelectionKey sk = channel.keyFor(selector);
        if (sk != null && sk.isValid())
            sk.cancel();
        if (channel.isOpen())
            channel.close();
    } catch (Exception e) {
        log.error("Could not close channel : " + e.toString());
    }
}

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  ww.  j  a va2s. 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:org.apache.axis2.transport.udp.IODispatcher.java

/**
 * Remove an endpoint. This causes the corresponding UDP socket to be
 * closed.//w  w w .j av  a2  s . com
 * 
 * @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.htrace.impl.PackedBufferManager.java

@Override
public void flush() throws IOException {
    SelectionKey sockKey = null;
    IOException ioe = null;/*from   ww  w .  j  a  va 2 s .co 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;
    boolean success = false;
    try {// w w  w  . ja  v a2  s .c  o m
        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.nifi.io.nio.ChannelListener.java

public void shutdown(final long period, final TimeUnit timeUnit) {
    channelDispatcher.stop();//from ww w.  j a  v a2s .c  om
    for (SelectionKey selectionKey : socketChannelSelector.keys()) {
        final AbstractChannelReader reader = (AbstractChannelReader) selectionKey.attachment();
        selectionKey.cancel();
        if (reader != null) {
            while (!reader.isClosed()) {
                try {
                    Thread.sleep(channelReaderFrequencyMSecs);
                } catch (InterruptedException e) {
                }
            }
            final ScheduledFuture<?> readerFuture = reader.getScheduledFuture();
            readerFuture.cancel(false);
        }
        IOUtils.closeQuietly(selectionKey.channel()); // should already be closed via reader, but if reader did not exist...
    }
    IOUtils.closeQuietly(socketChannelSelector);

    for (SelectionKey selectionKey : serverSocketSelector.keys()) {
        selectionKey.cancel();
        IOUtils.closeQuietly(selectionKey.channel());
    }
    IOUtils.closeQuietly(serverSocketSelector);
    executor.shutdown();
    try {
        executor.awaitTermination(period, timeUnit);
    } catch (final InterruptedException ex) {
        LOGGER.warn("Interrupted while trying to shutdown executor");
    }
    final int currentBufferPoolSize = bufferPool.size();
    final String warning = (currentBufferPoolSize != initialBufferPoolSize)
            ? "Initial buffer count=" + initialBufferPoolSize + " Current buffer count=" + currentBufferPoolSize
                    + " Could indicate a buffer leak.  Ensure all consumers are executed until they complete."
            : "";
    LOGGER.info("Channel listener shutdown. " + warning);
}

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

/**
 * Remove an endpoint. This causes the corresponding UDP socket to be
 * closed.//from  w w w  .  jav a  2s  .  c  o  m
 * 
 * @param serviceName the name of the service corresponding to
 *                    the endpoint
 * @throws IOException if an error occurred when closing the socket
 */
public void removeEndpoint(final String serviceName) 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 endpoint = (Endpoint) key.attachment();
                if (serviceName.equals(endpoint.getService().getName())) {
                    key.cancel();
                    key.channel().close();
                    break;
                }
            }
        }
    });
}

From source file:org.commoncrawl.io.internal.NIOSocketSelector.java

/** cancel all event registrations on the specified object (socket) */
public void cancelRegistration(NIOSocket theSocket) {

    if (_eventLoop == null || _eventLoop.getEventThread() == Thread.currentThread()) {
        if (theSocket.getChannel() != null) {
            SelectionKey key = theSocket.getChannel().keyFor(_selector);

            if (key != null) {
                key.cancel();
            }/*from  w  ww  .j  a va  2s  . c  o  m*/
        }
    } else {
        synchronized (_pendingRegistrations) {
            _pendingRegistrations.put(theSocket.getSocketId(), new PendingRegistration(theSocket, 0));
        }
        _eventLoop.wakeup();
    }
}

From source file:org.commoncrawl.rpc.thriftrpc.ThriftRPCServerChannel.java

/**
 * Do connection-close cleanup on a given SelectionKey.
 *///  ww  w.  ja va2 s. co m
private void cleanupSelectionkey(SelectionKey key) {
    // remove the records from the two maps
    ThriftRPCClientChannel buffer = (ThriftRPCClientChannel) key.attachment();
    if (buffer != null) {
        // close the buffer
        buffer.close();
    }
    // cancel the selection key
    key.cancel();
}

From source file:org.eclipsetrader.directa.internal.core.BrokerConnector.java

@Override
public void run() {
    Selector socketSelector;//from   ww w  .j  a  v  a 2  s. co m
    ByteBuffer dst = ByteBuffer.wrap(new byte[2048]);
    List<Position> positions = new ArrayList<Position>();

    try {
        // Create a non-blocking socket channel
        socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);

        socketChannel.socket().setReceiveBufferSize(32768);
        socketChannel.socket().setSoLinger(true, 1);
        socketChannel.socket().setSoTimeout(0x15f90);
        socketChannel.socket().setReuseAddress(true);

        // Kick off connection establishment
        socketChannel.connect(new InetSocketAddress(server, port));

        // Create a new selector
        socketSelector = SelectorProvider.provider().openSelector();

        // Register the server socket channel, indicating an interest in
        // accepting new connections
        socketChannel.register(socketSelector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT);
    } catch (Exception e) {
        Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to orders monitor", //$NON-NLS-1$
                e);
        Activator.log(status);
        return;
    }

    for (;;) {
        try {
            if (socketSelector.select(30 * 1000) == 0) {
                logger.trace(">" + HEARTBEAT); //$NON-NLS-1$
                socketChannel.write(ByteBuffer.wrap(new String(HEARTBEAT + "\r\n").getBytes())); //$NON-NLS-1$
            }
        } catch (Exception e) {
            break;
        }

        // Iterate over the set of keys for which events are available
        Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator();
        while (selectedKeys.hasNext()) {
            SelectionKey key = selectedKeys.next();
            selectedKeys.remove();

            if (!key.isValid()) {
                continue;
            }

            try {
                // Check what event is available and deal with it
                if (key.isConnectable()) {
                    // Finish the connection. If the connection operation failed
                    // this will raise an IOException.
                    try {
                        socketChannel.finishConnect();
                    } catch (IOException e) {
                        // Cancel the channel's registration with our selector
                        key.cancel();
                        return;
                    }

                    // Register an interest in writing on this channel
                    key.interestOps(SelectionKey.OP_WRITE);
                }
                if (key.isWritable()) {
                    logger.trace(">" + LOGIN + WebConnector.getInstance().getUser()); //$NON-NLS-1$
                    socketChannel.write(ByteBuffer.wrap(
                            new String(LOGIN + WebConnector.getInstance().getUser() + "\r\n").getBytes())); //$NON-NLS-1$

                    // Register an interest in reading on this channel
                    key.interestOps(SelectionKey.OP_READ);
                }
                if (key.isReadable()) {
                    dst.clear();
                    int readed = socketChannel.read(dst);
                    if (readed > 0) {
                        String[] s = new String(dst.array(), 0, readed).split("\r\n"); //$NON-NLS-1$
                        for (int i = 0; i < s.length; i++) {
                            logger.trace("<" + s[i]); //$NON-NLS-1$

                            if (s[i].endsWith(";" + WebConnector.getInstance().getUser() + ";")) { //$NON-NLS-1$ //$NON-NLS-2$
                                logger.trace(">" + UNKNOWN70); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN70 + "\r\n").getBytes())); //$NON-NLS-1$
                                logger.trace(">" + UNKNOWN55); //$NON-NLS-1$
                                socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN55 + "\r\n").getBytes())); //$NON-NLS-1$
                            }

                            if (s[i].indexOf(";6;5;") != -1 || s[i].indexOf(";8;0;") != -1) { //$NON-NLS-1$ //$NON-NLS-2$
                                try {
                                    OrderMonitor monitor = parseOrderLine(s[i]);

                                    OrderDelta[] delta;
                                    synchronized (orders) {
                                        if (!orders.contains(monitor)) {
                                            orders.add(monitor);
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_ADDED, monitor) };
                                        } else {
                                            delta = new OrderDelta[] {
                                                    new OrderDelta(OrderDelta.KIND_UPDATED, monitor) };
                                        }
                                    }
                                    fireUpdateNotifications(delta);

                                    if (monitor.getFilledQuantity() != null
                                            && monitor.getAveragePrice() != null) {
                                        Account account = WebConnector.getInstance().getAccount();
                                        account.updatePosition(monitor);
                                    }
                                } catch (ParseException e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";6;0;") != -1) { //$NON-NLS-1$
                                updateStatusLine(s[i]);
                            }
                            if (s[i].indexOf(";7;0;") != -1) { //$NON-NLS-1$
                                try {
                                    positions.add(new Position(s[i]));
                                } catch (Exception e) {
                                    Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0,
                                            "Error parsing line: " + s[i], e); //$NON-NLS-1$
                                    Activator.log(status);
                                }
                            }
                            if (s[i].indexOf(";7;9;") != -1) { //$NON-NLS-1$
                                Account account = WebConnector.getInstance().getAccount();
                                account.setPositions(positions.toArray(new Position[positions.size()]));
                                positions.clear();
                            }
                        }
                    }
                }
            } catch (Exception e) {
                Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Connection error", e); //$NON-NLS-1$
                Activator.log(status);
            }
        }
    }
}