Example usage for java.nio.channels DatagramChannel keyFor

List of usage examples for java.nio.channels DatagramChannel keyFor

Introduction

In this page you can find the example usage for java.nio.channels DatagramChannel keyFor.

Prototype

public final SelectionKey keyFor(Selector sel) 

Source Link

Usage

From source file:org.openhab.binding.keba.handler.KeContactHandler.java

protected ByteBuffer onReadable(DatagramChannel theChannel, int bufferSize) {
    lock.lock();/*  w  w  w . ja v  a2  s .co m*/
    try {

        SelectionKey theSelectionKey = theChannel.keyFor(selector);

        if (theSelectionKey != null) {

            synchronized (selector) {
                try {
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occurred while selecting: {}", e.getMessage());
                }
            }

            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey selKey = it.next();
                it.remove();
                if (selKey.isValid() && selKey.isReadable() && selKey == theSelectionKey) {

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

                    if (selKey == datagramChannelKey) {
                        try {
                            numberBytesRead = theChannel.read(readBuffer);
                        } catch (NotYetConnectedException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "The remote host is not yet connected");
                            error = true;
                        } catch (PortUnreachableException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                                    "The remote host is probably not a KEBA EV Charging station");
                            error = true;
                        } catch (IOException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "An IO exception occurred");
                            error = true;
                        }
                    }

                    if (numberBytesRead == -1) {
                        error = true;
                    }

                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error",
                                getThing().getUID().toString());
                        try {
                            theChannel.close();
                        } catch (IOException e) {
                            logger.error("An exception occurred while closing the channel '{}': {}",
                                    datagramChannel, e.getMessage());
                        }

                        onConnectionLost();

                    } else {
                        readBuffer.flip();
                        return readBuffer;
                    }
                }
            }
        }

        return null;
    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.keba.handler.KeContactHandler.java

protected void onWritable(ByteBuffer buffer, DatagramChannel theChannel) {
    lock.lock();//  ww  w . j  av a  2  s. c  o m
    try {

        SelectionKey theSelectionKey = theChannel.keyFor(selector);

        if (theSelectionKey != null) {

            synchronized (selector) {
                try {
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occurred while selecting: {}", e.getMessage());
                }
            }

            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey selKey = it.next();
                it.remove();
                if (selKey.isValid() && selKey.isWritable() && selKey == theSelectionKey) {

                    boolean error = false;
                    buffer.rewind();

                    try {
                        logger.debug("Sending '{}' on the channel '{}'->'{}'",
                                new Object[] { new String(buffer.array()), theChannel.getLocalAddress(),
                                        theChannel.getRemoteAddress() });
                        theChannel.write(buffer);
                    } catch (NotYetConnectedException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "The remote host is not yet connected");
                        error = true;
                    } catch (ClosedChannelException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "The connection to the remote host is closed");
                        error = true;
                    } catch (IOException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "An IO exception occurred");
                        error = true;
                    }

                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error",
                                getThing().getUID().toString());
                        try {
                            theChannel.close();
                        } catch (IOException e) {
                            logger.warn("An exception occurred while closing the channel '{}': {}",
                                    datagramChannel, e.getMessage());
                        }

                        onConnectionLost();

                    }
                }
            }
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.keba.handler.KeContactP20Handler.java

protected ByteBuffer onReadable(DatagramChannel theChannel, int bufferSize,
        InetAddress permittedClientAddress) {
    lock.lock();//from ww w  . j a  v a  2  s .c  o m
    try {

        SelectionKey theSelectionKey = theChannel.keyFor(selector);

        if (theSelectionKey != null) {

            synchronized (selector) {
                try {
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occurred while selecting: {}", e.getMessage());
                }
            }

            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey selKey = (SelectionKey) it.next();
                it.remove();
                if (selKey.isValid() && selKey.isReadable() && selKey == theSelectionKey) {

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

                    if (selKey == listenerKey) {
                        try {
                            InetSocketAddress clientAddress = (InetSocketAddress) theChannel
                                    .receive(readBuffer);
                            if (clientAddress.getAddress().equals(permittedClientAddress)) {
                                logger.debug("Received {} on the listener port from {}",
                                        new String(readBuffer.array()), clientAddress);
                                numberBytesRead = readBuffer.position();
                            } else {
                                logger.warn(
                                        "Received data from '{}' which is not the permitted remote address '{}'",
                                        clientAddress, permittedClientAddress);
                                return null;
                            }
                        } catch (Exception e) {
                            logger.error(
                                    "An exception occurred while receiving data on the listener port: '{}'",
                                    e.getMessage());
                            error = true;
                        }

                    } else {

                        try {
                            numberBytesRead = theChannel.read(readBuffer);
                        } catch (NotYetConnectedException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "The remote host is not yet connected");
                            error = true;
                        } catch (PortUnreachableException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                                    "The remote host is probably not a KEBA EV Charging station");
                            error = true;
                        } catch (IOException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "An IO exception occurred");
                            error = true;
                        }
                    }

                    if (numberBytesRead == -1) {
                        error = true;
                    }

                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error",
                                getThing().getUID().toString());
                        try {
                            theChannel.close();
                        } catch (IOException e) {
                            logger.error("An exception occurred while closing the channel '{}': {}",
                                    datagramChannel, e.getMessage());
                        }

                        onConnectionLost();

                    } else {
                        readBuffer.flip();
                        return readBuffer;
                    }
                }
            }
        }

        return null;
    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.keba.handler.KeContactP20Handler.java

protected void onWritable(ByteBuffer buffer, DatagramChannel theChannel) {
    lock.lock();//from ww w  .  j  av  a2 s.  c om
    try {

        SelectionKey theSelectionKey = theChannel.keyFor(selector);

        if (theSelectionKey != null) {

            synchronized (selector) {
                try {
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occurred while selecting: {}", e.getMessage());
                }
            }

            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            while (it.hasNext()) {
                SelectionKey selKey = (SelectionKey) it.next();
                it.remove();
                if (selKey.isValid() && selKey.isWritable() && selKey == theSelectionKey) {

                    boolean error = false;
                    buffer.rewind();

                    try {
                        logger.debug("Sending '{}' on the channel '{}'->'{}'",
                                new Object[] { new String(buffer.array()), theChannel.getLocalAddress(),
                                        theChannel.getRemoteAddress() });
                        theChannel.write(buffer);
                    } catch (NotYetConnectedException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "The remote host is not yet connected");
                        error = true;
                    } catch (ClosedChannelException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "The connection to the remote host is closed");
                        error = true;
                    } catch (IOException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "An IO exception occurred");
                        error = true;
                    }

                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error",
                                getThing().getUID().toString());
                        try {
                            theChannel.close();
                        } catch (IOException e) {
                            logger.warn("An exception occurred while closing the channel '{}': {}",
                                    datagramChannel, e.getMessage());
                        }

                        onConnectionLost();

                    }
                }
            }
        }
    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.mart.handler.martHandler.java

/**
 * Reads a buffer from the channel and returns it
 * A buffer is essentially a block of memory into which you can write data, which
 * you can then later read again/*from  w w  w .ja  va2 s.  co  m*/
 *
 * @param theChannel
 * @param bufferSize
 * @param permittedClientAddress
 * @return
 */
protected ByteBuffer Reader(DatagramChannel theChannel, int bufferSize, InetAddress permittedClientAddress) {
    // The lock() method locks the Lock instance so that all threads calling lock() are blocked until unlock() is
    // executed.
    lock.lock();
    try {
        // retrieves the channel's key representing its registration with the selector
        SelectionKey theSelectionKey = theChannel.keyFor(selector);
        if (theSelectionKey != null) {
            synchronized (selector) {
                try {
                    // it selects a set of keys whose corresponding channels are ready for I/O operations.
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occured while selecting: {}", e.getMessage());
                } catch (ClosedSelectorException e) {
                    logger.error("An exception occured while selecting: {}", e.getMessage());
                }
            }

            // to iterate over the this selector's selected key set
            Iterator<SelectionKey> iterate = selector.selectedKeys().iterator();
            // if iterate has more elements
            while (iterate.hasNext()) {
                // represents the key representing the channel's registration with the Selector (selector).
                SelectionKey selectKey = iterate.next();
                iterate.remove();
                if (selectKey.isValid() && selectKey.isReadable() && selectKey == theSelectionKey) {
                    // allocate a new byte buffer with 1024 bytes capacity
                    ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize);
                    int numOfBytesRead = 0;
                    boolean error = false;

                    // if the current select key is the key representing the listener's channel registration
                    // with the selector, then read the byte buffer or data from the channel
                    if (selectKey == listenerKey) {
                        try {
                            // receive a datagram via this channel
                            // the channel writes data into the the readBuffer
                            InetSocketAddress clientAddress = (InetSocketAddress) theChannel
                                    .receive(readBuffer);
                            // if the returned address given by the receive() is == permitted address
                            if (clientAddress.getAddress().equals(permittedClientAddress)) {
                                logger.debug("Received {} on the listener port from {}",
                                        new String(readBuffer.array()), clientAddress);
                                // returns the buffer's position to help as check whether the buffer is
                                // full or not
                                numOfBytesRead = readBuffer.position();
                            } else {
                                logger.warn(
                                        "Received data from '{}' which is not the permitted remote address '{}'",
                                        clientAddress, permittedClientAddress);
                                // since it is not a permitted remote address return nothing
                                return null;
                            }

                        } catch (Exception e) {
                            logger.error(
                                    "An exception occurred while receiving data on the listener port: '{}'",
                                    e.getMessage());
                            error = true;
                        }
                        // if the selectKey != listenerKey
                    } else {

                        try {
                            // reads a datagram from this channel though the selectKey != listenerKey
                            // reads a data from this channel into the readBuffer or
                            // the channel writes data into the the buffer
                            numOfBytesRead = theChannel.read(readBuffer);
                        } catch (NotYetConnectedException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "The MART adapter is not yet connected");
                            error = true;
                        } catch (PortUnreachableException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
                                    "This is probably not a MART adapter");
                            error = true;
                        } catch (IOException e) {
                            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                    "An IO exception occurred");
                            error = true;
                        }
                    }

                    // if numOfBytesRead == -1 then the channel has reached end of stream
                    if (numOfBytesRead == -1) {
                        error = true;
                    }
                    // if error == true , close the channel and re-establish connection
                    if (error) {
                        logger.debug("Disconnecting '{}' because of a socket error",
                                getThing().getUID().toString());
                        try {
                            // close the channel
                            theChannel.close();
                        } catch (IOException e) {
                            logger.error("An exception occurred while closing the channel '{}': {}",
                                    datagramChannel, e.getMessage());
                        }

                        // re-establish connection
                        onConnectionLost();
                        // if error == false,
                    } else {
                        // switch the buffer from writing mode into reading mode and return it
                        readBuffer.flip();
                        return readBuffer;

                    }
                }
            }
        }
        return null;

    } finally {
        lock.unlock();
    }
}

From source file:org.openhab.binding.mart.handler.martHandler.java

/**
 * this function reads from a buffer and writes into a channel
 * A buffer is essentially a block of memory into which you can write data, which
 * you can then later read again/*www . j  a v  a  2 s  .c om*/
 *
 * @param buffer
 * @param theChannel
 */
protected void writer(ByteBuffer buffer, DatagramChannel theChannel) {
    lock.lock();

    try {
        // represents the key representing the channel's registration with the Selector (selector).
        SelectionKey theSelectionKey = theChannel.keyFor(selector);

        // check if the key isn't null
        if (theSelectionKey != null) {
            synchronized (selector) {
                try {
                    // selects a set of keys whose corresponding channels are ready
                    // for I/O operations
                    selector.selectNow();
                } catch (IOException e) {
                    logger.error("An exception occured while selecting {}", e.getMessage());
                }
            }

            // returns this selector's selected-key set
            Iterator<SelectionKey> iterate = selector.selectedKeys().iterator();
            while (iterate.hasNext()) {
                SelectionKey selectKey = iterate.next();
                iterate.remove();
                // checks if the key is valid
                // tests whether this channels is ready for writing
                // checks whether the current select key is equal to the channel's registered key
                // with the selector
                if (selectKey.isValid() && selectKey.isWritable() && selectKey == theSelectionKey) {

                    boolean error = false;
                    // sets the position back to 0, so you can reread all the data in the buffer
                    buffer.rewind();

                    try {
                        logger.debug("Sending '{}' in the channel '{}'->'{}'",
                                new Object[] { new String(buffer.array()), theChannel.getLocalAddress(),
                                        theChannel.getRemoteAddress() });
                        // www.businessdictionary.com/definition/datagram.html
                        // writes a datagram to this channel
                        theChannel.write(buffer);
                    } catch (NotYetConnectedException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "The remote host is not yet connected");
                        error = true;
                    } catch (ClosedChannelException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "The connection to the remote host is closed");
                        error = true;
                    } catch (IOException e) {
                        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
                                "An Io exception occurred");
                        error = true;
                    }

                    if (error) {
                        try {
                            // closes the channel if it hasn't being closed already
                            theChannel.close();
                        } catch (Exception e) {
                            logger.warn("An exception occured while closing the channel '{}': {}",
                                    datagramChannel, e.getMessage());
                        }
                    }

                    // re-establish connection
                    onConnectionLost();

                }
            }
        }

    } finally {
        lock.unlock();
    }
}