Example usage for java.nio.channels SelectionKey isAcceptable

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

Introduction

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

Prototype

public final boolean isAcceptable() 

Source Link

Document

Tests whether this key's channel is ready to accept a new socket connection.

Usage

From source file:Proxy.java

/** We handle only non-SSL connections */
void loop(Selector selector) {
    Set ready_keys;// w  w w.j a  va2s.c  om
    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:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

@Override
public void run() {

    while (!this.isInterrupted()) {

        synchronized (this.pendingReadEventSubscribeRequests) {
            while (!this.pendingReadEventSubscribeRequests.isEmpty()) {
                final SelectionKey key = this.pendingReadEventSubscribeRequests.poll();
                final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
                final SocketChannel socketChannel = (SocketChannel) key.channel();

                try {
                    final SelectionKey newKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
                    newKey.attach(incomingConnection);
                } catch (ClosedChannelException e) {
                    incomingConnection.reportTransmissionProblem(key, e);
                }//w  w  w  .ja v  a 2  s.  c om
            }
        }

        try {
            this.selector.select(500);
        } 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.isReadable()) {
                    doRead(key);
                } else if (key.isAcceptable()) {
                    doAccept(key);
                } else {
                    LOG.error("Unknown key: " + key);
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Do cleanup, if necessary
    if (this.listeningSocket != null) {
        try {
            this.listeningSocket.close();
        } catch (IOException ioe) {
            // Actually, we can ignore this exception
            LOG.debug(ioe);
        }
    }

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

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

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {//from w w  w  .  ja  va  2  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: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 w  ww.  jav a 2s  . 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:middleware.NewServerSocket.java

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

        try {//from  www. j  a va  2  s .c  om
            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:org.gcaldaemon.core.ldap.LDAPListener.java

public final void run() {
    log.info("LDAP server started successfully.");

    // Create variables
    SelectionKey key, newKey;
    SocketChannel channel;// w  ww  .j a v a  2 s .com
    Socket socket = null;
    Iterator keys;
    int n;

    // Server loop
    for (;;) {
        try {

            // Select sockets
            try {
                socket = null;
                n = selector.select();
            } catch (NullPointerException closedError) {

                // Ignore Selector bug - client socket closed
                if (log.isDebugEnabled()) {
                    log.debug("Socket closed.", closedError);
                }
                continue;
            } catch (ClosedSelectorException interrupt) {
                break;
            } catch (Exception selectError) {

                // Unknown exception - stop server
                log.warn("Unable to select sockets!", selectError);
                break;
            }

            if (n != 0) {

                // Get an iterator over the set of selected keys
                keys = selector.selectedKeys().iterator();
                if (keys == null) {
                    continue;
                }

                // Look at each key in the selected set
                while (keys.hasNext()) {
                    key = (SelectionKey) keys.next();
                    keys.remove();

                    // Nothing to do
                    if (key == null) {
                        continue;
                    }

                    // Check key status
                    if (key.isValid()) {

                        // Accept new incoming connection
                        if (key.isAcceptable()) {
                            channel = serverChannel.accept();
                            if (channel != null) {

                                // Register new socket connection
                                socket = channel.socket();
                                channel.configureBlocking(false);
                                newKey = channel.register(selector, SelectionKey.OP_READ);
                                processAccept(newKey);
                            }
                        } else {
                            if (key.isReadable()) {

                                // Read from socket connection
                                socket = ((SocketChannel) key.channel()).socket();
                                processRead(key);
                            } else {

                                // Write to socket connection
                                if (key.isWritable()) {
                                    socket = ((SocketChannel) key.channel()).socket();
                                    processWrite(key);
                                }
                            }
                        }
                    }
                }
            }
        } catch (InterruptedException interrupt) {
            closeSocket(socket);
            break;
        } catch (IOException socketClosed) {
            closeSocket(socket);
            continue;
        } catch (Exception processingException) {
            closeSocket(socket);
            log.warn(processingException.getMessage(), processingException);
        }
    }
    log.info("LDAP server stopped.");
}

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

public final void run() {
    log.info("LDAP server started successfully.");

    // Create variables
    SelectionKey key, newKey;
    SocketChannel channel;/*from   www. j  ava  2s.  co m*/
    Socket socket = null;
    Iterator keys;
    int n;

    // Server loop
    for (;;) {
        try {
            // Select sockets
            try {
                socket = null;
                n = selector.select();
            } catch (NullPointerException closedError) {
                // Ignore Selector bug - client socket closed
                if (log.isDebugEnabled()) {
                    log.debug("Socket closed.", closedError);
                }
                sleep(5000);
                continue;
            } catch (ClosedSelectorException interrupt) {
                break;
            } catch (Exception selectError) {
                // Unknown exception - stop server
                log.warn("Unable to select sockets!", selectError);
                break;
            }

            if (n != 0) {
                // Get an iterator over the set of selected keys
                keys = selector.selectedKeys().iterator();
                if (keys == null) {
                    sleep(5000);
                    continue;
                }

                // Look at each key in the selected set
                while (keys.hasNext()) {
                    key = (SelectionKey) keys.next();
                    keys.remove();

                    // Nothing to do
                    if (key == null) {
                        sleep(5000);
                        continue;
                    }

                    // Check key status
                    if (key.isValid()) {
                        // Accept new incoming connection
                        if (key.isAcceptable()) {
                            channel = serverChannel.accept();
                            if (channel != null) {
                                // Register new socket connection
                                socket = channel.socket();
                                channel.configureBlocking(false);
                                newKey = channel.register(selector, SelectionKey.OP_READ);
                                processAccept(newKey);
                            }
                        } else {
                            if (key.isReadable()) {
                                // Read from socket connection
                                socket = ((SocketChannel) key.channel()).socket();
                                processRead(key);
                            } else {
                                // Write to socket connection
                                if (key.isWritable()) {
                                    socket = ((SocketChannel) key.channel()).socket();
                                    processWrite(key);
                                }
                            }
                        }
                    }
                }
            }
        } catch (InterruptedException interrupt) {
            closeSocket(socket);
            break;
        } catch (IOException socketClosed) {
            closeSocket(socket);
            continue;
        } catch (Exception processingException) {
            closeSocket(socket);
            log.warn(processingException.getMessage(), processingException);
        }
    }
    log.info("LDAP server stopped.");
}

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

/**
 * @{inheritDoc}/*from  ww w.  j ava2  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);

                            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: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 ww .  ja v a 2  s  . c o m*/
            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:org.quickserver.net.server.QuickServer.java

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

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

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

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

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

            server = null;
            serverSocketChannel = null;

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

            processServerHooks(ServerHook.POST_SHUTDOWN);
        }

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

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

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

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

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

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

                client = socketChannel.socket();

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

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

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

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

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

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

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

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

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

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

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

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

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