Example usage for java.nio.channels SelectionKey channel

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

Introduction

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

Prototype

public abstract SelectableChannel channel();

Source Link

Document

Returns the channel for which this key was created.

Usage

From source file:org.sipfoundry.sipxbridge.symmitron.DataShuffler.java

/**
 * Sit in a loop running the following algorthim till exit:
 * //from   w  w  w  .j  av a 2  s.c  o  m
 * <pre>
 * Let Si be a Sym belonging to Bridge B where an inbound packet P is received
 * Increment received packet count for B.
 * Record time for the received packet.
 * Record inboundAddress from where the packet was received
 * send(B,chan,inboundAddress)
 *            
 * </pre>
 * 
 */
public void run() {

    // Wait for an event one of the registered channels
    logger.debug("Starting Shuffler");

    while (true) {
        Bridge bridge = null;
        try {

            if (initializeSelectors.get()) {
                initializeSelector();
            }

            selector.select();

            while (!workQueue.isEmpty()) {
                logger.debug("Got a work item");
                WorkItem workItem = (WorkItem) workQueue.remove(0);
                workItem.doWork();
            }

            // Iterate over the set of keys for which events are
            // available
            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                // The key must be removed or you can get one way audio ( i.e. will read a
                // null byte ).
                // (see issue 2075 ).
                selectedKeys.remove();
                if (!key.isValid()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Discarding packet:Key not valid");
                    }

                    continue;
                }
                if (key.isReadable()) {
                    readBuffer.clear();
                    DatagramChannel datagramChannel = (DatagramChannel) key.channel();
                    if (!datagramChannel.isOpen()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Datagram channel is closed -- discarding packet.");
                        }
                        continue;
                    }
                    bridge = ConcurrentSet.getBridge(datagramChannel);
                    if (bridge == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Discarding packet: Could not find bridge");
                        }
                        continue;
                    }
                    Sym packetReceivedSym = bridge.getReceiverSym(datagramChannel);
                    /*
                     * Note the original hold value and put the transmitter on which this packet was received on hold.
                     */
                    if (packetReceivedSym == null || packetReceivedSym.getTransmitter() == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Could not find sym for inbound channel -- discarding packet");
                        }
                        continue;
                    }
                    boolean holdValue = packetReceivedSym.getTransmitter().isOnHold();
                    packetReceivedSym.getTransmitter().setOnHold(true);

                    InetSocketAddress remoteAddress = (InetSocketAddress) datagramChannel.receive(readBuffer);

                    bridge.pakcetsReceived++;
                    if (bridge.getState() != BridgeState.RUNNING) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Discarding packet: Bridge state is " + bridge.getState());
                        }
                        packetReceivedSym.getTransmitter().setOnHold(holdValue);
                        continue;
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("got something on " + datagramChannel.socket().getLocalPort());
                    }

                    long stamp = getPacketCounter();
                    send(bridge, datagramChannel, remoteAddress, stamp, false);
                    /*
                     * Reset the old value.
                     */
                    packetReceivedSym.getTransmitter().setOnHold(holdValue);

                }
            }
        } catch (Exception ex) {
            logger.error("Unexpected exception occured", ex);
            if (bridge != null && bridge.sessions != null) {
                for (Sym rtpSession : bridge.sessions) {
                    rtpSession.close();
                }
            }
            if (bridge != null)
                bridge.setState(BridgeState.TERMINATED);
            continue;
        }

    }

}

From source file:org.sipfoundry.sipxrelay.DataShuffler.java

/**
 * Sit in a loop running the following algorthim till exit:
 * /*from  w w w.  j  av a  2 s  . com*/
 * <pre>
 * Let Si be a Sym belonging to Bridge B where an inbound packet P is received
 * Increment received packet count for B.
 * Record time for the received packet.
 * Record inboundAddress from where the packet was received
 * send(B,chan,inboundAddress)
 *            
 * </pre>
 * 
 */
public void run() {

    // Wait for an event one of the registered channels
    logger.debug("Starting Shuffler");

    while (true) {
        Bridge bridge = null;
        try {

            if (initializeSelectors.get()) {
                initializeSelector();
            }

            selector.select();

            checkWorkQueue();

            // Iterate over the set of keys for which events are
            // available
            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                // The key must be removed or you can get one way audio ( i.e. will read a
                // null byte ).
                // (see issue 2075 ).
                selectedKeys.remove();
                if (!key.isValid()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Discarding packet:Key not valid");
                    }

                    continue;
                }
                if (key.isReadable()) {
                    readBuffer.clear();
                    DatagramChannel datagramChannel = (DatagramChannel) key.channel();
                    if (!datagramChannel.isOpen()) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Datagram channel is closed -- discarding packet.");
                        }
                        continue;
                    }
                    bridge = ConcurrentSet.getBridge(datagramChannel);
                    if (bridge == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug("DataShuffler: Discarding packet: Could not find bridge");
                        }
                        continue;
                    }
                    Sym packetReceivedSym = bridge.getReceiverSym(datagramChannel);
                    /*
                     * Note the original hold value and put the transmitter on which this packet was received on hold.
                     */
                    if (packetReceivedSym == null || packetReceivedSym.getTransmitter() == null) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Could not find sym for inbound channel -- discarding packet");
                        }
                        continue;
                    }
                    boolean holdValue = packetReceivedSym.getTransmitter().isOnHold();
                    packetReceivedSym.getTransmitter().setOnHold(true);

                    InetSocketAddress remoteAddress = (InetSocketAddress) datagramChannel.receive(readBuffer);

                    bridge.pakcetsReceived++;
                    if (bridge.getState() != BridgeState.RUNNING) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "DataShuffler: Discarding packet: Bridge state is " + bridge.getState());
                        }
                        packetReceivedSym.getTransmitter().setOnHold(holdValue);
                        continue;
                    }
                    if (logger.isTraceEnabled()) {
                        logger.trace("got something on " + datagramChannel.socket().getLocalPort());
                    }

                    long stamp = getPacketCounter();
                    send(bridge, datagramChannel, remoteAddress, stamp, false);
                    /*
                     * Reset the old value.
                     */
                    packetReceivedSym.getTransmitter().setOnHold(holdValue);

                }
            }
        } catch (Exception ex) {
            logger.error("Unexpected exception occured", ex);
            if (bridge != null && bridge.sessions != null) {
                for (Sym rtpSession : bridge.sessions) {
                    rtpSession.close();
                }
            }
            if (bridge != null)
                bridge.setState(BridgeState.TERMINATED);
            continue;
        }

    }

}

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

public void run() {
    try {/*from w w w  . j  av  a2 s. co m*/
        createSocket();

        synchronized (socketCreatedLock) {
            socketCreated = true;
            socketCreatedLock.notifyAll();
        }

        while (!stop) {
            int nbKeys = 0;
            try {
                nbKeys = selector.select();
            } catch (IOException e) {
                LOGGER.error(e);
            }

            if (nbKeys > 0) {
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();

                    if (key.isAcceptable()) {
                        createNewClientConnection(key);
                    } else if (key.isWritable()) {
                        long startTime = System.nanoTime();
                        readyToSend(key);
                        timeSending += System.nanoTime() - startTime;
                    } else if (key.isReadable()) {
                        long startTime = System.nanoTime();
                        readyToReceive(key);
                        timeReceiving += System.nanoTime() - startTime;
                    }

                    it.remove();
                }
            }
        }
    } catch (RuntimeException ex) {
        LOGGER.error("The MultiplexedServer [" + threadName + "] caught an unexpected exception.", ex);
        fatalErrorReporter.report(ex);
    } finally {
        if (selector != null) {
            for (SelectionKey key : selector.keys()) {
                SystemUtilities.safeClose(key.channel());
            }
            SystemUtilities.safeClose(selector);
        }

        LOGGER.info("[" + threadName + "] inTime=" + UnitUtilities.toElapsedNanoTime(timeReceiving)
                + " outTime=" + UnitUtilities.toElapsedNanoTime(timeSending) + " in=" + nbBytesReceived
                + "B out=" + UnitUtilities.toComputerSize(nbBytesSent) + "B inNb=" + nbReceived + " outNb="
                + nbSent);
    }
}

From source file:Proxy.java

/** We handle only non-SSL connections */
void loop(Selector selector) {
    Set ready_keys;/*from  w  w w .ja va  2 s  .com*/
    SelectionKey key;
    ServerSocketChannel srv_sock;
    SocketChannel in_sock, out_sock;
    InetSocketAddress src, dest;

    while (true) {
        if (verbose)
            log("[Proxy] ready to accept connection");

        // 4. Call Selector.select()
        try {
            selector.select();

            // get set of ready objects
            ready_keys = selector.selectedKeys();
            for (Iterator it = ready_keys.iterator(); it.hasNext();) {
                key = (SelectionKey) it.next();
                it.remove();

                if (key.isAcceptable()) {
                    srv_sock = (ServerSocketChannel) key.channel();
                    // get server socket and attachment
                    src = (InetSocketAddress) key.attachment();
                    in_sock = srv_sock.accept(); // accept request
                    if (verbose)
                        log("Proxy.loop()", "accepted connection from " + toString(in_sock));
                    dest = (InetSocketAddress) mappings.get(src);
                    // find corresponding dest
                    if (dest == null) {
                        in_sock.close();
                        log("Proxy.loop()", "did not find a destination host for " + src);
                        continue;
                    } else {
                        if (verbose)
                            log("Proxy.loop()",
                                    "relaying traffic from " + toString(src) + " to " + toString(dest));
                    }

                    // establish connection to destination host
                    try {
                        out_sock = SocketChannel.open(dest);
                        // uses thread pool (Executor) to handle request, closes socks at end
                        handleConnection(in_sock, out_sock);
                    } catch (Exception ex) {
                        in_sock.close();
                        throw ex;
                    }
                }
            }
        } catch (Exception ex) {
            log("Proxy.loop()", "exception: " + ex);
        }
    }
}

From source file:Proxy.java

void _handleConnection(final SocketChannel in_channel, final SocketChannel out_channel) throws Exception {
    executor.execute(new Runnable() {
        public void run() {
            Selector sel = null;//from  w w  w  .jav a 2  s.  c o m
            SocketChannel tmp;
            Set ready_keys;
            SelectionKey key;
            ByteBuffer transfer_buf = ByteBuffer.allocate(BUFSIZE);

            try {
                sel = Selector.open();
                in_channel.configureBlocking(false);
                out_channel.configureBlocking(false);
                in_channel.register(sel, SelectionKey.OP_READ);
                out_channel.register(sel, SelectionKey.OP_READ);

                while (sel.select() > 0) {
                    ready_keys = sel.selectedKeys();
                    for (Iterator it = ready_keys.iterator(); it.hasNext();) {
                        key = (SelectionKey) it.next();
                        it.remove(); // remove current entry (why ?)
                        tmp = (SocketChannel) key.channel();
                        if (tmp == null) {
                            log("Proxy._handleConnection()", "attachment is null, continuing");
                            continue;
                        }
                        if (key.isReadable()) { // data is available to be read from tmp
                            if (tmp == in_channel) {
                                // read all data from in_channel and forward it to out_channel (request)
                                if (relay(tmp, out_channel, transfer_buf) == false)
                                    return;
                            }
                            if (tmp == out_channel) {
                                // read all data from out_channel and forward it 
                                // to in_channel (response)
                                if (relay(tmp, in_channel, transfer_buf) == false)
                                    return;
                            }
                        }
                    }
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                close(sel, in_channel, out_channel);
            }
        }
    });
}

From source file:jp.queuelinker.system.net.SelectorThread.java

@Override
public void run() {
    ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
    // I believe the inner try-catches does not cause overhead.
    // http://stackoverflow.com/questions/141560/
    long sendCount = 0;

    SocketChannel currentChannel;
    SelectionKey key = null;
    while (true) {
        try {/* w  w w  .j  ava 2 s  . c  om*/
            selector.select();
            // selector.selectNow();
        } catch (ClosedSelectorException e) {
            logger.fatal("BUG: The selector is closed.");
            return;
        } catch (IOException e) {
            logger.fatal("An IOException occured while calling select().");
            // Fatal Error. Notify the error to the users and leave the matter to them.
            for (ChannelState state : channels) {
                state.callBack.fatalError();
            }
            return;
        }

        if (!requests.isEmpty()) {
            handleRequest();
            continue;
        }

        if (stopRequested) {
            return;
        }

        Set<SelectionKey> keys = selector.selectedKeys();

        Iterator<SelectionKey> iter = keys.iterator();
        iter_loop: while (iter.hasNext()) {
            key = iter.next();
            iter.remove(); // Required. Don't remove.

            if (key.isReadable()) {
                currentChannel = (SocketChannel) key.channel();
                final ChannelState state = (ChannelState) key.attachment();

                int valid;
                try {
                    valid = currentChannel.read(buffer);
                } catch (IOException e) {
                    logger.warn("An IOException happened while reading from a channel.");
                    state.callBack.exceptionOccured(state.channelId, state.attachment);
                    key.cancel();
                    continue;
                }
                if (valid == -1) {
                    // Normal socket close?
                    state.callBack.exceptionOccured(state.channelId, state.attachment);
                    // cleanUpChannel(state.channelId);
                    key.cancel();
                    continue;
                }

                buffer.rewind();
                if (state.callBack.receive(state.channelId, buffer, valid, state.attachment) == false) {
                    state.key.interestOps(state.key.interestOps() & ~SelectionKey.OP_READ);
                }
                buffer.clear();
            } else if (key.isWritable()) {
                currentChannel = (SocketChannel) key.channel();
                final ChannelState state = (ChannelState) key.attachment();

                while (state.sendBuffer.readableSize() < WRITE_SIZE) {
                    ByteBuffer newBuffer = state.callBack.send(state.channelId, state.attachment);
                    if (newBuffer != null) {
                        state.sendBuffer.write(newBuffer);
                        if (++sendCount % 50000 == 0) {
                            logger.info("Send Count: " + sendCount);
                        }
                    } else if (state.sendBuffer.readableSize() == 0) {
                        key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
                        continue iter_loop;
                    } else {
                        break;
                    }
                }

                final int available = state.sendBuffer.readableSize();
                if (available >= WRITE_SIZE || ++state.noopCount >= HEURISTIC_WAIT) {
                    int done;
                    try {
                        done = currentChannel.write(state.sendBuffer.getByteBuffer());
                    } catch (IOException e) {
                        logger.warn("An IOException occured while writing to a channel.");
                        state.callBack.exceptionOccured(state.channelId, state.attachment);
                        key.cancel();
                        continue;
                    }
                    if (done < available) {
                        state.sendBuffer.rollback(available - done);
                    }
                    state.sendBuffer.compact();
                    state.noopCount = 0;
                }
            } else if (key.isAcceptable()) {
                ServerSocketChannel channel = (ServerSocketChannel) key.channel();
                ChannelState state = (ChannelState) key.attachment();
                SocketChannel socketChannel;
                try {
                    socketChannel = channel.accept();
                    socketChannel.configureBlocking(false);
                } catch (IOException e) {
                    continue; // Do nothing.
                }
                state.callBack.newConnection(state.channelId, socketChannel, state.attachment);
            }
        }
    }
}

From source file:x10.x10rt.yarn.ApplicationMaster.java

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {//from   www  .  j ava2 s. c  om
            SelectionKey key;
            // check for previously unhandled events
            if (events != null && events.hasNext()) {
                key = events.next();
                events.remove();
            } else if (selector.select() == 0) // check for new events
                continue; // nothing to process, go back and block on select again
            else { // select returned some events
                events = selector.selectedKeys().iterator();
                key = events.next();
                events.remove();
            }

            // process the selectionkey
            if (key.isAcceptable()) {
                LOG.info("New connection from X10 detected");
                // accept any connections on the server socket, and look for things to read from it
                ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
                SocketChannel sc = ssc.accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();

                ByteBuffer incomingMsg;
                if (pendingReads.containsKey(sc))
                    incomingMsg = pendingReads.remove(sc);
                else
                    incomingMsg = ByteBuffer.allocateDirect(headerLength).order(ByteOrder.nativeOrder());

                LOG.info("Reading message from X10");
                try {
                    if (sc.read(incomingMsg) == -1) {
                        // socket closed
                        sc.close();
                        key.cancel();
                        pendingReads.remove(sc);
                    } else if (incomingMsg.hasRemaining()) {
                        LOG.info("Message header partially read. " + incomingMsg.remaining()
                                + " bytes remaining");
                        pendingReads.put(sc, incomingMsg);
                    } else { // buffer is full
                        if (incomingMsg.capacity() == headerLength) {
                            // check to see if there is a body associated with this message header
                            int datalen = incomingMsg.getInt(headerLength - 4);
                            //System.err.println("Byte order is "+incomingMsg.order()+" datalen="+datalen);
                            if (datalen == 0)
                                processMessage(incomingMsg, sc);
                            else { // create a larger array to hold the header+body
                                ByteBuffer newBuffer = ByteBuffer.allocateDirect(headerLength + datalen)
                                        .order(ByteOrder.nativeOrder());
                                incomingMsg.rewind();
                                newBuffer.put(incomingMsg);
                                incomingMsg = newBuffer;
                                sc.read(incomingMsg); // read in the body, if available
                                if (incomingMsg.hasRemaining()) {
                                    LOG.info("Message partially read. " + incomingMsg.remaining()
                                            + " bytes remaining");
                                    pendingReads.put(sc, incomingMsg);
                                } else
                                    processMessage(incomingMsg, sc);
                            }
                        }
                    }
                } catch (IOException e) {
                    LOG.warn("Error reading in message from socket channel", e);
                }
            }
        } catch (IOException e) {
            LOG.warn("Error handling X10 links", e);
        }
    }
}

From source file:middleware.NewServerSocket.java

public void run() {
    int count = 0;
    while (!sharedData.isEndOfProgram()) {

        try {//from  w  w w.j  ava  2  s .  c  o m
            if (monitoring) {
                selector.select(10);
            } else {
                selector.select();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

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

            if (key.isAcceptable()) {
                if (key.channel() == serverSocketChannel) {
                    SocketChannel socketChannel = null;
                    try {
                        socketChannel = serverSocketChannel.accept();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    if (socketChannel != null) {

                        MiddleClient middleClient = new MiddleClient(sharedData.getServerIpAddr(),
                                sharedData.getServerPortNum());
                        middleClient.startClient();

                        MiddleServer middleServer = new MiddleServer(socketChannel);
                        TransactionData transactionData = new TransactionData(sharedData, middleServer);
                        middleServer.startServer(transactionData);

                        int len = 0;
                        buffer.clear();
                        len = middleClient.getInput(buffer);
                        middleServer.sendOutput(buffer, len);

                        buffer.clear();
                        len = middleServer.getInput(buffer);
                        transactionData.setUserId(getUserId(data));
                        middleClient.sendOutput(buffer, len);

                        middleServer.setNonBlocking();
                        middleClient.setNonBlocking();

                        if (sharedData.isOutputToFile()) {
                            transactionData.openFileOutputStream();
                        }

                        sharedData.allTransactionData.add(transactionData);

                        workers[count % numWorkers].socketMap.put(middleServer.socketChannel, middleServer);
                        workers[count % numWorkers].socketMap.put(middleClient.socketChannel, middleClient);

                        middleServer.register(workers[count % numWorkers].selector, middleClient);

                        middleClient.register(workers[count % numWorkers].selector, middleServer);

                        ++count;
                    }
                } else if (key.channel() == adminServerSocketChannel) {
                    SocketChannel sock = null;
                    try {
                        sock = adminServerSocketChannel.accept();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (sock != null) {
                        try {
                            sock.configureBlocking(true);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        MiddleSocketChannel middleSocketChannel = new MiddleSocketChannel(sock);
                        middleSocketChannel.setNonBlocking();

                        middleSocketChannel.register(selector, middleSocketChannel);

                    }
                }
            } else if (key.isReadable()) {
                MiddleSocketChannel middleSocketChannel = (MiddleSocketChannel) key.attachment();

                buffer.clear();
                int len = middleSocketChannel.getInput(buffer);
                if (len == -1) {
                    middleSocketChannel.cancelKey();
                    continue;
                }
                buffer.position(0);

                int packetID = 0;
                long packetLength = -1;
                boolean isValidPacket = true;

                try {
                    packetID = buffer.getInt();
                    packetLength = buffer.getLong();
                } catch (BufferUnderflowException e) {
                    buffer.clear();
                    buffer.putInt(102);
                    String response = "Invalid packet header";
                    buffer.putLong(response.length());
                    buffer.put(response.getBytes());
                    isValidPacket = false;
                    middleSocketChannel.sendOutput(buffer, buffer.position());
                }

                if (isValidPacket) {
                    if (packetID == 100) {
                        if (userList.contains(middleSocketChannel)) {
                            buffer.clear();
                            buffer.putInt(102);
                            String response = "You have already logged in";
                            buffer.putLong(response.length());
                            buffer.put(response.getBytes());
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        } else if (packetLength <= 0) {
                            buffer.clear();
                            buffer.putInt(102);
                            String response = "Invalid packet length";
                            buffer.putLong(response.length());
                            buffer.put(response.getBytes());
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        } else {
                            String userID = null;
                            byte[] password = new byte[Encrypt.MAX_LENGTH];
                            byte[] packet = new byte[(int) packetLength];
                            buffer.get(packet);
                            userID = parseLogInPacket(packet, password);
                            if (userInfo.get(userID) != null && Arrays.equals(((byte[]) userInfo.get(userID)),
                                    Encrypt.encrypt(password))) {
                                buffer.clear();
                                buffer.putInt(101);
                                buffer.putLong(0);
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                                userList.add(middleSocketChannel);
                            } else {
                                buffer.clear();
                                buffer.putInt(102);
                                String response = "Invalid User ID or password";
                                buffer.putLong(response.length());
                                buffer.put(response.getBytes());
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                            }
                        }
                    } else if (packetID == 103) {
                        stopIncrementalLogging();
                    } else if (packetID == 200) {
                        if (userList.contains(middleSocketChannel)) {
                            if (sharedData.isOutputToFile() || endingMonitoring || sendingFiles) {
                                String response = "Current monitoring not finished";
                                buffer.clear();
                                buffer.putInt(202);
                                buffer.putLong(response.length());
                                buffer.put(response.getBytes());
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                            } else {
                                startMonitoring();
                                buffer.clear();
                                buffer.putInt(201);
                                buffer.putLong(0);
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                                curUser = middleSocketChannel;
                            }
                        } else {
                            buffer.clear();
                            buffer.putInt(102);
                            String response = "You have not been registered";
                            buffer.putLong(response.length());
                            buffer.put(response.getBytes());
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        }

                    } else if (packetID == 300) {
                        if (userList.contains(middleSocketChannel)) {
                            if (!sharedData.isOutputToFile()) {
                                String response = "No monitoring running";
                                buffer.clear();
                                buffer.putInt(302);
                                buffer.putLong(response.length());
                                buffer.put(response.getBytes());
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                                // DY : I think this use case is not right at the moment where
                                // monitoring is only stoppable by a user who started it.
                                //                } else if (middleSocketChannel != curUser) {
                                //                  String response = "Monitoring running by other user";
                                //                  buffer.clear();
                                //                  buffer.putInt(302);
                                //                  buffer.putLong(response.length());
                                //                  buffer.put(response.getBytes());
                                //                  middleSocketChannel.sendOutput(buffer, buffer.position());
                            } else if (endingMonitoring) {
                                String response = "Writing log files, please wait";
                                buffer.clear();
                                buffer.putInt(302);
                                buffer.putLong(response.length());
                                buffer.put(response.getBytes());
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                            } else {
                                sendLog = true;
                                curUser = middleSocketChannel;
                                stopMonitoring();
                            }
                        } else {
                            buffer.clear();
                            buffer.putInt(102);
                            String response = "You have not been registered";
                            buffer.putLong(response.length());
                            buffer.put(response.getBytes());
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        }
                    } else if (packetID == 303) {
                        if (userList.contains(middleSocketChannel)) {
                            if (!sharedData.isOutputToFile()) {
                                String response = "No monitoring running";
                                buffer.clear();
                                buffer.putInt(302);
                                buffer.putLong(response.length());
                                buffer.put(response.getBytes());
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                                //                } else if (middleSocketChannel != curUser) {
                                //                  String response = "Monitoring running by other user";
                                //                  buffer.clear();
                                //                  buffer.putInt(302);
                                //                  buffer.putLong(response.length());
                                //                  buffer.put(response.getBytes());
                                //                  middleSocketChannel.sendOutput(buffer, buffer.position());
                            } else if (endingMonitoring) {
                                String response = "Writing log files, please wait";
                                buffer.clear();
                                buffer.putInt(302);
                                buffer.putLong(response.length());
                                buffer.put(response.getBytes());
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                            } else {
                                sendLog = false;
                                stopMonitoring();
                            }
                        } else {
                            buffer.clear();
                            buffer.putInt(102);
                            String response = "You have not been registered";
                            buffer.putLong(response.length());
                            buffer.put(response.getBytes());
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        }

                    } else if (packetID == 400) {
                        if (userList.contains(middleSocketChannel)) {
                            // when the GUI reconnects and the middleware is still monitoring...
                            if (monitoring) {

                                // start new logging threads and resume monitoring
                                stopIncrementalLogging();
                                startIncrementalLogging(true);

                                buffer.clear();
                                buffer.putInt(402);
                                buffer.putLong(0);
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                            } else {
                                buffer.clear();
                                buffer.putInt(401);
                                buffer.putLong(0);
                                middleSocketChannel.sendOutput(buffer, buffer.position());
                            }
                        } else {
                            buffer.clear();
                            buffer.putInt(102);
                            String response = "You have not been registered";
                            buffer.putLong(response.length());
                            buffer.put(response.getBytes());
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        }

                    } else if (packetID == 500) {
                        if (!sharedData.isLiveMonitoring()) {
                            buffer.clear();
                            buffer.putInt(501);
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        } else {
                            buffer.clear();
                            buffer.putInt(502);
                            LiveAggregateGlobal globalAggregate = sharedData.liveMonitor.globalAggregate;
                            int numTransactionType = globalAggregate.getNumTransactionType();
                            buffer.putInt(numTransactionType);
                            buffer.putDouble(globalAggregate.totalTransactionCount);
                            for (int i = 0; i < numTransactionType; ++i) {
                                buffer.putDouble(
                                        globalAggregate.transactionStatistics.get(i).currentTransactionCounts); // current TPS
                                buffer.putDouble(
                                        globalAggregate.transactionStatistics.get(i).currentAverageLatency); // current average latency.
                                buffer.putDouble(
                                        globalAggregate.transactionStatistics.get(i).totalTransactionCounts); // total transaction count
                            }
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        }
                    } else if (packetID == 600) {
                        int type = buffer.getInt();
                        int index = buffer.getInt();
                        String[] samples = sharedData.liveMonitor.getTransactionSamples(type);
                        if (samples == null) {
                            buffer.clear();
                            buffer.putInt(601);
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        } else if (samples.length < index + 1) {
                            buffer.clear();
                            buffer.putInt(601);
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        } else {
                            String sample = samples[index];
                            buffer.clear();
                            buffer.putInt(602);
                            buffer.putLong(sample.length());
                            buffer.put(sample.getBytes());
                            middleSocketChannel.sendOutput(buffer, buffer.position());
                        }
                    } else if (packetID == 700) {
                        int type = buffer.getInt();
                        sharedData.liveMonitor.removeTransactionType(type);
                        buffer.clear();
                        buffer.putInt(701);
                        buffer.putInt(sharedData.liveMonitor.globalAggregate.getNumTransactionType());
                        middleSocketChannel.sendOutput(buffer, buffer.position());
                    } else {
                        buffer.clear();
                        buffer.putInt(102);
                        String response = "Invalid packet ID";
                        buffer.putLong(response.length());
                        buffer.put(response.getBytes());
                        middleSocketChannel.sendOutput(buffer, buffer.position());
                    }
                }
            }
        }

        if (!sharedData.allTransactions.isEmpty() || !sharedData.allQueries.isEmpty()) {
            int c = sharedData.allQueries.size();
            while (c > 0) {
                printQueries();
                --c;
            }
            // c = sharedData.allStatementsInfo.size();
            // while (c > 0) {
            // printStatementsInfo();
            // --c;
            // }
            c = sharedData.allTransactions.size();
            while (c > 0) {
                printTransactions();
                --c;
            }
        } else if (endingMonitoring) {
            try {
                sharedData.tAllLogFileOutputStream.flush();
                sharedData.tAllLogFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                sharedData.sAllLogFileOutputStream.flush();
                sharedData.sAllLogFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                sharedData.qAllLogFileOutputStream.flush();
                sharedData.qAllLogFileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (curUser != null && sendLog) {

                //          System.out.println("ready to compress log files");

                if (stopRemoteDstat != null) {
                    Interrupter interrupter = new Interrupter(Thread.currentThread());
                    interrupter.start();
                    try {
                        stopRemoteDstat.waitFor();
                        interrupter.setOuterThreadWaiting(false);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    stopRemoteDstat = null;
                }
                buffer.clear();
                buffer.putInt(301);
                buffer.putLong(0);
                curUser.sendOutput(buffer, buffer.position());

                //          if (zipAllFiles()) {
                //
                //            System.out
                //                .println("finish compressing files, ready to send zip file");
                //
                //            File zipFile = new File(zipFileName);
                //
                //            FileInputStream fis = null;
                //            try {
                //              fis = new FileInputStream(zipFile);
                //            } catch (FileNotFoundException e) {
                //              e.printStackTrace();
                //            }
                //
                //            FileChannel fc = fis.getChannel();
                //
                //            buffer.clear();
                //            buffer.putInt(301);
                //            buffer.putLong(zipFile.length());
                //            curUser.sendOutput(buffer, buffer.position());
                //            long position = 0;
                //            long remaining = zipFile.length();
                //            long len = 0;
                //            while (remaining > 0) {
                //              try {
                //               len = fc.transferTo(position, 1024, curUser.socketChannel);
                //              } catch (IOException e) {
                //                e.printStackTrace();
                //              }
                //              position += len;
                //              remaining -= len;
                //              len = 0;
                //            }
                //
                //            System.out.println("finish sending zip file");
                //
                //          } else {
                //            String response = "fail to compress log files";
                //            buffer.clear();
                //            buffer.putInt(302);
                //            buffer.putLong(response.length());
                //            buffer.put(response.getBytes());
                //            curUser.sendOutput(buffer, buffer.position());
                //          }
                curUser = null;
            }

            endingMonitoring = false;
            monitoring = false;
            if (System.getProperty("user.name").contentEquals("root")) {
                String[] cmd = { "/bin/bash", "shell/chmod" };
                try {
                    Runtime.getRuntime().exec(cmd);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }

    }

}

From source file:com.openteach.diamond.network.waverider.network.DefaultNetWorkServer.java

private void dispatch() throws IOException {
    logger.debug("try dispatch");
    SelectionKey key = null;
    for (SocketChannelOPSChangeRequest request : opsChangeRequstMap.values()) {
        key = request.getChannel().keyFor(selector);
        if (key != null) {
            // /*from  ww w  . j a  v a2  s .  c o  m*/
            if ((request.getOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
                key.interestOps(SelectionKey.OP_WRITE);
                request.clearOps(SelectionKey.OP_WRITE);
            } else if ((request.getOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
                key.interestOps(SelectionKey.OP_READ);
                request.clearOps(SelectionKey.OP_READ);
            }
        }
    }

    isWeakuped.set(false);
    if (selector.select(WaveriderConfig.WAVERIDER_DEFAULT_NETWORK_TIME_OUT) <= 0) {
        return;
    }

    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
    while (iterator.hasNext()) {
        key = (SelectionKey) iterator.next();
        iterator.remove();
        try {
            if (!key.isValid()) {
                continue;
            } else if (key.isAcceptable()) {
                onAccept(key);
            } else if (key.isReadable()) {
                //readerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_READ));
                onRead(key);
            } else if (key.isWritable()) {
                //writerExecutor.execute(new NetworkTask(key, NETWORK_OPERATION_WRITE));
                onWrite(key);
            }
        } catch (IOException e) {
            // 
            opsChangeRequstMap.remove((SocketChannel) key.channel());
            Session session = (Session) key.attachment();
            if (session != null) {
                session.onException(e);
                // Session
                sessionManager.freeSession(session);
            }
            key.cancel();
            key.channel().close();
            e.printStackTrace();
            logger.error("OOPSException", e);
        }
    }
}

From source file:org.openhab.binding.tcp.AbstractDatagramChannelBinding.java

/**
 * @{inheritDoc}//from  w w w .j a  va2  s  .c o m
 */
@Override
protected void execute() {

    // Cycle through the Items and setup channels if required
    for (P provider : providers) {
        for (String itemName : provider.getItemNames()) {
            for (Command aCommand : ((P) provider).getAllCommands(itemName)) {

                String remoteHost = ((P) provider).getHost(itemName, aCommand);
                String remotePort = ((P) provider).getPortAsString(itemName, aCommand);
                Direction direction = ((P) provider).getDirection(itemName, aCommand);

                InetSocketAddress remoteAddress = null;
                if (!(remoteHost.equals("*") || remotePort.equals("*"))) {
                    remoteAddress = new InetSocketAddress(remoteHost, Integer.parseInt(remotePort));
                }

                Channel newChannel = null;
                Channel existingChannel = null;

                if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                    newChannel = new Channel(itemName, aCommand, remoteHost, remotePort,
                            ((P) provider).getDirection(itemName, aCommand), false, null, false, null);
                    existingChannel = channels.get(itemName, aCommand, direction, remoteHost, remotePort);
                } else {
                    newChannel = new Channel(itemName, aCommand, remoteAddress,
                            ((P) provider).getDirection(itemName, aCommand), false, null, false, null);
                    existingChannel = channels.get(itemName, aCommand, direction, remoteAddress);
                }

                if (existingChannel == null) {
                    if (direction == Direction.IN) {

                        boolean assigned = false;

                        if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                            logger.warn(
                                    "When using address masks we will not verify if we are already listening to similar incoming connections");
                            logger.info("We will accept data coming from the remote end {}:{}", remoteHost,
                                    remotePort);
                        } else {
                            if (channels.contains(itemName, aCommand, Direction.IN, remoteAddress)) {
                                logger.warn("We already listen for incoming connections from {}",
                                        remoteAddress);
                            } else {

                                if (itemShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(itemName, direction,
                                            remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }

                                if (bindingShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(direction, remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }

                                if (directionsShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }
                            }
                        }

                        if (!assigned) {
                            newChannel.channel = listenerChannel;
                        }

                        if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                            logger.info("We will accept data coming from the remote end with mask {}:{}",
                                    remoteHost, remotePort);
                        } else {
                            logger.info("We will accept data coming from the remote end {}", remoteAddress);
                        }
                        logger.debug("Setting up the inbound channel {}", newChannel);
                        channels.add(newChannel);

                    } else if (direction == Direction.OUT) {

                        boolean assigned = false;

                        if (useAddressMask && (remoteHost.equals("*") || remotePort.equals("*"))) {
                            logger.error(
                                    "We do not accept outgoing connections for Items that do use address masks");
                        } else {

                            channels.add(newChannel);

                            if (newChannel.channel == null) {

                                if (itemShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(itemName, direction,
                                            remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }

                                if (bindingShareChannels) {
                                    Channel firstChannel = channels.getFirstServed(direction, remoteAddress);
                                    if (firstChannel != null) {
                                        newChannel.channel = firstChannel.channel;
                                        assigned = true;
                                    }
                                }

                                // I think it is better not to share incoming connections with outgoing connections (in the case of the 
                                // UDP binding)

                                //               if(directionsShareChannels) {
                                //                  Channel firstChannel = channels.getFirstServed(remoteAddress);
                                //                  if(firstChannel != null) {
                                //                     newChannel.channel = firstChannel.channel;
                                //                     assigned = true;
                                //                  }               
                                //   

                                if (assigned) {
                                    logger.debug("Setting up the outbound assigned channel {} ", newChannel);
                                }
                            }

                            synchronized (this) {

                                if (!assigned || newChannel.channel == null) {

                                    DatagramChannel newDatagramChannel = null;
                                    try {
                                        newDatagramChannel = DatagramChannel.open();
                                    } catch (IOException e2) {
                                        logger.error("An exception occurred while opening a channel: {}",
                                                e2.getMessage());
                                    }

                                    try {
                                        newDatagramChannel.configureBlocking(false);
                                        //setKeepAlive(true);
                                    } catch (IOException e) {
                                        logger.error("An exception occurred while configuring a channel: {}",
                                                e.getMessage());
                                    }

                                    synchronized (selector) {
                                        selector.wakeup();
                                        try {
                                            newDatagramChannel.register(selector,
                                                    newDatagramChannel.validOps());
                                        } catch (ClosedChannelException e1) {
                                            logger.error(
                                                    "An exception occurred while registering a selector: {}",
                                                    e1.getMessage());
                                        }
                                    }

                                    newChannel.channel = newDatagramChannel;
                                    logger.debug("Setting up the outbound channel {}", newChannel);

                                    try {
                                        logger.info("'Connecting' the channel {} ", newChannel);
                                        newDatagramChannel.connect(remoteAddress);
                                    } catch (IOException e) {
                                        logger.error("An exception occurred while connecting a channel: {}",
                                                e.getMessage());
                                    }
                                } else {
                                    logger.info("There is already an active channel {} for the remote end {}",
                                            newChannel.channel, newChannel.remote);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    // Check on channels for which we have to process data
    synchronized (selector) {
        try {
            // Wait for an event
            selector.selectNow();
        } catch (IOException e) {
            logger.error("An exception occurred while Selecting ({})", e.getMessage());
        }
    }

    // Get list of selection keys with pending events
    Iterator<SelectionKey> it = selector.selectedKeys().iterator();

    // Process each key at a time
    while (it.hasNext()) {
        SelectionKey selKey = (SelectionKey) it.next();
        it.remove();

        if (selKey.isValid()) {
            DatagramChannel theDatagramChannel = (DatagramChannel) selKey.channel();
            Channel theChannel = channels.get(theDatagramChannel);

            if (selKey.isReadable()) {
                InetSocketAddress clientAddress = null;
                ByteBuffer readBuffer = ByteBuffer.allocate(maximumBufferSize);
                int numberBytesRead = 0;
                boolean error = false;

                if (selKey == listenerKey) {
                    try {
                        clientAddress = (InetSocketAddress) theDatagramChannel.receive(readBuffer);
                        logger.debug("Received {} on the listener port from {}", new String(readBuffer.array()),
                                clientAddress);
                        numberBytesRead = readBuffer.position();
                    } catch (Exception e) {
                        error = true;
                    }

                } else {

                    try {
                        //TODO: Additional code to split readBuffer in multiple parts, in case the data send by the remote end is not correctly fragemented. Could be handed of to implementation class if for example, the buffer needs to be split based on a special character like line feed or carriage return
                        numberBytesRead = theDatagramChannel.read(readBuffer);
                        logger.debug("Received {} bytes ({}) on the channel {}->{}",
                                new Object[] { numberBytesRead, new String(readBuffer.array()),
                                        theDatagramChannel.getLocalAddress(),
                                        theDatagramChannel.getRemoteAddress() });
                    } catch (NotYetConnectedException e) {
                        try {
                            logger.warn("The channel for {} has no connection pending ({})",
                                    theDatagramChannel.getRemoteAddress(), e.getMessage());
                        } catch (IOException e1) {
                            logger.error(
                                    "An exception occurred while getting the remote address of channel {} ({})",
                                    theDatagramChannel, e1.getMessage());
                        }
                        error = true;
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        try {
                            logger.warn("The channel for {} has encountered an unknown IO Exception: {}",
                                    theDatagramChannel.getRemoteAddress(), e.getMessage());
                        } catch (IOException e1) {
                            logger.error(
                                    "An exception occurred while getting the remote address of channel {} ({})",
                                    theDatagramChannel, e1.getMessage());
                        }
                        error = true;
                    }
                }

                if (numberBytesRead == -1) {
                    try {
                        if (selKey != listenerKey) {
                            theDatagramChannel.close();
                        }
                    } catch (IOException e) {
                        try {
                            logger.warn("The channel for {} is closed ({})",
                                    theDatagramChannel.getRemoteAddress(), e.getMessage());
                        } catch (IOException e1) {
                            logger.error(
                                    "An exception occurred while getting the remote address of channel {} ({})",
                                    theDatagramChannel, e1.getMessage());
                        }
                    }
                    error = true;
                }

                if (error) {
                    if (selKey != listenerKey) {

                        Scheduler scheduler = null;
                        try {
                            scheduler = StdSchedulerFactory.getDefaultScheduler();
                        } catch (SchedulerException e1) {
                            logger.error("An exception occurred while getting the Quartz scheduler: {}",
                                    e1.getMessage());
                        }

                        JobDataMap map = new JobDataMap();
                        map.put("Channel", theChannel);
                        map.put("Binding", this);

                        JobDetail job = null;
                        Trigger trigger = null;

                        job = newJob(ReconnectJob.class)
                                .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-"
                                        + Long.toString(System.currentTimeMillis()), this.toString())
                                .usingJobData(map).build();

                        trigger = newTrigger()
                                .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-"
                                        + Long.toString(System.currentTimeMillis()), this.toString())
                                .startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();

                        try {
                            if (job != null && trigger != null && selKey != listenerKey) {
                                if (!theChannel.isReconnecting) {
                                    channels.setAllReconnecting(theDatagramChannel, true);
                                    scheduler.scheduleJob(job, trigger);
                                }
                            }
                        } catch (SchedulerException e) {
                            logger.error(
                                    "An exception occurred while scheduling a job with the Quartz Scheduler {}",
                                    e.getMessage());
                        }
                    }

                } else {

                    ArrayList<Channel> channelsToServe = new ArrayList<Channel>();

                    if (selKey == listenerKey) {
                        channelsToServe = channels.getAll(Direction.IN, clientAddress);
                        if (channelsToServe.size() == 0) {
                            logger.warn(
                                    "Received data {} from an undefined remote end {}. We will not process it",
                                    new String(readBuffer.array()), clientAddress);
                        }
                    } else {
                        channelsToServe = channels.getAll(theDatagramChannel);
                    }

                    if (channelsToServe.size() > 0) {

                        readBuffer.flip();

                        if (channels.isBlocking(theDatagramChannel)) {
                            // if we are in a blocking operation, we get are now finished and we have to reset the flag. The read buffer will be returned to the instance
                            // that initiated the write opreation - it has to parse the buffer itself

                            //find the Channel with this DGC that is holding a Blocking flag
                            theChannel = channels.getBlocking(theDatagramChannel);
                            theChannel.buffer = readBuffer;

                        } else {
                            for (Channel aChannel : channelsToServe) {
                                if (useAddressMask) {
                                    aChannel.lastRemote = clientAddress;
                                }
                                // if not, then we parse the buffer as ususal
                                parseChanneledBuffer(aChannel, readBuffer);
                            }
                        }
                    } else {
                        try {
                            if (selKey == listenerKey) {
                                logger.warn(
                                        "No channel is active or defined for the data we received from {}. It will be discarded.",
                                        clientAddress);
                            } else {
                                logger.warn(
                                        "No channel is active or defined for the data we received from {}. It will be discarded.",
                                        theDatagramChannel.getRemoteAddress());
                            }
                        } catch (IOException e) {
                            logger.error(
                                    "An exception occurred while getting the remote address of channel {} ({})",
                                    theDatagramChannel, e.getMessage());
                        }
                    }
                }
            } else if (selKey.isWritable()) {

                WriteBufferElement theElement = null;

                if (selKey == listenerKey) {
                    Iterator<WriteBufferElement> iterator = writeQueue.iterator();
                    while (iterator.hasNext()) {
                        WriteBufferElement anElement = iterator.next();
                        if (anElement.channel.channel.equals(listenerChannel)) {
                            theElement = anElement;
                            break;
                        }
                    }
                }

                //check if any of the Channel using the DatagramChannel is blocking the DGC in a R/W operation
                boolean isBlocking = channels.isBlocking(theDatagramChannel);

                if (isBlocking) {
                    // if this channel is already flagged as being in a blocked write/read operation, we skip this selKey
                } else {

                    if (selKey != listenerKey) {
                        Iterator<WriteBufferElement> iterator = writeQueue.iterator();
                        while (iterator.hasNext()) {
                            WriteBufferElement anElement = iterator.next();
                            if (anElement.channel.channel.equals(theDatagramChannel)) {
                                theElement = anElement;
                                break;
                            }
                        }
                    }

                    if (theElement != null && theElement.buffer != null) {

                        logger.debug("Picked {} from the queue", theElement);

                        if (theElement.isBlocking) {
                            theElement.channel.isBlocking = true;
                        }

                        boolean error = false;

                        theElement.buffer.rewind();

                        if (selKey == listenerKey) {
                            try {
                                if (useAddressMask && theElement.channel.remote == null) {
                                    if (theElement.channel.lastRemote != null) {
                                        logger.debug(
                                                "Sending {} for the masked inbound channel {}:{} to the remote address {}",
                                                new Object[] { new String(theElement.buffer.array()),
                                                        theElement.channel.host, theElement.channel.port,
                                                        theElement.channel.lastRemote });
                                        listenerChannel.send(theElement.buffer, theElement.channel.lastRemote);
                                    } else {
                                        logger.warn("I do not know where to send the data {}",
                                                new String(theElement.buffer.array()));
                                    }
                                } else {
                                    logger.debug(
                                            "Sending {} for the inbound channel {}:{} to the remote address {}",
                                            new Object[] { new String(theElement.buffer.array()),
                                                    theElement.channel.host, theElement.channel.port,
                                                    theElement.channel.remote });
                                    listenerChannel.send(theElement.buffer, theElement.channel.remote);
                                }
                            } catch (IOException e) {
                                if (theElement.channel.lastRemote != null) {
                                    logger.error(
                                            "An exception occurred while sending data to the remote end {} ({})",
                                            theElement.channel.lastRemote, e.getMessage());
                                } else {
                                    logger.error(
                                            "An exception occurred while sending data to the remote end {} ({})",
                                            theElement.channel.remote, e.getMessage());
                                }
                            }
                        } else {

                            try {
                                logger.debug(
                                        "Sending {} for the outbound channel {}:{} to the remote address {}",
                                        new Object[] { new String(theElement.buffer.array()),
                                                theElement.channel.host, theElement.channel.port,
                                                theElement.channel.remote });
                                theDatagramChannel.write(theElement.buffer);
                            } catch (NotYetConnectedException e) {
                                logger.warn("The channel for {} has no connection pending ({})",
                                        theElement.channel.remote, e.getMessage());
                                error = true;
                            } catch (ClosedChannelException e) {
                                // If some other I/O error occurs
                                logger.warn("The channel for {} is closed ({})", theElement.channel.remote,
                                        e.getMessage());
                                error = true;
                            } catch (IOException e) {
                                // If some other I/O error occurs
                                logger.warn("The channel for {} has encountered an unknown IO Exception: {}",
                                        theElement.channel.remote, e.getMessage());
                                error = true;
                            }
                        }

                        if (error) {

                            if (selKey != listenerKey) {

                                Scheduler scheduler = null;
                                try {
                                    scheduler = StdSchedulerFactory.getDefaultScheduler();
                                } catch (SchedulerException e1) {
                                    logger.error("An exception occurred while getting the Quartz scheduler: {}",
                                            e1.getMessage());
                                }

                                JobDataMap map = new JobDataMap();
                                map.put("Channel", theElement.channel);
                                map.put("Binding", this);

                                JobDetail job = null;
                                Trigger trigger = null;

                                job = newJob(ReconnectJob.class)
                                        .withIdentity(
                                                Integer.toHexString(hashCode()) + "-Reconnect-"
                                                        + Long.toString(System.currentTimeMillis()),
                                                this.toString())
                                        .usingJobData(map).build();

                                trigger = newTrigger()
                                        .withIdentity(
                                                Integer.toHexString(hashCode()) + "-Reconnect-"
                                                        + Long.toString(System.currentTimeMillis()),
                                                this.toString())
                                        .startAt(futureDate(reconnectInterval, IntervalUnit.SECOND)).build();

                                try {
                                    if (job != null && trigger != null && selKey != listenerKey) {
                                        if (!theElement.channel.isReconnecting) {
                                            channels.setAllReconnecting(theElement.channel.channel, true);
                                            scheduler.scheduleJob(job, trigger);
                                        }
                                    }
                                } catch (SchedulerException e) {
                                    logger.error(
                                            "An exception occurred while scheduling a job with the Quartz Scheduler {}",
                                            e.getMessage());
                                }
                            }
                        } else {
                            if (theElement != null) {
                                writeQueue.remove(theElement);
                            }

                        }
                    }
                }
            }
        }
    }
}