List of usage examples for java.nio.channels SelectionKey isValid
public abstract boolean isValid();
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;/* w ww. ja v a 2 s . c o 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.limewire.mojito.io.MessageDispatcherImpl.java
private void interest(int ops, boolean on) { try {/*from ww w. ja v a 2 s. c om*/ SelectionKey sk = channel.keyFor(selector); if (sk != null && sk.isValid()) { synchronized (channel.blockingLock()) { if (on) { sk.interestOps(sk.interestOps() | ops); } else { sk.interestOps(sk.interestOps() & ~ops); } } } } catch (CancelledKeyException ignore) { } }
From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java
protected void onAcceptable() { lock.lock();//from ww w . j a v 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.irtrans.handler.EthernetBridgeHandler.java
protected void onConnectable() { lock.lock();/*from w ww . j av a 2 s . c o m*/ SocketChannel aSocketChannel = null; try { synchronized (selector) { selector.selectNow(); } Iterator<SelectionKey> it = selector.selectedKeys().iterator(); while (it.hasNext()) { SelectionKey selKey = it.next(); it.remove(); if (selKey.isValid() && selKey.isConnectable()) { aSocketChannel = (SocketChannel) selKey.channel(); aSocketChannel.finishConnect(); logger.trace("The channel for '{}' is connected", aSocketChannel.getRemoteAddress()); } } } catch (IOException | NoConnectionPendingException e) { if (aSocketChannel != null) { logger.debug("Disconnecting '{}' because of a socket error : '{}'", getThing().getUID(), e.getMessage(), e); try { aSocketChannel.close(); } catch (IOException e1) { logger.debug("An exception occurred while closing the channel '{}': {}", socketChannel, e1.getMessage()); } } } finally { lock.unlock(); } }
From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java
protected ByteBuffer onReadable(int bufferSize, boolean isSelective) { lock.lock();/*from w w w. j av a 2 s. c o m*/ try { 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()) { SocketChannel aSocketChannel = (SocketChannel) selKey.channel(); if ((aSocketChannel.equals(socketChannel) && isSelective) || !isSelective) { ByteBuffer readBuffer = ByteBuffer.allocate(bufferSize); int numberBytesRead = 0; boolean error = false; try { numberBytesRead = aSocketChannel.read(readBuffer); } catch (NotYetConnectedException e) { logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel, e.getMessage()); if (!aSocketChannel.isConnectionPending()) { error = true; } } catch (IOException e) { // If some other I/O error occurs logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel, e.getMessage()); error = true; } if (numberBytesRead == -1) { error = true; } if (error) { logger.debug("Disconnecting '{}' because of a socket error", getThing().getUID()); try { aSocketChannel.close(); } catch (IOException e1) { logger.debug("An exception occurred while closing the channel '{}': {}", socketChannel, e1.getMessage()); } } else { readBuffer.flip(); return readBuffer; } } } } return null; } finally { lock.unlock(); } }
From source file:org.openhab.binding.irtrans.handler.EthernetBridgeHandler.java
protected void onWritable(ByteBuffer buffer) { lock.lock();/*from w w w. j a va 2 s. c o m*/ try { 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()) { SocketChannel aSocketChannel = (SocketChannel) selKey.channel(); if (aSocketChannel.equals(socketChannel)) { boolean error = false; buffer.rewind(); try { logger.trace("Sending '{}' on the channel '{}'->'{}'", new String(buffer.array()), aSocketChannel.getLocalAddress(), aSocketChannel.getRemoteAddress()); aSocketChannel.write(buffer); } catch (NotYetConnectedException e) { logger.warn("The channel '{}' is not yet connected: {}", aSocketChannel, e.getMessage()); if (!aSocketChannel.isConnectionPending()) { error = true; } } catch (ClosedChannelException e) { // If some other I/O error occurs logger.warn("The channel for '{}' is closed: {}", aSocketChannel, e.getMessage()); error = true; } catch (IOException e) { // If some other I/O error occurs logger.warn("An IO exception occured on channel '{}': {}", aSocketChannel, e.getMessage()); error = true; } if (error) { try { aSocketChannel.close(); } catch (IOException e) { logger.warn("An exception occurred while closing the channel '{}': {}", aSocketChannel, e.getMessage()); } } } } } } finally { lock.unlock(); } }
From source file:org.openhab.binding.keba.handler.KeContactHandler.java
protected ByteBuffer onReadable(DatagramChannel theChannel, int bufferSize) { lock.lock();/*from w w w . j a v a 2s . 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.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();//from w ww . ja v a 2 s .com 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 . com*/ 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 w w w .ja 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.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(); } }