List of usage examples for java.nio.channels SelectionKey interestOps
public abstract SelectionKey interestOps(int ops);
From source file:org.apache.htrace.impl.PackedBufferManager.java
/** * Send the provided ByteBuffer objects. * * We use non-blocking I/O because Java does not provide write timeouts. * Without a write timeout, the socket could get hung and we'd never recover. * We also use the GatheringByteChannel#write method which calls the pread() * system call under the covers. This ensures that even if TCP_NODELAY is on, * we send the minimal number of packets. *//*from w w w . j a v a 2 s .c om*/ private void doSend(SelectionKey sockKey, ByteBuffer[] bufs) throws IOException { long totalWritten = 0; sockKey.interestOps(SelectionKey.OP_WRITE); SocketChannel sock = (SocketChannel) sockKey.attachment(); long startMs = TimeUtil.nowMs(); long remainingMs = conf.ioTimeoutMs; while (true) { selector.select(remainingMs); int firstBuf = 0; for (SelectionKey key : selector.selectedKeys()) { if (key.isWritable()) { long written = sock.write(bufs, firstBuf, bufs.length - firstBuf); if (LOG.isTraceEnabled()) { LOG.trace("Sent " + written + " bytes to " + conf.endpointStr); } totalWritten += written; } } while (true) { if (firstBuf == bufs.length) { if (LOG.isTraceEnabled()) { LOG.trace("Finished sending " + totalWritten + " bytes to " + conf.endpointStr); } return; } if (bufs[firstBuf].remaining() > 0) { break; } firstBuf++; } remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs); if (remainingMs == 0) { throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after " + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms."); } } }
From source file:org.apache.htrace.impl.PackedBufferManager.java
private void doRecv(SelectionKey sockKey, ByteBuffer response) throws IOException { sockKey.interestOps(SelectionKey.OP_READ); SocketChannel sock = (SocketChannel) sockKey.attachment(); int totalRead = response.remaining(); long startMs = TimeUtil.nowMs(); long remainingMs = conf.ioTimeoutMs; while (remainingMs > 0) { selector.select(remainingMs);/*w w w . ja va 2s .com*/ for (SelectionKey key : selector.selectedKeys()) { if (key.isReadable()) { sock.read(response); } } if (response.remaining() == 0) { if (LOG.isTraceEnabled()) { LOG.trace("Received all " + totalRead + " bytes from " + conf.endpointStr); } return; } remainingMs = updateRemainingMs(startMs, conf.ioTimeoutMs); if (LOG.isTraceEnabled()) { LOG.trace("Received " + (totalRead - response.remaining()) + " out of " + totalRead + " bytes from " + conf.endpointStr); } if (remainingMs == 0) { throw new IOException("Attempt to write to " + conf.endpointStr + " timed out after " + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms."); } } }
From source file:org.apache.nifi.processor.util.listen.dispatcher.SocketChannelDispatcher.java
@Override public void run() { while (!stopped) { try {//from w ww .j ava 2s.c om 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.commoncrawl.io.internal.NIOSocketSelector.java
/** internal registration helper */ private void registerSocket(NIOSocket theSocket, int interestOps) throws IOException { if (_eventLoop == null || _eventLoop.getEventThread() == Thread.currentThread()) { SelectionKey key = theSocket.getChannel().keyFor(_selector); if (key == null) { key = theSocket.getChannel().register(_selector, interestOps, theSocket); } else {/*w ww . j ava 2s. c om*/ key.interestOps(key.interestOps() | interestOps); } } else { synchronized (_pendingRegistrations) { PendingRegistration pendingRegistration = _pendingRegistrations.get(theSocket.getSocketId()); if (pendingRegistration == null) { _pendingRegistrations.put(theSocket.getSocketId(), new PendingRegistration(theSocket, interestOps)); } else { pendingRegistration.setInterestOps(pendingRegistration.getInterestOps() | interestOps); } } _eventLoop.wakeup(); } }
From source file:org.commoncrawl.io.internal.NIOSocketSelector.java
/** poll method - poll the registered socket for events and potentially block for IO for the * specified timeout value /*from w w w. java2s.c o m*/ * * @param timeoutValue - amount of time in MS to wait (block) for IO * * */ @SuppressWarnings("unchecked") public int poll(long timeoutValue, TimeUsageDetail timeUsageDetailOut) throws IOException { long timeStart = System.currentTimeMillis(); if (_lastPollTime != -1 && (timeStart - _lastPollTime) >= 30000) { LOG.error("POLL Delta Too Long:" + (timeStart - _lastPollTime)); } _lastPollTime = timeStart; if (timeUsageDetailOut != null) { timeUsageDetailOut.blockedTime = 0; timeUsageDetailOut.unblockedTime = 0; } if (_selector == null || !_selector.isOpen()) { IOException e = new IOException("Selector NULL or Selector is Not Open!"); LOG.error(e); throw e; } processPendingRegistrations(); long timeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.unblockedTime += (timeEnd - timeStart); } /* if (timeoutWatchSet.size() != 0) { // We have a timeout pending, so calculate the time until then and select appropriately long nextTimeout = timeoutWatchSet.first().getTimeoutTimestamp(); long selectTime = nextTimeout - System.currentTimeMillis(); if (selectTime < timeoutValue) { timeoutValue = Math.max(selectTime,0); } } */ timeStart = System.currentTimeMillis(); int count = 0; if (timeoutValue <= 0) { count = _selector.selectNow(); } else { if (timeoutValue == Long.MAX_VALUE) timeoutValue = 0; count = _selector.select(timeoutValue); } timeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.blockedTime += (timeEnd - timeStart); } long unblockedTimeStart = System.currentTimeMillis(); // if (count != 0 ) { Set<SelectionKey> selectionSet = _selector.selectedKeys(); for (Iterator<SelectionKey> i = selectionSet.iterator(); i.hasNext();) { SelectionKey selectionKey = i.next(); i.remove(); if (selectionKey.isValid()) { Object attachment = selectionKey.attachment(); /* if (attachment instanceof TAsyncMethodCall) { transitionThriftMethod((TAsyncMethodCall)attachment,selectionKey); } */ if (attachment instanceof NIOSocket) { NIOSocket theSocket = (NIOSocket) selectionKey.attachment(); if (theSocket != null && theSocket.getListener() != null) { // reset interest ops selectionKey.interestOps(0); // process events in key ... if (selectionKey.isConnectable()) { boolean connected = false; Exception disconnectException = null; try { if (((NIOClientSocket) theSocket).finishConnect()) { connected = true; // log it ... // LOG.info("Connected to:"+((NIOClientSocket)theSocket).getSocketAddress()); // reset the selection key's ops.. otherwise, select keeps returning on an already connected socket (since we have registered for CONNECT) System.out.println( "Connected to:" + ((NIOClientSocket) theSocket).getSocketAddress()); timeStart = System.currentTimeMillis(); ((NIOClientSocketListener) theSocket.getListener()) .Connected((NIOClientSocket) theSocket); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInConnectedEvt += System.currentTimeMillis() - timeStart; } } else { //LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() + " - finishConnect returned false"); theSocket.close(); } } catch (IOException e) { //LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() + " with Exception:"+e); theSocket.close(); disconnectException = e; } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Connected Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()) .Excepted((NIOClientSocket) theSocket, e); theSocket.close(); disconnectException = e; //KILL THE SERVER //throw e; } // if we were unable to properly establish the connection, trigger the Disconnected notification ... if (!connected) { //LOG.error("Failed to Complete Connection in Finish Connect- Calling Disconnected"); ((NIOClientSocketListener) theSocket.getListener()) .Disconnected((NIOClientSocket) theSocket, disconnectException); // continue to the next socket ... continue; } } // now always set the socket to readable state ... if ((theSocket instanceof NIOClientSocket) && selectionKey.isValid()) { selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ); } if (selectionKey.isValid() && selectionKey.isReadable()) { int bytesRead = -1; try { timeStart = System.currentTimeMillis(); // track the number of actual bytes read in the callback ... bytesRead = ((NIOClientSocketListener) theSocket.getListener()) .Readable((NIOClientSocket) theSocket); //System.out.println("Readable Took:" + (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart; } if (bytesRead == -1) { // log it ... // LOG.error("Abnormal Disconnect Detected on Socket:"+ ((NIOClientSocket)theSocket).getSocketAddress()); // trigger a disconnect event ... ((NIOClientSocketListener) theSocket.getListener()) .Disconnected((NIOClientSocket) theSocket, null); // close the socket ... theSocket.close(); } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()) .Excepted((NIOClientSocket) theSocket, e); theSocket.close(); //KILL THE SERVER // throw e; } // if bytesRead == -1 then this means that the underlying connection has gone bad ... } if (selectionKey.isValid() && selectionKey.isWritable()) { try { timeStart = System.currentTimeMillis(); ((NIOClientSocketListener) theSocket.getListener()) .Writeable((NIOClientSocket) theSocket); // System.out.println("Writable Took:" + (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart; } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()) .Excepted((NIOClientSocket) theSocket, e); theSocket.close(); //KILL THE SERVER ? //throw e; } } if (selectionKey.isValid() && selectionKey.isAcceptable()) { ((NIOServerSocket) theSocket).acceptable(); // re-register for accept on this socket selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_ACCEPT); } } } // exernally managed socket (thrift client socket) else if (attachment instanceof NIOClientSocketListener) { NIOClientSocketListener listener = (NIOClientSocketListener) attachment; // reset interest ops selectionKey.interestOps(0); // now always set the socket to readable state ... selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ); if (selectionKey.isValid() && selectionKey.isReadable()) { int bytesRead = -1; try { timeStart = System.currentTimeMillis(); // track the number of actual bytes read in the callback ... bytesRead = listener.Readable(null); //System.out.println("Readable Took:" + (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart; } if (bytesRead == -1) { // log it ... // LOG.error("Abnormal Disconnect Detected on Socket:"+ ((NIOClientSocket)theSocket).getSocketAddress()); // trigger a disconnect event ... listener.Disconnected(null, null); } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); listener.Excepted(null, e); } // if bytesRead == -1 then this means that the underlying connection has gone bad ... } if (selectionKey.isValid() && selectionKey.isWritable()) { try { timeStart = System.currentTimeMillis(); listener.Writeable(null); // System.out.println("Writable Took:" + (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart; } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); listener.Excepted(null, e); } } } } else { LOG.error("Invalid Socket Detected. Calling Disconnect"); NIOSocket theSocket = (NIOSocket) selectionKey.attachment(); if (theSocket != null && theSocket.getListener() != null) { theSocket.getListener().Disconnected(theSocket, null); } } } //timeoutThriftMethods(); //startPendingThriftMethods(); long unblockedTimeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.unblockedTime += (unblockedTimeEnd - unblockedTimeStart); } // } return count; }
From source file:org.commoncrawl.io.NIOSocketSelector.java
/** * poll method - poll the registered socket for events and potentially block * for IO for the specified timeout value * /*from ww w . j av a 2s.c o m*/ * @param timeoutValue * - amount of time in MS to wait (block) for IO * * */ public int poll(long timeoutValue, TimeUsageDetail timeUsageDetailOut) throws IOException { long timeStart = System.currentTimeMillis(); if (_lastPollTime != -1 && (timeStart - _lastPollTime) >= 30000) { LOG.error("POLL Delta Too Long:" + (timeStart - _lastPollTime)); } _lastPollTime = timeStart; if (timeUsageDetailOut != null) { timeUsageDetailOut.blockedTime = 0; timeUsageDetailOut.unblockedTime = 0; } if (_selector == null || !_selector.isOpen()) { IOException e = new IOException("Selector NULL or Selector is Not Open!"); LOG.error(e); throw e; } processPendingRegistrations(); long timeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.unblockedTime += (timeEnd - timeStart); } timeStart = System.currentTimeMillis(); int count = _selector.select(timeoutValue); timeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.blockedTime += (timeEnd - timeStart); } long unblockedTimeStart = System.currentTimeMillis(); // if (count != 0 ) { Set<SelectionKey> selectionSet = _selector.selectedKeys(); for (Iterator<SelectionKey> i = selectionSet.iterator(); i.hasNext();) { SelectionKey selectionKey = i.next(); i.remove(); if (selectionKey.isValid()) { NIOSocket theSocket = (NIOSocket) selectionKey.attachment(); if (theSocket != null && theSocket.getListener() != null) { // reset interest ops selectionKey.interestOps(0); // process events in key ... if (selectionKey.isConnectable()) { boolean connected = false; Exception disconnectException = null; try { if (((NIOClientSocket) theSocket).finishConnect()) { connected = true; // log it ... // LOG.info("Connected to:"+((NIOClientSocket)theSocket).getSocketAddress()); // reset the selection key's ops.. otherwise, select keeps // returning on an already connected socket (since we have // registered for CONNECT) System.out.println( "Connected to:" + ((NIOClientSocket) theSocket).getSocketAddress()); timeStart = System.currentTimeMillis(); ((NIOClientSocketListener) theSocket.getListener()) .Connected((NIOClientSocket) theSocket); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInConnectedEvt += System.currentTimeMillis() - timeStart; } } else { // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() // + " - finishConnect returned false"); theSocket.close(); } } catch (IOException e) { // LOG.error("Failed to Connect to:"+((NIOClientSocket)theSocket).getSocketAddress() // + " with Exception:"+e); theSocket.close(); disconnectException = e; } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Connected Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e); theSocket.close(); disconnectException = e; // KILL THE SERVER throw e; } // if we were unable to properly establish the connection, trigger // the Disconnected notification ... if (!connected) { // LOG.error("Failed to Complete Connection in Finish Connect- Calling Disconnected"); ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket, disconnectException); // continue to the next socket ... continue; } } // now always set the socket to readable state ... if ((theSocket instanceof NIOClientSocket) && selectionKey.isValid()) { selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_READ); } if (selectionKey.isValid() && selectionKey.isReadable()) { int bytesRead = -1; try { timeStart = System.currentTimeMillis(); // track the number of actual bytes read in the callback ... bytesRead = ((NIOClientSocketListener) theSocket.getListener()) .Readable((NIOClientSocket) theSocket); // System.out.println("Readable Took:" + // (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInReadableEvt += System.currentTimeMillis() - timeStart; } if (bytesRead == -1) { // log it ... // LOG.error("Abnormal Disconnect Detected on Socket:"+ // ((NIOClientSocket)theSocket).getSocketAddress()); // trigger a disconnect event ... ((NIOClientSocketListener) theSocket.getListener()).Disconnected(theSocket, null); // close the socket ... theSocket.close(); } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e); theSocket.close(); // KILL THE SERVER throw e; } // if bytesRead == -1 then this means that the underlying connection // has gone bad ... } if (selectionKey.isValid() && selectionKey.isWritable()) { try { timeStart = System.currentTimeMillis(); ((NIOClientSocketListener) theSocket.getListener()) .Writeable((NIOClientSocket) theSocket); // System.out.println("Writable Took:" + // (System.currentTimeMillis() - timeStart)); if (timeUsageDetailOut != null) { timeUsageDetailOut.timeInWritableEvt += System.currentTimeMillis() - timeStart; } } catch (RuntimeException e) { LOG.error("Caught Runtime Exception in Readable Event:" + StringUtils.stringifyException(e)); ((NIOClientSocketListener) theSocket.getListener()).Excepted(theSocket, e); theSocket.close(); // KILL THE SERVER throw e; } } if (selectionKey.isValid() && selectionKey.isAcceptable()) { ((NIOServerSocket) theSocket).acceptable(); // re-register for accept on this socket selectionKey.interestOps(selectionKey.interestOps() | SelectionKey.OP_ACCEPT); } } } else { LOG.error("Invalid Socket Detected. Calling Disconnect"); NIOSocket theSocket = (NIOSocket) selectionKey.attachment(); if (theSocket != null && theSocket.getListener() != null) { theSocket.getListener().Disconnected(theSocket, null); } } } long unblockedTimeEnd = System.currentTimeMillis(); if (timeUsageDetailOut != null) { timeUsageDetailOut.unblockedTime += (unblockedTimeEnd - unblockedTimeStart); } // } return count; }
From source file:org.eclipsetrader.directa.internal.core.BrokerConnector.java
@Override public void run() { Selector socketSelector;//ww w .j a va 2 s. co m ByteBuffer dst = ByteBuffer.wrap(new byte[2048]); List<Position> positions = new ArrayList<Position>(); try { // Create a non-blocking socket channel socketChannel = SocketChannel.open(); socketChannel.configureBlocking(false); socketChannel.socket().setReceiveBufferSize(32768); socketChannel.socket().setSoLinger(true, 1); socketChannel.socket().setSoTimeout(0x15f90); socketChannel.socket().setReuseAddress(true); // Kick off connection establishment socketChannel.connect(new InetSocketAddress(server, port)); // Create a new selector socketSelector = SelectorProvider.provider().openSelector(); // Register the server socket channel, indicating an interest in // accepting new connections socketChannel.register(socketSelector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT); } catch (Exception e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error connecting to orders monitor", //$NON-NLS-1$ e); Activator.log(status); return; } for (;;) { try { if (socketSelector.select(30 * 1000) == 0) { logger.trace(">" + HEARTBEAT); //$NON-NLS-1$ socketChannel.write(ByteBuffer.wrap(new String(HEARTBEAT + "\r\n").getBytes())); //$NON-NLS-1$ } } catch (Exception e) { break; } // Iterate over the set of keys for which events are available Iterator<SelectionKey> selectedKeys = socketSelector.selectedKeys().iterator(); while (selectedKeys.hasNext()) { SelectionKey key = selectedKeys.next(); selectedKeys.remove(); if (!key.isValid()) { continue; } try { // Check what event is available and deal with it if (key.isConnectable()) { // Finish the connection. If the connection operation failed // this will raise an IOException. try { socketChannel.finishConnect(); } catch (IOException e) { // Cancel the channel's registration with our selector key.cancel(); return; } // Register an interest in writing on this channel key.interestOps(SelectionKey.OP_WRITE); } if (key.isWritable()) { logger.trace(">" + LOGIN + WebConnector.getInstance().getUser()); //$NON-NLS-1$ socketChannel.write(ByteBuffer.wrap( new String(LOGIN + WebConnector.getInstance().getUser() + "\r\n").getBytes())); //$NON-NLS-1$ // Register an interest in reading on this channel key.interestOps(SelectionKey.OP_READ); } if (key.isReadable()) { dst.clear(); int readed = socketChannel.read(dst); if (readed > 0) { String[] s = new String(dst.array(), 0, readed).split("\r\n"); //$NON-NLS-1$ for (int i = 0; i < s.length; i++) { logger.trace("<" + s[i]); //$NON-NLS-1$ if (s[i].endsWith(";" + WebConnector.getInstance().getUser() + ";")) { //$NON-NLS-1$ //$NON-NLS-2$ logger.trace(">" + UNKNOWN70); //$NON-NLS-1$ socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN70 + "\r\n").getBytes())); //$NON-NLS-1$ logger.trace(">" + UNKNOWN55); //$NON-NLS-1$ socketChannel.write(ByteBuffer.wrap(new String(UNKNOWN55 + "\r\n").getBytes())); //$NON-NLS-1$ } if (s[i].indexOf(";6;5;") != -1 || s[i].indexOf(";8;0;") != -1) { //$NON-NLS-1$ //$NON-NLS-2$ try { OrderMonitor monitor = parseOrderLine(s[i]); OrderDelta[] delta; synchronized (orders) { if (!orders.contains(monitor)) { orders.add(monitor); delta = new OrderDelta[] { new OrderDelta(OrderDelta.KIND_ADDED, monitor) }; } else { delta = new OrderDelta[] { new OrderDelta(OrderDelta.KIND_UPDATED, monitor) }; } } fireUpdateNotifications(delta); if (monitor.getFilledQuantity() != null && monitor.getAveragePrice() != null) { Account account = WebConnector.getInstance().getAccount(); account.updatePosition(monitor); } } catch (ParseException e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error parsing line: " + s[i], e); //$NON-NLS-1$ Activator.log(status); } } if (s[i].indexOf(";6;0;") != -1) { //$NON-NLS-1$ updateStatusLine(s[i]); } if (s[i].indexOf(";7;0;") != -1) { //$NON-NLS-1$ try { positions.add(new Position(s[i])); } catch (Exception e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Error parsing line: " + s[i], e); //$NON-NLS-1$ Activator.log(status); } } if (s[i].indexOf(";7;9;") != -1) { //$NON-NLS-1$ Account account = WebConnector.getInstance().getAccount(); account.setPositions(positions.toArray(new Position[positions.size()])); positions.clear(); } } } } } catch (Exception e) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, 0, "Connection error", e); //$NON-NLS-1$ Activator.log(status); } } } }
From source file:org.gcaldaemon.core.ldap.LDAPListener.java
private final void processRead(SelectionKey key) throws Exception { // Read packet from socket channel sleep(100);// w ww. ja va 2s . c o m byte[] bytes = null; Object att = key.attachment(); if (att != null && att instanceof byte[]) { bytes = (byte[]) att; } SocketChannel channel = (SocketChannel) key.channel(); requestBuffer.clear(); int len = channel.read(requestBuffer); if (len == -1) { throw new IOException(); } if (len != 0) { requestBuffer.flip(); byte[] packet = new byte[len]; requestBuffer.get(packet, 0, len); if (bytes == null || bytes.length == 0) { bytes = packet; key.attach(bytes); } else { byte[] swap = new byte[bytes.length + packet.length]; System.arraycopy(bytes, 0, swap, 0, bytes.length); System.arraycopy(packet, 0, swap, bytes.length, packet.length); bytes = swap; key.attach(bytes); } // Try to process packet LdapMessageContainer container = new LdapMessageContainer(); try { ByteBuffer buffer = ByteBuffer.wrap(bytes); LdapDecoder decoder = new LdapDecoder(); decoder.decode(buffer, container); } catch (DecoderException emptyStringException) { String msg = emptyStringException.getMessage(); if (msg != null && (msg.indexOf("empty") != -1 || msg.indexOf("transition") != -1)) { // All contacts requested int id = container.getMessageId(); SearchRequest search = new SearchRequest(); search.setMessageId(id); LdapMessage ldap = new LdapMessage(); ldap.setMessageId(id); ldap.setProtocolOP(search); container.setLdapMessage(ldap); } else { throw emptyStringException; } } // Process LDAP request ByteBuffer response = processRequest(container.getLdapMessage(), !container.isGrammarEndAllowed()); key.attach(response); key.interestOps(SelectionKey.OP_WRITE); } }
From source file:org.gcaldaemon.core.ldap.LDAPListener.java
private static final void processWrite(SelectionKey key) throws Exception { Object att = key.attachment(); if (att == null) { Thread.sleep(100);/*from w w w . j a v a 2 s.c om*/ return; } if (att instanceof ByteBuffer) { ByteBuffer buffer = (ByteBuffer) att; if (!buffer.hasRemaining()) { key.attach(new byte[0]); key.interestOps(SelectionKey.OP_READ); return; } SocketChannel channel = (SocketChannel) key.channel(); channel.write(buffer); } }
From source file:org.gldapdaemon.core.ldap.LDAPListener.java
private final void processRead(SelectionKey key) throws Exception { // Read packet from socket channel sleep(100);/*from w w w. j av a 2s . com*/ byte[] bytes = null; Object att = key.attachment(); if (att != null && att instanceof byte[]) { bytes = (byte[]) att; } SocketChannel channel = (SocketChannel) key.channel(); requestBuffer.clear(); int len = channel.read(requestBuffer); if (len == -1) { throw new IOException(); } if (len != 0) { requestBuffer.flip(); byte[] packet = new byte[len]; requestBuffer.get(packet, 0, len); if (bytes == null || bytes.length == 0) { bytes = packet; key.attach(bytes); } else { byte[] swap = new byte[bytes.length + packet.length]; System.arraycopy(bytes, 0, swap, 0, bytes.length); System.arraycopy(packet, 0, swap, bytes.length, packet.length); bytes = swap; key.attach(bytes); } // Try to process packet LdapMessageContainer container = new LdapMessageContainer(); try { ByteBuffer buffer = ByteBuffer.wrap(bytes); LdapDecoder decoder = new LdapDecoder(); decoder.decode(buffer, container); } catch (DecoderException emptyStringException) { String msg = emptyStringException.getMessage(); if (msg != null && (msg.indexOf("empty") != -1 || msg.indexOf("transition") != -1)) { // All contacts requested int id = container.getMessageId(); SearchRequest search = new SearchRequest(); search.setMessageId(id); LdapMessage ldap = new LdapMessage(); ldap.setMessageId(id); ldap.setProtocolOP(search); container.setLdapMessage(ldap); } else { throw emptyStringException; } } // Process LDAP request ByteBuffer response = processRequest(container.getLdapMessage(), !container.isGrammarEndAllowed()); key.attach(response); key.interestOps(SelectionKey.OP_WRITE); } }