private void read(SelectionKey key) throws IOException {
        PerfMonMetricGetter getter = null;
        ByteBuffer buf = ByteBuffer.allocateDirect(1024);
        if (key.channel() instanceof SocketChannel) {
            SocketChannel channel = (SocketChannel) key.channel();
            if (channel.read(buf) < 0) {
                log.info("Closing TCP connection");
                channel.close();
                notifyDisonnected();
                return;
            }
            getter = (PerfMonMetricGetter) key.attachment();
        } else if (key.channel() instanceof DatagramChannel) {
            DatagramChannel channel = (DatagramChannel) key.channel();
            SocketAddress remoteAddr = channel.receive(buf);
            if (remoteAddr == null) {
                throw new IOException("Received null datagram");
            }

            synchronized (udpConnections) {
                if (!udpConnections.containsKey(remoteAddr)) {
                    connectUDPClient(remoteAddr, channel, new PerfMonMetricGetter(sigar, this, channel, remoteAddr));
                }
                getter = (PerfMonMetricGetter) udpConnections.get(remoteAddr);
            }
        }

        buf.flip();
        log.debug("Read: " + buf.toString());

        getter.addCommandString(byteBufferToString(buf));
        try {
            while (getter.processNextCommand()) {
                log.debug("Done executing command");
            }
        } catch (Exception e) {
            log.error("Error executing command", e);
        }
    }
private void read ( SelectionKey key ) throws IOException { PerfMonMetricGetter getter = null ; ByteBuffer buf = ByteBuffer . allocateDirect ( 1024 ) ; if ( key . channel ( ) instanceof SocketChannel ) { SocketChannel channel = ( SocketChannel ) key . channel ( ) ; if ( channel . read ( buf ) < 0 ) { log . info ( "Closing TCP connection" ) ; channel . close ( ) ; notifyDisonnected ( ) ; return ; } getter = ( PerfMonMetricGetter ) key . attachment ( ) ; } else if ( key . channel ( ) instanceof DatagramChannel ) { DatagramChannel channel = ( DatagramChannel ) key . channel ( ) ; SocketAddress remoteAddr = channel . receive ( buf ) ; if ( remoteAddr == null ) { throw new IOException ( "Received null datagram" ) ; } synchronized ( udpConnections ) { if ( ! udpConnections . containsKey ( remoteAddr ) ) { connectUDPClient ( remoteAddr , channel , new PerfMonMetricGetter ( sigar , this , channel , remoteAddr ) ) ; } getter = ( PerfMonMetricGetter ) udpConnections . get ( remoteAddr ) ; } } buf . flip ( ) ; log . debug ( "Read: " + buf . toString ( ) ) ; getter . addCommandString ( byteBufferToString ( buf ) ) ; try { while ( getter . processNextCommand ( ) ) { log . debug ( "Done executing command" ) ; } } catch ( Exception e ) { log . error ( "Error executing command" , e ) ; } }
TODO: refactor this code