Example usage for java.nio.channels SelectionKey attach

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

Introduction

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

Prototype

public final Object attach(Object ob) 

Source Link

Document

Attaches the given object to this key.

Usage

From source file:com.web.services.ExecutorServiceThread.java

public void run() {

    // create a selector that will by used for multiplexing. The selector
    // registers the socketserverchannel as
    // well as all socketchannels that are created
    String CLIENTCHANNELNAME = "clientChannel";
    String SERVERCHANNELNAME = "serverChannel";
    String channelType = "channelType";

    ConcurrentHashMap<SelectionKey, Object> resultMap = new ConcurrentHashMap<SelectionKey, Object>();
    ClassLoader classLoader = null;
    ByteArrayOutputStream bstr;/*  w  w w. jav a2s . com*/
    ByteBuffer buffer = null;
    ByteBuffer lengthBuffer = ByteBuffer.allocate(4);
    int bytesRead;
    InputStream bais;
    ObjectInputStream ois;
    Object object;
    ExecutorServiceInfo executorServiceInfo = null;
    Random random = new Random(System.currentTimeMillis());
    // register the serversocketchannel with the selector. The OP_ACCEPT
    // option marks
    // a selection key as ready when the channel accepts a new connection.
    // When the
    // socket server accepts a connection this key is added to the list of
    // selected keys of the selector.
    // when asked for the selected keys, this key is returned and hence we
    // know that a new connection has been accepted.
    try {
        Selector selector = Selector.open();
        SelectionKey socketServerSelectionKey = serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        // SelectionKey socketServerSelectionKey1 =
        // channel.register(selector1,
        // SelectionKey.OP_ACCEPT);

        // set property in the key that identifies the channel
        Map<String, String> properties = new ConcurrentHashMap<String, String>();
        properties.put(channelType, SERVERCHANNELNAME);
        socketServerSelectionKey.attach(properties);
        // wait for the selected keys
        SelectionKey key = null;
        Set<SelectionKey> selectedKeys;
        // logger.info("Instance Number"+instanceNumber);
        Iterator<SelectionKey> iterator = null;
        SocketChannel clientChannel = null;
        while (true) {
            try {
                // the select method is a blocking method which returns when
                // atleast
                // one of the registered
                // channel is selected. In this example, when the socket
                // accepts
                // a
                // new connection, this method
                // will return. Once a socketclient is added to the list of
                // registered channels, then this method
                // would also return when one of the clients has data to be
                // read
                // or
                // written. It is also possible to perform a nonblocking
                // select
                // using the selectNow() function.
                // We can also specify the maximum time for which a select
                // function
                // can be blocked using the select(long timeout) function.

                if (selector.select() >= 0) {
                    selectedKeys = selector.selectedKeys();
                    iterator = selectedKeys.iterator();
                }
                while (iterator.hasNext()) {
                    try {
                        key = iterator.next();
                        // the selection key could either by the
                        // socketserver
                        // informing
                        // that a new connection has been made, or
                        // a socket client that is ready for read/write
                        // we use the properties object attached to the
                        // channel
                        // to
                        // find
                        // out the type of channel.
                        if (((Map) key.attachment()).get(channelType).equals(SERVERCHANNELNAME)) {
                            // a new connection has been obtained. This
                            // channel
                            // is
                            // therefore a socket server.
                            ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                            // accept the new connection on the server
                            // socket.
                            // Since
                            // the
                            // server socket channel is marked as non
                            // blocking
                            // this channel will return null if no client is
                            // connected.
                            SocketChannel clientSocketChannel = serverSocketChannel.accept();

                            if (clientSocketChannel != null) {
                                // set the client connection to be non
                                // blocking
                                clientSocketChannel.configureBlocking(false);
                                SelectionKey clientKey = clientSocketChannel.register(selector,
                                        SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                                Map<String, String> clientproperties = new ConcurrentHashMap<String, String>();
                                clientproperties.put(channelType, CLIENTCHANNELNAME);
                                clientKey.attach(clientproperties);
                                clientKey.interestOps(SelectionKey.OP_READ);
                                // clientSocketChannel.close();
                                // write something to the new created client
                                /*
                                 * CharBuffer buffer =
                                 * CharBuffer.wrap("Hello client"); while
                                 * (buffer.hasRemaining()) {
                                 * clientSocketChannel.write
                                 * (Charset.defaultCharset()
                                 * .encode(buffer)); }
                                 * clientSocketChannel.close();
                                 * buffer.clear();
                                 */
                            }

                        } else {
                            // data is available for read
                            // buffer for reading
                            clientChannel = (SocketChannel) key.channel();
                            if (key.isReadable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till
                                // the
                                // count is >=0
                                clientChannel = (SocketChannel) key.channel();
                                if (resultMap.get(key) == null) {
                                    //System.out.println(key);
                                    bstr = new ByteArrayOutputStream();
                                    object = null;
                                    clientChannel.read(lengthBuffer);
                                    int length = lengthBuffer.getInt(0);
                                    lengthBuffer.clear();
                                    //System.out.println(length);
                                    buffer = ByteBuffer.allocate(length);
                                    if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                        // buffer.flip();
                                        // System.out
                                        // .println(bytesRead);
                                        bstr.write(buffer.array(), 0, bytesRead);
                                        buffer.clear();
                                    }
                                    buffer.clear();
                                    //System.out.println("Message1"+new String(bstr
                                    //      .toByteArray()));
                                    bais = new ByteArrayInputStream(bstr.toByteArray());
                                    ois = new ObjectInputStream(bais); // Offending
                                    // line.
                                    // Produces
                                    // the
                                    // StreamCorruptedException.
                                    //System.out.println("In read obect");
                                    object = ois.readObject();
                                    //System.out.println("Class Cast");
                                    //System.out.println("Class Cast1");
                                    ois.close();
                                    byte[] params = bstr.toByteArray();
                                    bstr.close();
                                    //System.out.println("readObject");
                                    //System.out.println("After readObject");
                                    if (object instanceof CloseSocket) {
                                        resultMap.remove(key);
                                        clientChannel.close();
                                        key.cancel();
                                    }
                                    // clientChannel.close();
                                    String serviceurl = (String) object;
                                    String[] serviceRegistry = serviceurl.split("/");
                                    //System.out.println("classLoaderMap"
                                    //      + urlClassLoaderMap);
                                    //System.out.println(deployDirectory
                                    //      + "/" + serviceRegistry[0]);

                                    int servicenameIndex;
                                    //System.out.println(earServicesDirectory
                                    //      + "/" + serviceRegistry[0]
                                    //      + "/" + serviceRegistry[1]);
                                    if (serviceRegistry[0].endsWith(".ear")) {
                                        classLoader = (VFSClassLoader) urlClassLoaderMap
                                                .get(earServicesDirectory + "/" + serviceRegistry[0] + "/"
                                                        + serviceRegistry[1]);
                                        servicenameIndex = 2;
                                    } else if (serviceRegistry[0].endsWith(".jar")) {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(jarservicesDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    } else {
                                        classLoader = (WebClassLoader) urlClassLoaderMap
                                                .get(deployDirectory + "/" + serviceRegistry[0]);
                                        servicenameIndex = 1;
                                    }
                                    String serviceName = serviceRegistry[servicenameIndex];
                                    // System.out.println("servicename:"+serviceName);;
                                    synchronized (executorServiceMap) {
                                        executorServiceInfo = (ExecutorServiceInfo) executorServiceMap
                                                .get(serviceName.trim());
                                    }
                                    ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = new ExecutorServiceInfoClassLoader();
                                    classLoaderExecutorServiceInfo.setClassLoader(classLoader);
                                    classLoaderExecutorServiceInfo.setExecutorServiceInfo(executorServiceInfo);
                                    resultMap.put(key, classLoaderExecutorServiceInfo);
                                    // key.interestOps(SelectionKey.OP_READ);
                                    // System.out.println("Key interested Ops");
                                    // continue;
                                }
                                //Thread.sleep(100);
                                /*
                                 * if (classLoader == null) throw new
                                 * Exception(
                                 * "Could able to obtain deployed class loader"
                                 * );
                                 */
                                /*
                                 * System.out.println(
                                 * "current context classloader" +
                                 * classLoader);
                                 */
                                //System.out.println("In rad object");
                                bstr = new ByteArrayOutputStream();
                                lengthBuffer.clear();
                                int numberofDataRead = clientChannel.read(lengthBuffer);
                                //System.out.println("numberofDataRead"
                                //      + numberofDataRead);
                                int length = lengthBuffer.getInt(0);
                                if (length <= 0) {
                                    iterator.remove();
                                    continue;
                                }
                                lengthBuffer.clear();
                                //System.out.println(length);
                                buffer = ByteBuffer.allocate(length);
                                buffer.clear();
                                if ((bytesRead = clientChannel.read(buffer)) > 0) {
                                    // buffer.flip();
                                    // System.out
                                    // .println(bytesRead);
                                    bstr.write(buffer.array(), 0, bytesRead);
                                    buffer.clear();
                                }
                                if (bytesRead <= 0 || bytesRead < length) {
                                    //System.out.println("bytesRead<length");
                                    iterator.remove();
                                    continue;
                                }
                                //System.out.println(new String(bstr
                                //   .toByteArray()));
                                bais = new ByteArrayInputStream(bstr.toByteArray());

                                ExecutorServiceInfoClassLoader classLoaderExecutorServiceInfo = (ExecutorServiceInfoClassLoader) resultMap
                                        .get(key);
                                ois = new ClassLoaderObjectInputStream(
                                        (ClassLoader) classLoaderExecutorServiceInfo.getClassLoader(), bais); // Offending
                                // line.
                                // Produces
                                // the
                                // StreamCorruptedException.
                                object = ois.readObject();
                                ois.close();
                                bstr.close();
                                executorServiceInfo = classLoaderExecutorServiceInfo.getExecutorServiceInfo();
                                //System.out
                                //      .println("inputStream Read Object");
                                //System.out.println("Object="
                                //      + object.getClass());
                                // Thread.currentThread().setContextClassLoader(currentContextLoader);
                                if (object instanceof ExecutorParams) {
                                    ExecutorParams exeParams = (ExecutorParams) object;
                                    Object returnValue = null;

                                    //System.out.println("test socket1");
                                    String ataKey;
                                    ATAConfig ataConfig;
                                    ConcurrentHashMap ataServicesMap;

                                    ATAExecutorServiceInfo servicesAvailable;
                                    Socket sock1 = new Socket("0.0.0.0",
                                            Integer.parseInt(nodesport[random.nextInt(nodesport.length)]));
                                    OutputStream outputStr = sock1.getOutputStream();
                                    ObjectOutputStream objOutputStream = new ObjectOutputStream(outputStr);
                                    NodeInfo nodeInfo = new NodeInfo();
                                    nodeInfo.setClassNameWithPackage(
                                            executorServiceInfo.getExecutorServicesClass().getName());
                                    nodeInfo.setMethodName(executorServiceInfo.getMethod().getName());

                                    nodeInfo.setWebclassLoaderURLS(((WebClassLoader) classLoader).geturlS());
                                    NodeInfoMethodParam nodeInfoMethodParam = new NodeInfoMethodParam();
                                    nodeInfoMethodParam.setMethodParams(exeParams.getParams());
                                    nodeInfoMethodParam
                                            .setMethodParamTypes(executorServiceInfo.getMethodParams());
                                    //System.out.println("Serializable socket="+sock);
                                    //nodeInfo.setSock(sock);
                                    //nodeInfo.setOstream(sock.getOutputStream());
                                    objOutputStream.writeObject(nodeInfo);
                                    objOutputStream = new ObjectOutputStream(outputStr);
                                    objOutputStream.writeObject(nodeInfoMethodParam);
                                    ObjectInputStream objInputStream1 = new ObjectInputStream(
                                            sock1.getInputStream());
                                    returnValue = objInputStream1.readObject();
                                    objOutputStream.close();
                                    objInputStream1.close();
                                    sock1.close();
                                    /*returnValue = executorServiceInfo
                                          .getMethod()
                                          .invoke(executorServiceInfo
                                                .getExecutorServicesClass()
                                                .newInstance(),
                                                exeParams.getParams());*/
                                    // Thread.currentThread().setContextClassLoader(oldCL);

                                    //   System.out.println("Written Value="
                                    //         + returnValue.toString());
                                    resultMap.put(key, returnValue);
                                }
                                key.interestOps(SelectionKey.OP_WRITE);
                                //System.out.println("Key interested Ops1");
                            } else if (key.isWritable()) {
                                // the channel is non blocking so keep it
                                // open
                                // till the
                                // count is >=0
                                //System.out.println("In write");
                                ByteArrayOutputStream baos = new ByteArrayOutputStream(); // make
                                // a
                                // BAOS
                                // stream
                                ObjectOutputStream oos = new ObjectOutputStream(baos); // wrap and OOS around the
                                                                                       // stream
                                Object result = resultMap.get(key);
                                oos.writeObject(result); // write an object
                                // to
                                // the stream
                                oos.flush();
                                oos.close();
                                byte[] objData = baos.toByteArray(); // get
                                // the
                                // byte
                                // array
                                baos.close();
                                buffer = ByteBuffer.wrap(objData); // wrap
                                // around
                                // the
                                // data
                                buffer.rewind();
                                // buffer.flip(); //prep for writing
                                //System.out.println(new String(objData));
                                //while (buffer.hasRemaining())
                                clientChannel.write(buffer); // write
                                resultMap.remove(key);
                                buffer.clear();
                                key.cancel();
                                clientChannel.close();
                                //System.out.println("In write1");
                                numberOfServicesRequests++;
                                //System.out.println("Key interested Ops2");
                            }

                        }

                        iterator.remove();
                    } catch (Exception ex) {
                        ex.printStackTrace();
                        key.cancel();
                        clientChannel.close();
                        resultMap.remove(key);
                        //ex.printStackTrace();
                    }

                }

            } catch (Exception ex) {

                //ex.printStackTrace();
            }
        }
    } catch (Exception ex) {
        //ex.printStackTrace();
    }
}

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

protected void addInterest(AbstractSelectableChannel channel, int interest, Object attachment,
        Selector selector) {//from   w w w . j  a v a  2s  . c o m
    try {
        SelectionKey sk = channel.keyFor(selector);
        if (sk != null) {
            if (!sk.isValid())
                return;

            int actualInterests = sk.interestOps();
            if ((actualInterests & interest) != interest)
                sk.interestOps(actualInterests | interest);
            if (attachment != null)
                sk.attach(attachment);
        } else
            channel.register(selector, interest, attachment);
    } catch (ClosedChannelException e) {
        log.warn("Cannot add interest to selector channel : channel is closed");
    }
}

From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java

@Override
public void run() {
    while (!stopped) {
        try {// w w w .  j a  v a 2 s . c om
            int selected = selector.select();
            // if stopped the selector could already be closed which would result in a ClosedSelectorException
            if (selected > 0 && !stopped) {
                Iterator<SelectionKey> selectorKeys = selector.selectedKeys().iterator();
                // if stopped we don't want to modify the keys because close() may still be in progress
                while (selectorKeys.hasNext() && !stopped) {
                    SelectionKey key = selectorKeys.next();
                    selectorKeys.remove();
                    if (!key.isValid()) {
                        continue;
                    }
                    if (key.isAcceptable()) {
                        // Handle new connections coming in
                        final ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                        final SocketChannel socketChannel = channel.accept();
                        // Check for available connections
                        if (currentConnections.incrementAndGet() > maxConnections) {
                            currentConnections.decrementAndGet();
                            logger.warn("Rejecting connection from {} because max connections has been met",
                                    new Object[] { socketChannel.getRemoteAddress().toString() });
                            IOUtils.closeQuietly(socketChannel);
                            continue;
                        }
                        logger.debug("Accepted incoming connection from {}",
                                new Object[] { socketChannel.getRemoteAddress().toString() });
                        // Set socket to non-blocking, and register with selector
                        socketChannel.configureBlocking(false);
                        SelectionKey readKey = socketChannel.register(selector, SelectionKey.OP_READ);

                        // Prepare the byte buffer for the reads, clear it out
                        ByteBuffer buffer = bufferPool.poll();
                        buffer.clear();
                        buffer.mark();

                        // If we have an SSLContext then create an SSLEngine for the channel
                        SSLSocketChannel sslSocketChannel = null;
                        if (sslContext != null) {
                            final SSLEngine sslEngine = sslContext.createSSLEngine();
                            sslEngine.setUseClientMode(false);

                            switch (clientAuth) {
                            case REQUIRED:
                                sslEngine.setNeedClientAuth(true);
                                break;
                            case WANT:
                                sslEngine.setWantClientAuth(true);
                                break;
                            case NONE:
                                sslEngine.setNeedClientAuth(false);
                                sslEngine.setWantClientAuth(false);
                                break;
                            }

                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }

                        // Attach the buffer and SSLSocketChannel to the key
                        SocketChannelAttachment attachment = new SocketChannelAttachment(buffer,
                                sslSocketChannel);
                        readKey.attach(attachment);
                    } else if (key.isReadable()) {
                        // Clear out the operations the select is interested in until done reading
                        key.interestOps(0);
                        // Create a handler based on the protocol and whether an SSLEngine was provided or not
                        final Runnable handler;
                        if (sslContext != null) {
                            handler = handlerFactory.createSSLHandler(key, this, charset, eventFactory, events,
                                    logger);
                        } else {
                            handler = handlerFactory.createHandler(key, this, charset, eventFactory, events,
                                    logger);
                        }

                        // run the handler
                        executor.execute(handler);
                    }
                }
            }
            // Add back all idle sockets to the select
            SelectionKey key;
            while ((key = keyQueue.poll()) != null) {
                key.interestOps(SelectionKey.OP_READ);
            }
        } catch (IOException e) {
            logger.error("Error accepting connection from SocketChannel", e);
        }
    }
}

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

@Override
public void Accepted(NIOClientSocket theSocket) throws IOException {
    SelectionKey clientKey = null;
    TNonblockingTransport client = null;
    try {/*  w ww  .ja  v  a  2s .c o m*/
        // accept the connection
        client = new TNonblockingSocket((SocketChannel) theSocket.getChannel());
        try {
            clientKey = client.registerSelector(eventLoop.getSelector().getSelector(), SelectionKey.OP_READ);
        } catch (IOException e) {
            LOG.error(CCStringUtils.stringifyException(e));
            throw new TTransportException(e);
        }

        // add this key to the map
        ThriftRPCClientChannel frameBuffer = new ThriftRPCClientChannel(this, this, client, clientKey);
        clientKey.attach(frameBuffer);
    } catch (TTransportException tte) {
        // something went wrong accepting.
        LOG.warn("Exception trying to accept!", tte);
        tte.printStackTrace();
        if (clientKey != null)
            cleanupSelectionkey(clientKey);
        if (client != null)
            client.close();
    }
}

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   www .j a v a 2s . 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 .co  m*/
        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);//from  w w w .j  av 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 createNewClientConnection(SelectionKey key) {
    SocketChannel socket = null;//from   ww w . j a  v  a  2  s . co  m
    try {
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        socket = serverSocketChannel.accept();
    } catch (IOException e) {
        LOGGER.error("Cannot accept the connection from a new client", e);
        SystemUtilities.safeClose(socket);
        return;
    }

    SelectionKey newKey;
    try {
        socket.configureBlocking(false);
        newKey = socket.register(selector, SelectionKey.OP_READ);
    } catch (IOException e) {
        LOGGER.error("Cannot add a new client socket to the selector", e);
        SystemUtilities.safeClose(socket);
        return;
    }

    ServerConnection connection = newConnection(newKey);
    newKey.attach(connection);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("[" + threadName + "] New connection from " + connection);
    }
}

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

protected void closeInternal() {
    if (logger.isDebugEnabled())
        logger.debug("Closing remote connection from " + socketChannel.socket());

    try {/*  w ww  .  j av a2  s .  c o m*/
        socketChannel.socket().close();
    } catch (IOException e) {
        if (logger.isEnabledFor(Level.WARN))
            logger.warn(e.getMessage(), e);
    }

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

    SelectionKey selectionKey = socketChannel.keyFor(selector);

    if (selectionKey != null) {
        try {
            selectionKey.attach(null);
            selectionKey.cancel();
        } catch (Exception e) {
            if (logger.isEnabledFor(Level.WARN))
                logger.warn(e.getMessage(), e);
        }
    }

    // close the streams, so we account for comm buffer frees
    IOUtils.closeQuietly(inputStream);
    IOUtils.closeQuietly(outputStream);
}