Example usage for java.nio.channels SocketChannel register

List of usage examples for java.nio.channels SocketChannel register

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel register.

Prototype

public final SelectionKey register(Selector sel, int ops) throws ClosedChannelException 

Source Link

Document

Registers this channel with the given selector, returning a selection key.

Usage

From source file:Proxy.java

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

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

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

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

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

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

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

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

                            sslSocketChannel = new SSLSocketChannel(sslEngine, socketChannel);
                        }

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

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

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

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

    // Create variables
    SelectionKey key, newKey;//w  w  w .jav a2  s  .  c  o  m
    SocketChannel channel;
    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;//w w  w .j  a  v a2  s.co m
    SocketChannel channel;
    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.irtrans.handler.EthernetBridgeHandler.java

protected void onAcceptable() {
    lock.lock();/*  w w  w.j  av a 2  s  .c  o  m*/
    try {
        try {
            selector.selectNow();
        } catch (IOException e) {
            logger.debug("An exception occurred while selecting: {}", e.getMessage());
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
        }

        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey selKey = it.next();
            it.remove();
            if (selKey.isValid()) {
                if (selKey.isAcceptable() && selKey == listenerKey) {
                    try {
                        SocketChannel newChannel = listenerChannel.accept();
                        newChannel.configureBlocking(false);
                        logger.trace("Received a connection request from '{}'", newChannel.getRemoteAddress());

                        synchronized (selector) {
                            selector.wakeup();
                            newChannel.register(selector, newChannel.validOps());
                        }
                    } catch (IOException e) {
                        logger.debug("An exception occurred while accepting a connection on channel '{}': {}",
                                listenerChannel, e.getMessage());
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                e.getMessage());
                    }
                }
            }
        }
    } finally {
        lock.unlock();
    }
}

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

/**
 * @{inheritDoc}/*from  www .  jav a  2 s .  com*/
 */
@Override
protected void execute() {

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

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

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

                Channel newChannel = null;
                Channel existingChannel = null;

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

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

                        boolean assigned = false;

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

                            channels.add(newChannel);
                        } else {

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

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

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

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

                            }
                        }

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

                        boolean assigned = false;

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

                            channels.add(newChannel);

                            if (newChannel.channel == null) {

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

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

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

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

                                synchronized (this) {

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

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

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

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

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

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

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

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

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

        if (selKey.isValid()) {
            if (selKey == listenerKey) {
                if (selKey.isAcceptable()) {

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

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

                        if (firstChannel != null) {

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    if (error) {

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

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

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

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

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

                    } else {
                        if (result) {
                            InetSocketAddress remote = null;
                            try {
                                remote = (InetSocketAddress) theSocketChannel.getRemoteAddress();
                            } catch (IOException e) {
                                logger.error(
                                        "An exception occurred while getting the remote address of channel {} ({})",
                                        theSocketChannel, e.getMessage());
                            }

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

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

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

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

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

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

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

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

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

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

                            trigger = newTrigger()
                                    .withIdentity(
                                            Integer.toHexString(hashCode()) + "-Reconnect-"
                                                    + Long.toString(System.currentTimeMillis()),
                                            this.toString())
                                    .withSchedule(cronSchedule(reconnectCron)).build();

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

                } else if (selKey.isReadable()) {

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

                    try {
                        //TODO: Additional code to split readBuffer in multiple parts, in case the data send by the remote end is not correctly fragemented. Could be handed of to implementation class if for example, the buffer needs to be split based on a special character like line feed or carriage return
                        numberBytesRead = theSocketChannel.read(readBuffer);
                    } catch (NotYetConnectedException e) {
                        logger.warn("The channel for {} has no connection pending ({})", theChannel.remote,
                                e.getMessage());
                        if (!theSocketChannel.isConnectionPending()) {
                            error = true;
                        }
                    } catch (IOException e) {
                        // If some other I/O error occurs
                        logger.warn("The channel for {} has encountered an unknown IO Exception: {}",
                                theChannel.remote, e.getMessage());
                        error = true;
                    }

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

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

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

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

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

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

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

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

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

                        channelsToServe = channels.getAll(theSocketChannel);

                        if (channelsToServe.size() > 0) {

                            readBuffer.flip();

                            boolean isBlocking = channels.isBlocking(theSocketChannel);

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

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

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

                } else if (selKey.isWritable()) {

                    boolean isBlocking = channels.isBlocking(theSocketChannel);

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

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

                        WriteBufferElement theElement = null;

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

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

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

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

                            boolean error = false;

                            theElement.buffer.rewind();
                            try {
                                logger.debug("Sending {} for the outbound channel {}->{}",
                                        new Object[] { new String(theElement.buffer.array()),
                                                theElement.channel.channel.getLocalAddress(),
                                                theElement.channel.channel.getRemoteAddress() });
                                theSocketChannel.write(theElement.buffer);
                            } catch (NotYetConnectedException e) {
                                logger.warn("The channel for {} has no connection pending ({})",
                                        theChannel.remote, e.getMessage());
                                if (!theSocketChannel.isConnectionPending()) {
                                    error = true;
                                }
                            } catch (ClosedChannelException e) {
                                // If some other I/O error occurs
                                logger.warn("The channel for {} is closed ({})", theChannel.remote,
                                        e.getMessage());
                                error = true;
                            } catch (IOException e) {
                                // If some other I/O error occurs
                                logger.warn("The channel for {} has encountered an unknown IO Exception: {}",
                                        theChannel.remote, e.getMessage());
                                error = true;
                            }

                            if (error) {

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

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

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

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

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

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

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

                            }
                        }
                    }
                }
            }
        }
    }
}

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

private void createNewClientConnection(SelectionKey key) {
    SocketChannel socket = null;
    try {/*from   w ww  . j  av a 2s  .  c  om*/
        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
        socket = serverSocketChannel.accept();
    } catch (IOException e) {
        LOGGER.error("Cannot accept the connection from a new client", e);
        SystemUtilities.safeClose(socket);
        return;
    }

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

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

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

From source file:oz.hadoop.yarn.api.net.ApplicationContainerClientImpl.java

/**
 * /*from w  w  w .j av a  2s.  c o  m*/
 */
@Override
void init() throws IOException {
    SocketChannel channel = (SocketChannel) this.rootChannel;

    boolean connected = channel.connect(this.address);
    if (connected) {
        channel.configureBlocking(false);

        channel.register(this.selector, SelectionKey.OP_READ);

        if (logger.isInfoEnabled()) {
            logger.info("Connected to " + this.address);
        }
    } else {
        throw new IllegalStateException("Failed to connect to ClientServer at: " + this.address);
    }
}

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

protected void handleX10() {
    // handle X10 place requests
    Iterator<SelectionKey> events = null;
    while (running) {
        try {/*  w w  w .  j a  v a  2 s  .  c  o m*/
            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);
        }
    }
}