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:org.gcaldaemon.core.ldap.LDAPListener.java

private final void processRead(SelectionKey key) throws Exception {

    // Read packet from socket channel
    sleep(100);//from   w  w w . j a  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:org.gcaldaemon.core.ldap.LDAPListener.java

private static final void processWrite(SelectionKey key) throws Exception {
    Object att = key.attachment();
    if (att == null) {
        Thread.sleep(100);/*from w ww.  j  a va 2 s  .c  om*/
        return;
    }
    if (att instanceof ByteBuffer) {
        ByteBuffer buffer = (ByteBuffer) att;
        if (!buffer.hasRemaining()) {
            key.attach(new byte[0]);
            key.interestOps(SelectionKey.OP_READ);
            return;
        }
        SocketChannel channel = (SocketChannel) key.channel();
        channel.write(buffer);
    }
}

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

private final void processRead(SelectionKey key) throws Exception {

    // Read packet from socket channel
    sleep(100);//w w  w  .jav a  2  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:org.pvalsecc.comm.MultiplexedServer.java

private void readyToReceive(SelectionKey key) {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    //noinspection ConstantConditions
    SocketChannel socket = (SocketChannel) key.channel();
    ServerConnection connection = (ServerConnection) key.attachment();

    int size;//from w  w  w.  j a v  a2  s  .  co  m
    try {
        size = socket.read(buffer);
    } catch (IOException e) {
        //message logging and call to "closed" is done in "error" method
        connection.error("Cannot receive data", e);
        key.cancel();
        SystemUtilities.safeClose(socket);
        return;
    }

    if (size >= 0) {
        if (size != buffer.position()) {
            throw new RuntimeException(
                    "[" + threadName + "] Inconsistent buffer: " + size + "!=" + buffer.position());
        }
        nbBytesReceived += size;
        nbReceived++;
        buffer.flip();
        connection.received(buffer);
    } else {
        LOGGER.info("[" + threadName + "] Connection closed by " + connection);
        connection.closed();
        key.cancel();
    }
}

From source file:org.pvalsecc.comm.MultiplexedServer.java

private void readyToSend(SelectionKey key) {
    SocketChannel socket = (SocketChannel) key.channel();
    ServerConnection connection = (ServerConnection) key.attachment();

    try {/*from   w ww  . java2s  .  co m*/
        nbBytesSent += connection.send(socket);
        nbSent++;
    } catch (IOException e) {
        connection.error("Cannot send data", e);
        key.cancel();
        SystemUtilities.safeClose(socket);
    }
}

From source file:org.quickserver.net.server.QuickServer.java

/**
 * Starts server in non-blocking mode./* ww w.jav  a 2  s .  c o m*/
 * @since 1.4.5
 */
private void runNonBlocking(TheClient theClient) throws Exception {
    int selectCount = 0;
    Iterator iterator = null;
    SelectionKey key = null;
    ServerSocketChannel serverChannel = null;
    SocketChannel socketChannel = null;
    Socket client = null;
    ClientHandler _chPolled = null;
    boolean stopServerProcessed = false;
    int linger = getBasicConfig().getAdvancedSettings().getSocketLinger();
    registerChannelRequestMap = new HashMap();

    int socketTrafficClass = 0;
    if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
        socketTrafficClass = Integer
                .parseInt(getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass());
    }

    while (true) {
        selectCount = selector.select(500);
        //selectCount = selector.select();//for testing

        //check for any pending registerChannel req.
        synchronized (registerChannelRequestMap) {
            if (registerChannelRequestMap.size() > 0) {
                RegisterChannelRequest req = null;
                Object hashkey = null;
                iterator = registerChannelRequestMap.keySet().iterator();
                while (iterator.hasNext()) {
                    hashkey = iterator.next();
                    req = (RegisterChannelRequest) registerChannelRequestMap.get(hashkey);
                    req.register(getSelector());
                }
                iterator = null;
                registerChannelRequestMap.clear();
            } //if
        } //sync

        if (stopServer == true && stopServerProcessed == false) {
            logger.warning("Closing " + getName());
            serverSocketChannel.close();
            stopServerProcessed = true;

            server = null;
            serverSocketChannel = null;

            setServiceState(Service.STOPPED);
            logger.warning("Closed " + getName());

            processServerHooks(ServerHook.POST_SHUTDOWN);
        }

        if (stopServer == false && stopServerProcessed == true) {
            logger.finest("Server must have re-started.. will break");
            break;
        }

        if (selectCount == 0 && stopServerProcessed == true) {
            java.util.Set keyset = selector.keys();
            if (keyset.isEmpty() == true && getClientCount() <= 0) {
                break;
            } else {
                continue;
            }
        } else if (selectCount == 0) {
            continue;
        }

        iterator = selector.selectedKeys().iterator();
        while (iterator.hasNext()) {
            key = (SelectionKey) iterator.next();

            if (key.isValid() == false) {
                iterator.remove();
                continue;
            }

            if (key.isAcceptable() && stopServer == false) {
                logger.finest("Key is Acceptable");
                serverChannel = (ServerSocketChannel) key.channel();
                socketChannel = serverChannel.accept();

                if (socketChannel == null) {
                    iterator.remove();
                    continue;
                }

                client = socketChannel.socket();

                if (linger < 0) {
                    client.setSoLinger(false, 0);
                } else {
                    client.setSoLinger(true, linger);
                }

                client.setTcpNoDelay(getBasicConfig().getAdvancedSettings().getClientSocketTcpNoDelay());

                if (getBasicConfig().getAdvancedSettings().getClientSocketTrafficClass() != null) {
                    client.setTrafficClass(socketTrafficClass);//low delay=10
                }

                //logger.fine("ReceiveBufferSize: "+client.getReceiveBufferSize());

                if (getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize() != 0) {
                    client.setSendBufferSize(
                            getBasicConfig().getAdvancedSettings().getClientSocketSendBufferSize());
                    //logger.fine("SendBufferSize: "+client.getSendBufferSize());
                }

                if (checkAccessConstraint(client) == false) {
                    iterator.remove();
                    continue;
                }

                socketChannel.configureBlocking(false);
                theClient.setTrusted(getSkipValidation());
                theClient.setSocket(socketChannel.socket());
                theClient.setSocketChannel(socketChannel);

                if (clientDataClass != null) {
                    if (getClientDataPool() == null) {
                        clientData = (ClientData) clientDataClass.newInstance();
                    } else {
                        //borrow a object from pool
                        clientData = (ClientData) getClientDataPool().borrowObject();
                    }
                    theClient.setClientData(clientData);
                }

                //Check if max connection has reached
                if (getSkipValidation() != true && maxConnection != -1
                        && getClientHandlerPool().getNumActive() >= maxConnection) {
                    theClient.setClientEvent(ClientEvent.MAX_CON);
                } else {
                    theClient.setClientEvent(ClientEvent.ACCEPT);
                }

                try {
                    _chPolled = (ClientHandler) getClientHandlerPool().borrowObject();
                    logger.finest("Asking " + _chPolled.getName() + " to handle.");
                    _chPolled.handleClient(theClient);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.warning("Could not borrow ClientHandler Object from pool. Error: " + nsee);
                    logger.warning("Closing SocketChannel [" + serverChannel.socket()
                            + "] since no ClientHandler available.");
                    socketChannel.close();
                }

                if (_chPolled != null) {
                    try {
                        getClientPool().addClient(_chPolled, true);
                    } catch (java.util.NoSuchElementException nsee) {
                        logger.warning("Could not borrow Thread from pool. Error: " + nsee);
                        //logger.warning("Closing SocketChannel ["+serverChannel.socket()+"] since no Thread available.");
                        //socketChannel.close();
                        //returnClientHandlerToPool(_chPolled);
                    }
                    _chPolled = null;
                }
                socketChannel = null;
                client = null;

                setSkipValidation(false);//reset it back
            } else if (key.isValid() && key.isReadable()) {
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Readable, removing OP_READ from interestOps for " + _ch.getName());
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
                    _ch.addEvent(ClientEvent.READ);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.READ);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (key.isValid() && key.isWritable()) {
                if (getClientPool().shouldNioWriteHappen() == false) {
                    continue; //no need to remove the key
                }
                boolean addedEvent = false;
                ClientHandler _ch = null;
                try {
                    _ch = (ClientHandler) key.attachment();
                    logger.finest("Key is Writable, removing OP_WRITE from interestOps for " + _ch.getName());
                    //remove OP_WRITE from interest set
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                    _ch.addEvent(ClientEvent.WRITE);
                    addedEvent = true;
                    //_ch.setSelectionKey(key);
                    getClientPool().addClient(_ch);
                } catch (CancelledKeyException cke) {
                    logger.fine("Ignored Error - Key was Cancelled: " + cke);
                } catch (java.util.NoSuchElementException nsee) {
                    logger.finest("NoSuchElementException: " + nsee);
                    if (addedEvent)
                        _ch.removeEvent(ClientEvent.WRITE);
                    continue;//no need to remove the key
                }
                _ch = null;
            } else if (stopServer == true && key.isAcceptable()) {
                //we will not accept this key
                setSkipValidation(false);//reset it back
            } else {
                logger.warning("Unknown key got in SelectionKey: " + key);
            }
            iterator.remove(); //Remove key

            Thread.yield();
        } //end of iterator
        iterator = null;
    } //end of loop
}

From source file:voldemort.common.nio.AbstractSelectorManager.java

public void close() {
    // Attempt to close, but if already closed, then we've been beaten to
    // the punch...
    if (!isClosed.compareAndSet(false, true))
        return;// ww  w .j  a v a 2s  .  c  o  m

    try {
        for (SelectionKey sk : selector.keys()) {
            try {
                if (logger.isTraceEnabled())
                    logger.trace("Closing SelectionKey's channel");

                sk.channel().close();

                Object attachment = sk.attachment();
                if (attachment instanceof Closeable) {
                    IOUtils.closeQuietly((Closeable) attachment);
                }
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.WARN))
                    logger.warn(e.getMessage(), e);
            }

            try {
                if (logger.isTraceEnabled())
                    logger.trace("Cancelling SelectionKey");

                sk.cancel();
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.WARN))
                    logger.warn(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.WARN))
            logger.warn(e.getMessage(), e);
    }

    try {
        selector.close();
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.WARN))
            logger.warn(e.getMessage(), e);
    }
}

From source file:voldemort.common.nio.AbstractSelectorManager.java

public void run() {
    threadName = Thread.currentThread().getName();

    try {//from www  .j a v a2s .  c  o  m
        while (true) {
            if (isClosed.get()) {
                logger.debug("SelectorManager is closed, exiting");

                break;
            }

            lastHeartBeatTimeMs = System.currentTimeMillis();
            processEvents();

            try {
                selectTimeMs = System.currentTimeMillis();
                int selected = selector.select(SELECTOR_POLL_MS);
                selectTimeMs = System.currentTimeMillis() - selectTimeMs;
                selectCount = selected;

                if (isClosed.get()) {
                    logger.debug("SelectorManager is closed, exiting");

                    break;
                }

                if (selected > 0) {
                    processingTimeMs = System.currentTimeMillis();
                    Iterator<SelectionKey> i = selector.selectedKeys().iterator();

                    while (i.hasNext()) {
                        SelectionKey selectionKey = i.next();
                        i.remove();

                        if (selectionKey.isValid() && (selectionKey.isConnectable() || selectionKey.isReadable()
                                || selectionKey.isWritable())) {
                            Runnable worker = (Runnable) selectionKey.attachment();
                            worker.run();
                        }
                    }
                    processingTimeMs = System.currentTimeMillis() - processingTimeMs;
                }
            } catch (ClosedSelectorException e) {
                logger.debug("SelectorManager is closed, exiting");

                break;
            } catch (Throwable t) {
                if (logger.isEnabledFor(Level.ERROR))
                    logger.error(t.getMessage(), t);
            }
        }
    } catch (Throwable t) {
        if (logger.isEnabledFor(Level.ERROR))
            logger.error(t.getMessage(), t);
    } finally {
        try {
            close();
        } catch (Exception e) {
            if (logger.isEnabledFor(Level.ERROR))
                logger.error(e.getMessage(), e);
        }
    }
}

From source file:xbird.server.services.RemotePagingService.java

private void acceptConnections(final ServerSocketChannel channel) throws IOException {
    // set to non blocking mode
    channel.configureBlocking(false);//from   w  w w  .  j a v  a2s. c  om

    // Bind the server socket to the local host and port
    InetAddress host = InetAddress.getLocalHost();
    InetSocketAddress sockAddr = new InetSocketAddress(host, PORT);
    ServerSocket socket = channel.socket();
    //socket.setReuseAddress(true);
    socket.bind(sockAddr);

    // Register accepts on the server socket with the selector. This
    // step tells the selector that the socket wants to be put on the
    // ready list when accept operations occur.
    Selector selector = Selector.open();

    ByteBuffer cmdBuffer = ByteBuffer.allocateDirect(MAX_COMMAND_BUFLEN);
    IOHandler ioHandler = new IOHandler(cmdBuffer);
    AcceptHandler acceptHandler = new AcceptHandler(ioHandler);

    channel.register(selector, SelectionKey.OP_ACCEPT, acceptHandler);

    int n;
    while ((n = selector.select()) > 0) {
        // Someone is ready for I/O, get the ready keys
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> keyItor = selectedKeys.iterator();
        while (keyItor.hasNext()) {
            SelectionKey key = keyItor.next();
            keyItor.remove();
            // The key indexes into the selector so you
            // can retrieve the socket that's ready for I/O
            Handler handler = (Handler) key.attachment();
            try {
                handler.handle(key);
            } catch (CancelledKeyException cke) {
                ;
            } catch (IOException ioe) {
                LOG.fatal(ioe);
                NIOUtils.cancelKey(key);
            } catch (Throwable e) {
                LOG.fatal(e);
                NIOUtils.cancelKey(key);
            }
        }
    }
}