Example usage for java.nio.channels SelectionKey isConnectable

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

Introduction

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

Prototype

public final boolean isConnectable() 

Source Link

Document

Tests whether this key's channel has either finished, or failed to finish, its socket-connection operation.

Usage

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }/* w w  w . j  a v  a2s  .  c o  m*/
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:net.ymate.platform.serv.nio.support.NioEventProcessor.java

@Override
public void run() {
    try {//from  w  w  w .ja v a  2 s. c  om
        while (__flag) {
            __selector.select(5 * DateTimeUtils.SECOND);
            __doRegisterEvent();
            Iterator<SelectionKey> _keyIterator = __selector.selectedKeys().iterator();
            while (_keyIterator.hasNext()) {
                SelectionKey _selectionKey = _keyIterator.next();
                _keyIterator.remove();
                if (_selectionKey.isValid()) {
                    Object _attachment = _selectionKey.attachment();
                    if (_attachment instanceof INioSession) {
                        ((INioSession) _attachment).touch();
                    }
                    try {
                        if (_selectionKey.isAcceptable()) {
                            __doAcceptEvent(_selectionKey);
                        } else if (_selectionKey.isConnectable()) {
                            __doConnectEvent(_selectionKey);
                        } else if (_selectionKey.isReadable()) {
                            __doReadEvent(_selectionKey);
                        } else if (_selectionKey.isWritable()) {
                            __doWriteEvent(_selectionKey);
                        }
                    } catch (Throwable e) {
                        __doExceptionEvent(_selectionKey, e);
                    }
                }
            }
            __doClosedEvent();
        }
    } catch (IOException e) {
        if (__flag) {
            _LOG.error(e.getMessage(), RuntimeUtils.unwrapThrow(e));
        } else {
            _LOG.debug(e.getMessage(), RuntimeUtils.unwrapThrow(e));
        }
    }
}

From source file:org.apache.htrace.impl.PackedBufferManager.java

private SelectionKey doConnect() throws IOException {
    SocketChannel sock = SocketChannel.open();
    SelectionKey sockKey = null;//from ww  w .ja  va  2s. c  o  m
    boolean success = false;
    try {
        if (sock.isBlocking()) {
            sock.configureBlocking(false);
        }
        InetSocketAddress resolvedEndpoint = new InetSocketAddress(conf.endpoint.getHostString(),
                conf.endpoint.getPort());
        resolvedEndpoint.getHostName(); // trigger DNS resolution
        sock.connect(resolvedEndpoint);
        sockKey = sock.register(selector, SelectionKey.OP_CONNECT, sock);
        long startMs = TimeUtil.nowMs();
        long remainingMs = conf.connectTimeoutMs;
        while (true) {
            selector.select(remainingMs);
            for (SelectionKey key : selector.keys()) {
                if (key.isConnectable()) {
                    SocketChannel s = (SocketChannel) key.attachment();
                    s.finishConnect();
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Successfully connected to " + conf.endpointStr + ".");
                    }
                    success = true;
                    return sockKey;
                }
            }
            remainingMs = updateRemainingMs(startMs, conf.connectTimeoutMs);
            if (remainingMs == 0) {
                throw new IOException("Attempt to connect to " + conf.endpointStr + " timed out after "
                        + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms.");
            }
        }
    } finally {
        if (!success) {
            if (sockKey != null) {
                sockKey.cancel();
            }
            sock.close();
        }
    }
}

From source file:org.cloudata.core.commitlog.WorkerPool.java

private void dispatchSelectedKeys() {
    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();

    while (iter.hasNext()) {
        SelectionKey key = iter.next();
        iter.remove();/*from w  ww  .  j  av a2  s. c  o m*/

        if (key.isValid()) {
            if (key.isReadable()) {
                handleData(key);
            } else if (key.isConnectable()) {
                handleConnection(key);
            } else if (key.isWritable()) {
                handleWrite(key);
            }
        }
    }
}

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

/** poll method  - poll the registered socket for events and potentially block for IO for the 
 *  specified timeout value /*from  w w w  .  j av a 2  s  . c o m*/
 *  
 *  @param timeoutValue - amount of time in MS to wait (block) for IO 
 *  
 *  */
@SuppressWarnings("unchecked")
public int poll(long timeoutValue, TimeUsageDetail timeUsageDetailOut) throws IOException {

    long timeStart = System.currentTimeMillis();

    if (_lastPollTime != -1 && (timeStart - _lastPollTime) >= 30000) {
        LOG.error("POLL Delta Too Long:" + (timeStart - _lastPollTime));
    }
    _lastPollTime = timeStart;

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime = 0;
        timeUsageDetailOut.unblockedTime = 0;
    }

    if (_selector == null || !_selector.isOpen()) {
        IOException e = new IOException("Selector NULL or Selector is Not Open!");
        LOG.error(e);
        throw e;
    }

    processPendingRegistrations();
    long timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (timeEnd - timeStart);
    }

    /*
    if (timeoutWatchSet.size() != 0) { 
      // We have a timeout pending, so calculate the time until then and select appropriately
      long nextTimeout = timeoutWatchSet.first().getTimeoutTimestamp();
      long selectTime = nextTimeout - System.currentTimeMillis();
      if (selectTime < timeoutValue) {
        timeoutValue = Math.max(selectTime,0);
      }
    }
    */
    timeStart = System.currentTimeMillis();

    int count = 0;
    if (timeoutValue <= 0) {
        count = _selector.selectNow();
    } else {
        if (timeoutValue == Long.MAX_VALUE)
            timeoutValue = 0;
        count = _selector.select(timeoutValue);
    }
    timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime += (timeEnd - timeStart);
    }

    long unblockedTimeStart = System.currentTimeMillis();

    // if (count != 0 ) { 

    Set<SelectionKey> selectionSet = _selector.selectedKeys();

    for (Iterator<SelectionKey> i = selectionSet.iterator(); i.hasNext();) {

        SelectionKey selectionKey = i.next();

        i.remove();

        if (selectionKey.isValid()) {

            Object attachment = selectionKey.attachment();
            /*
            if (attachment instanceof TAsyncMethodCall) {
              transitionThriftMethod((TAsyncMethodCall)attachment,selectionKey);
            }
            */
            if (attachment instanceof NIOSocket) {
                NIOSocket theSocket = (NIOSocket) selectionKey.attachment();

                if (theSocket != null && theSocket.getListener() != null) {

                    // reset interest ops 
                    selectionKey.interestOps(0);

                    // process events in key ... 
                    if (selectionKey.isConnectable()) {

                        boolean connected = false;
                        Exception disconnectException = null;
                        try {
                            if (((NIOClientSocket) theSocket).finishConnect()) {
                                connected = true;
                                // log it ... 
                                // LOG.info("Connected to:"+((NIOClientSocket)theSocket).getSocketAddress());
                                // reset the selection key's ops.. otherwise, select keeps returning on an already connected socket (since we have registered for CONNECT)
                                System.out.println(
                                        "Connected to:" + ((NIOClientSocket) theSocket).getSocketAddress());
                                timeStart = System.currentTimeMillis();
                                ((NIOClientSocketListener) theSocket.getListener())
                                        .Connected((NIOClientSocket) theSocket);
                                if (timeUsageDetailOut != null) {
                                    timeUsageDetailOut.timeInConnectedEvt += System.currentTimeMillis()
                                            - timeStart;
                                }
                            } else {
                                //LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() + " - finishConnect returned false");
                                theSocket.close();
                            }
                        } catch (IOException e) {
                            //LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() + " with Exception:"+e);
                            theSocket.close();
                            disconnectException = e;
                        } catch (RuntimeException e) {
                            LOG.error("Caught Runtime Exception in Connected Event:"
                                    + StringUtils.stringifyException(e));
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Excepted((NIOClientSocket) theSocket, e);
                            theSocket.close();
                            disconnectException = e;
                            //KILL THE SERVER 
                            //throw e;
                        }

                        // if we were unable to properly establish the connection, trigger the Disconnected notification ... 
                        if (!connected) {
                            //LOG.error("Failed to Complete Connection in Finish Connect- Calling Disconnected");
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Disconnected((NIOClientSocket) theSocket, disconnectException);
                            // continue to the next socket ... 
                            continue;
                        }
                    }

                    // now always set the socket to readable state ... 
                    if ((theSocket instanceof NIOClientSocket) && selectionKey.isValid()) {
                        selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ);
                    }

                    if (selectionKey.isValid() && selectionKey.isReadable()) {
                        int bytesRead = -1;

                        try {

                            timeStart = System.currentTimeMillis();
                            // track the number of actual bytes read in the callback ... 
                            bytesRead = ((NIOClientSocketListener) theSocket.getListener())
                                    .Readable((NIOClientSocket) theSocket);
                            //System.out.println("Readable Took:" + (System.currentTimeMillis() - timeStart));
                            if (timeUsageDetailOut != null) {
                                timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart;
                            }

                            if (bytesRead == -1) {
                                // log it ... 
                                // LOG.error("Abnormal Disconnect Detected on Socket:"+ ((NIOClientSocket)theSocket).getSocketAddress());
                                // trigger a disconnect event ...
                                ((NIOClientSocketListener) theSocket.getListener())
                                        .Disconnected((NIOClientSocket) theSocket, null);
                                // close the socket ... 
                                theSocket.close();
                            }
                        } catch (RuntimeException e) {
                            LOG.error("Caught Runtime Exception in Readable Event:"
                                    + StringUtils.stringifyException(e));
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Excepted((NIOClientSocket) theSocket, e);
                            theSocket.close();
                            //KILL THE SERVER 
                            // throw e;
                        }
                        // if bytesRead == -1 then this means that the underlying connection has gone bad ... 
                    }

                    if (selectionKey.isValid() && selectionKey.isWritable()) {
                        try {

                            timeStart = System.currentTimeMillis();
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Writeable((NIOClientSocket) theSocket);
                            // System.out.println("Writable Took:" + (System.currentTimeMillis() - timeStart));
                            if (timeUsageDetailOut != null) {
                                timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart;
                            }
                        } catch (RuntimeException e) {
                            LOG.error("Caught Runtime Exception in Readable Event:"
                                    + StringUtils.stringifyException(e));
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Excepted((NIOClientSocket) theSocket, e);
                            theSocket.close();
                            //KILL THE SERVER ? 
                            //throw e;
                        }

                    }

                    if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                        ((NIOServerSocket) theSocket).acceptable();
                        // re-register for accept on this socket 
                        selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_ACCEPT);
                    }
                }
            }
            // exernally managed socket (thrift client socket)
            else if (attachment instanceof NIOClientSocketListener) {
                NIOClientSocketListener listener = (NIOClientSocketListener) attachment;
                // reset interest ops 
                selectionKey.interestOps(0);
                // now always set the socket to readable state ... 
                selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ);

                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    int bytesRead = -1;

                    try {

                        timeStart = System.currentTimeMillis();
                        // track the number of actual bytes read in the callback ... 
                        bytesRead = listener.Readable(null);
                        //System.out.println("Readable Took:" + (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart;
                        }

                        if (bytesRead == -1) {
                            // log it ... 
                            // LOG.error("Abnormal Disconnect Detected on Socket:"+ ((NIOClientSocket)theSocket).getSocketAddress());
                            // trigger a disconnect event ...
                            listener.Disconnected(null, null);
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        listener.Excepted(null, e);
                    }
                    // if bytesRead == -1 then this means that the underlying connection has gone bad ... 
                }

                if (selectionKey.isValid() && selectionKey.isWritable()) {
                    try {

                        timeStart = System.currentTimeMillis();
                        listener.Writeable(null);
                        // System.out.println("Writable Took:" + (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart;
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        listener.Excepted(null, e);
                    }
                }
            }
        } else {
            LOG.error("Invalid Socket Detected. Calling Disconnect");
            NIOSocket theSocket = (NIOSocket) selectionKey.attachment();
            if (theSocket != null && theSocket.getListener() != null) {
                theSocket.getListener().Disconnected(theSocket, null);
            }
        }
    }
    //timeoutThriftMethods();
    //startPendingThriftMethods();      

    long unblockedTimeEnd = System.currentTimeMillis();
    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (unblockedTimeEnd - unblockedTimeStart);
    }

    // }
    return count;
}

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

/**
 * poll method - poll the registered socket for events and potentially block
 * for IO for the specified timeout value
 * /*from  w  w  w.j  av a 2  s  .c  o  m*/
 * @param timeoutValue
 *          - amount of time in MS to wait (block) for IO
 * 
 * */
public int poll(long timeoutValue, TimeUsageDetail timeUsageDetailOut) throws IOException {

    long timeStart = System.currentTimeMillis();

    if (_lastPollTime != -1 && (timeStart - _lastPollTime) >= 30000) {
        LOG.error("POLL Delta Too Long:" + (timeStart - _lastPollTime));
    }
    _lastPollTime = timeStart;

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime = 0;
        timeUsageDetailOut.unblockedTime = 0;
    }

    if (_selector == null || !_selector.isOpen()) {
        IOException e = new IOException("Selector NULL or Selector is Not Open!");
        LOG.error(e);
        throw e;
    }

    processPendingRegistrations();
    long timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (timeEnd - timeStart);
    }

    timeStart = System.currentTimeMillis();
    int count = _selector.select(timeoutValue);
    timeEnd = System.currentTimeMillis();

    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.blockedTime += (timeEnd - timeStart);
    }

    long unblockedTimeStart = System.currentTimeMillis();

    // if (count != 0 ) {

    Set<SelectionKey> selectionSet = _selector.selectedKeys();

    for (Iterator<SelectionKey> i = selectionSet.iterator(); i.hasNext();) {

        SelectionKey selectionKey = i.next();

        i.remove();

        if (selectionKey.isValid()) {

            NIOSocket theSocket = (NIOSocket) selectionKey.attachment();

            if (theSocket != null && theSocket.getListener() != null) {

                // reset interest ops
                selectionKey.interestOps(0);

                // process events in key ...
                if (selectionKey.isConnectable()) {

                    boolean connected = false;
                    Exception disconnectException = null;
                    try {
                        if (((NIOClientSocket) theSocket).finishConnect()) {
                            connected = true;
                            // log it ...
                            // LOG.info("Connected to:"+((NIOClientSocket)theSocket).getSocketAddress());
                            // reset the selection key's ops.. otherwise, select keeps
                            // returning on an already connected socket (since we have
                            // registered for CONNECT)
                            System.out.println(
                                    "Connected to:" + ((NIOClientSocket) theSocket).getSocketAddress());
                            timeStart = System.currentTimeMillis();
                            ((NIOClientSocketListener) theSocket.getListener())
                                    .Connected((NIOClientSocket) theSocket);
                            if (timeUsageDetailOut != null) {
                                timeUsageDetailOut.timeInConnectedEvt += System.currentTimeMillis() - timeStart;
                            }
                        } else {
                            // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress()
                            // + " - finishConnect returned false");
                            theSocket.close();
                        }
                    } catch (IOException e) {
                        // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress()
                        // + " with Exception:"+e);
                        theSocket.close();
                        disconnectException = e;
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Connected Event:"
                                + StringUtils.stringifyException(e));
                        ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e);
                        theSocket.close();
                        disconnectException = e;
                        // KILL THE SERVER
                        throw e;
                    }

                    // if we were unable to properly establish the connection, trigger
                    // the Disconnected notification ...
                    if (!connected) {
                        // LOG.error("Failed to Complete Connection in Finish Connect- Calling Disconnected");
                        ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket,
                                disconnectException);
                        // continue to the next socket ...
                        continue;
                    }
                }

                // now always set the socket to readable state ...
                if ((theSocket instanceof NIOClientSocket) && selectionKey.isValid()) {
                    selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ);
                }

                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    int bytesRead = -1;

                    try {

                        timeStart = System.currentTimeMillis();
                        // track the number of actual bytes read in the callback ...
                        bytesRead = ((NIOClientSocketListener) theSocket.getListener())
                                .Readable((NIOClientSocket) theSocket);
                        // System.out.println("Readable Took:" +
                        // (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart;
                        }

                        if (bytesRead == -1) {
                            // log it ...
                            // LOG.error("Abnormal Disconnect Detected on Socket:"+
                            // ((NIOClientSocket)theSocket).getSocketAddress());
                            // trigger a disconnect event ...
                            ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket, null);
                            // close the socket ...
                            theSocket.close();
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e);
                        theSocket.close();
                        // KILL THE SERVER
                        throw e;
                    }
                    // if bytesRead == -1 then this means that the underlying connection
                    // has gone bad ...
                }

                if (selectionKey.isValid() && selectionKey.isWritable()) {
                    try {

                        timeStart = System.currentTimeMillis();
                        ((NIOClientSocketListener) theSocket.getListener())
                                .Writeable((NIOClientSocket) theSocket);
                        // System.out.println("Writable Took:" +
                        // (System.currentTimeMillis() - timeStart));
                        if (timeUsageDetailOut != null) {
                            timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart;
                        }
                    } catch (RuntimeException e) {
                        LOG.error("Caught Runtime Exception in Readable Event:"
                                + StringUtils.stringifyException(e));
                        ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e);
                        theSocket.close();
                        // KILL THE SERVER
                        throw e;
                    }

                }

                if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                    ((NIOServerSocket) theSocket).acceptable();
                    // re-register for accept on this socket
                    selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_ACCEPT);
                }
            }
        } else {
            LOG.error("Invalid Socket Detected. Calling Disconnect");
            NIOSocket theSocket = (NIOSocket) selectionKey.attachment();
            if (theSocket != null && theSocket.getListener() != null) {
                theSocket.getListener().Disconnected(theSocket, null);
            }
        }
    }

    long unblockedTimeEnd = System.currentTimeMillis();
    if (timeUsageDetailOut != null) {
        timeUsageDetailOut.unblockedTime += (unblockedTimeEnd - unblockedTimeStart);
    }

    // }
    return count;
}

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

@Override
public void run() {
    Selector socketSelector;/*from  www. ja  v  a  2s. com*/
    ByteBuffer dst = ByteBuffer.wrap(new byte[2048]);
    List<Position> positions = new ArrayList<Position>();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java

protected void onConnectable() {
    lock.lock();//from   w  ww  .  j  a v  a2s  .  c  o  m
    SocketChannel aSocketChannel = null;
    try {
        synchronized (selector) {
            selector.selectNow();
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid() && selKey.isConnectable()) {
                aSocketChannel = (SocketChannel) selKey.channel();
                aSocketChannel.finishConnect();
                logger.trace("The channel for '{}' is connected", aSocketChannel.getRemoteAddress());
            }
        }
    } catch (IOException | NoConnectionPendingException e) {
        if (aSocketChannel != null) {
            logger.debug("Disconnecting '{}' because of a socket error : '{}'", getThing().getUID(),
                    e.getMessage(), e);
            try {
                aSocketChannel.close();
            } catch (IOException e1) {
                logger.debug("An exception occurred while closing the channel '{}': {}", socketChannel,
                        e1.getMessage());
            }
        }
    } finally {
        lock.unlock();
    }
}

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

/**
 * @{inheritDoc}/*from  www  .  jav  a 2s  . 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);

                            channels.add(newChannel);
                        } 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 == null) {
                                if (channels.contains(itemName, aCommand, Direction.IN, remoteAddress)) {
                                    logger.warn("We already listen for incoming connections from {}",
                                            remoteAddress);
                                } else {
                                    logger.debug("Setting up the inbound channel {}", newChannel);
                                    channels.add(newChannel);
                                    logger.info("We will accept data coming from the remote end {}",
                                            remoteAddress);
                                }

                            }
                        }

                    } 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;
                                    }
                                }

                                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) {

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

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

                                        synchronized (selector) {
                                            selector.wakeup();
                                            int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE
                                                    | SelectionKey.OP_CONNECT;
                                            try {
                                                newSocketChannel.register(selector, interestSet);
                                            } catch (ClosedChannelException e1) {
                                                logger.error(
                                                        "An exception occurred while registering a selector: {}",
                                                        e1.getMessage());
                                            }
                                        }

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

                                        try {
                                            logger.info("Connecting the channel {} ", newChannel);
                                            newSocketChannel.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()) {
            if (selKey == listenerKey) {
                if (selKey.isAcceptable()) {

                    try {
                        SocketChannel newChannel = listenerChannel.accept();
                        logger.info("Received connection request from {}", newChannel.getRemoteAddress());

                        Channel firstChannel = channels.getFirstNotServed(Direction.IN,
                                (InetSocketAddress) newChannel.getRemoteAddress());

                        if (firstChannel != null) {

                            if (firstChannel.direction == Direction.IN) {

                                if (useAddressMask
                                        && (firstChannel.host.equals("*") || firstChannel.port.equals("*"))) {
                                    logger.info(
                                            "{}:{} is an allowed masked remote end. The channel will now be configured",
                                            firstChannel.host, firstChannel.port);
                                } else {
                                    logger.info(
                                            "{} is an allowed remote end. The channel will now be configured",
                                            firstChannel.remote);
                                }

                                if (firstChannel.channel == null || !firstChannel.channel.isOpen()) {

                                    firstChannel.channel = newChannel;
                                    firstChannel.isBlocking = false;
                                    firstChannel.buffer = null;

                                    if (itemShareChannels) {
                                        channels.replace(firstChannel.item, firstChannel.direction,
                                                (InetSocketAddress) newChannel.getRemoteAddress(),
                                                firstChannel.channel);
                                    }

                                    if (bindingShareChannels) {
                                        channels.replace(firstChannel.direction,
                                                (InetSocketAddress) newChannel.getRemoteAddress(),
                                                firstChannel.channel);
                                    }

                                    if (directionsShareChannels) {
                                        channels.replace((InetSocketAddress) newChannel.getRemoteAddress(),
                                                firstChannel.channel);
                                    }

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

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

                                    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", firstChannel);
                                    map.put("Binding", this);

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

                                    Trigger trigger = newTrigger().withIdentity(
                                            Integer.toHexString(hashCode()) + "-Configure-"
                                                    + Long.toString(System.currentTimeMillis()),
                                            this.toString()).startNow().build();

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

                                } else {
                                    logger.info(
                                            "We previously already accepted a connection from the remote end {} for this channel. Goodbye",
                                            firstChannel.remote);
                                    newChannel.close();
                                }
                            } else {
                                logger.info(
                                        "Disconnecting the remote end {} that tries to connect an outbound only port",
                                        newChannel.getRemoteAddress());
                                newChannel.close();
                            }
                        } else {
                            logger.info("Disconnecting the unallowed remote end {}",
                                    newChannel.getRemoteAddress());
                            newChannel.close();
                        }

                    } catch (IOException e) {
                        logger.error("An exception occurred while configuring a channel: {}", e.getMessage());
                    }
                }
            } else {

                SocketChannel theSocketChannel = (SocketChannel) selKey.channel();
                Channel theChannel = channels.get(theSocketChannel);

                if (selKey.isConnectable()) {
                    channels.setAllReconnecting(theSocketChannel, false);

                    boolean result = false;
                    boolean error = false;
                    try {
                        result = theSocketChannel.finishConnect();
                    } catch (NoConnectionPendingException e) {
                        // this channel is not connected and a connection operation
                        // has not been initiated
                        logger.warn("The channel  {} has no connection pending ({})", theSocketChannel,
                                e.getMessage());
                        error = true;
                    } catch (ClosedChannelException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel  {} is closed ({})", theSocketChannel, e.getMessage());
                        error = true;
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel {} has encountered an unknown IO Exception: {}",
                                theSocketChannel, e.getMessage());
                        error = true;
                    }

                    if (error) {

                        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 = newJob(ReconnectJob.class)
                                .withIdentity(Integer.toHexString(hashCode()) + "-Reconnect-"
                                        + Long.toString(System.currentTimeMillis()), this.toString())
                                .usingJobData(map).build();

                        Trigger 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(theSocketChannel, 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 (result) {
                            InetSocketAddress remote = null;
                            try {
                                remote = (InetSocketAddress) theSocketChannel.getRemoteAddress();
                            } catch (IOException e) {
                                logger.error(
                                        "An exception occurred while getting the remote address of channel {} ({})",
                                        theSocketChannel, e.getMessage());
                            }

                            logger.info("The channel for {} is now connected", remote);

                            if (itemShareChannels) {
                                channels.replace(theChannel.item, theChannel.direction, remote,
                                        theChannel.channel);
                            }

                            if (bindingShareChannels) {
                                channels.replace(theChannel.direction, remote, theChannel.channel);
                            }

                            if (directionsShareChannels) {
                                channels.replace(remote, theChannel.channel);
                            }

                            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 = newJob(ConfigureJob.class)
                                    .withIdentity(
                                            Integer.toHexString(hashCode()) + "-Configure-"
                                                    + Long.toString(System.currentTimeMillis()),
                                            this.toString())
                                    .usingJobData(map).build();

                            Trigger trigger = newTrigger()
                                    .withIdentity(
                                            Integer.toHexString(hashCode()) + "-Configure-"
                                                    + Long.toString(System.currentTimeMillis()),
                                            this.toString())
                                    .startNow().build();

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

                            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())
                                    .withSchedule(cronSchedule(reconnectCron)).build();

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

                } else if (selKey.isReadable()) {

                    ByteBuffer readBuffer = ByteBuffer.allocate(maximumBufferSize);
                    int numberBytesRead = 0;
                    boolean error = false;

                    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 = theSocketChannel.read(readBuffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel for {} has no connection pending ({})", theChannel.remote,
                                e.getMessage());
                        if (!theSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel for {} has encountered an unknown IO Exception: {}",
                                theChannel.remote, e.getMessage());
                        error = true;
                    }

                    if (numberBytesRead == -1) {
                        try {
                            theSocketChannel.close();
                        } catch (IOException e) {
                            logger.warn("The channel for {} is closed ({})", theChannel.remote, e.getMessage());
                        }
                        error = true;
                    }

                    if (error) {
                        if (theChannel.direction == Direction.OUT) {

                            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 = newJob(ReconnectJob.class).withIdentity(
                                    Integer.toHexString(hashCode()) + "-Reconnect-"
                                            + Long.toString(System.currentTimeMillis()),
                                    "AbstractSocketChannelBinding").usingJobData(map).build();

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

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

                        } else {
                            theChannel.channel = null;
                        }
                    } else {

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

                        channelsToServe = channels.getAll(theSocketChannel);

                        if (channelsToServe.size() > 0) {

                            readBuffer.flip();

                            boolean isBlocking = channels.isBlocking(theSocketChannel);

                            if (isBlocking) {
                                // 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

                                theChannel = channels.getBlocking(theSocketChannel);
                                theChannel.buffer = readBuffer;
                                theChannel.isBlocking = false;

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

                } else if (selKey.isWritable()) {

                    boolean isBlocking = channels.isBlocking(theSocketChannel);

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

                        // pick up a QueueElement for this channel, if any

                        WriteBufferElement theElement = null;

                        Iterator<WriteBufferElement> iterator = writeQueue.iterator();
                        while (iterator.hasNext()) {
                            WriteBufferElement anElement = iterator.next();
                            if (anElement.channel.channel.equals(theSocketChannel)) {
                                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();
                            try {
                                logger.debug("Sending {} for the outbound channel {}->{}",
                                        new Object[] { new String(theElement.buffer.array()),
                                                theElement.channel.channel.getLocalAddress(),
                                                theElement.channel.channel.getRemoteAddress() });
                                theSocketChannel.write(theElement.buffer);
                            } catch (NotYetConnectedException e) {
                                logger.warn("The channel for {} has no connection pending ({})",
                                        theChannel.remote, e.getMessage());
                                if (!theSocketChannel.isConnectionPending()) {
                                    error = true;
                                }
                            } catch (ClosedChannelException e) {
                                // If some other I/O error occurs
                                logger.warn("The channel for {} is closed ({})", theChannel.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: {}",
                                        theChannel.remote, e.getMessage());
                                error = true;
                            }

                            if (error) {

                                if (theElement.channel.direction == Direction.OUT) {

                                    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 = newJob(ReconnectJob.class).withIdentity(
                                            Integer.toHexString(hashCode()) + "-Reconnect-"
                                                    + Long.toString(System.currentTimeMillis()),
                                            "AbstractSocketChannelBinding").usingJobData(map).build();

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

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

                                } else {
                                    theElement.channel.channel = null;
                                }
                            } else {
                                if (theElement != null) {
                                    writeQueue.remove(theElement);
                                }

                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:org.openhab.io.transport.cul.internal.network.CULNetworkHandlerImpl.java

private void processSelectedKeys(Set<SelectionKey> keys) throws Exception {
    Iterator<SelectionKey> itr = keys.iterator();
    while (itr.hasNext()) {
        SelectionKey key = itr.next();
        if (key.isReadable()) {
            processRead(key);//w  w  w . java2s .  co  m
        }
        if (key.isWritable()) {
            processWrite(key);
        }
        if (key.isConnectable()) {
            processConnect(key);
        }
        if (key.isAcceptable()) {
            ;
        }
        itr.remove();
    }
}