/* (non-Javadoc)
@see net.timewalker.ffmq4.transport.tcp.nio.NIOClientSocketHandler#handleIncomingData()
170348
@Override
	public boolean handleIncomingData()
	{
		lastRecvActivity = System.currentTimeMillis();
		
		while (inputBuffer.remaining() > 0)
		{		
			if (packetInputBuffer.size() == 0)
			{
				if (inputBuffer.remaining() >= 4) // packet_size = sizeof(int) = 4
				{
					int packetSize = inputBuffer.getInt();
					
					// Security check
					int actualMaxPacketSize = Integer.MAX_VALUE;
					if (maxPacketSize != -1)
						actualMaxPacketSize = trustedConnection ? maxPacketSize : 1024;
					
					if (packetSize > actualMaxPacketSize)
					{
						log.error("#"+id+" packet is too large : "+packetSize+" (maxPacketSize="+actualMaxPacketSize+"), dropping client.");
						return false;
					}
					
					packetInputBuffer.setSize(packetSize);
				}
				else
					return true; // Not enough data to proceed ...
			}
			else
			{
				// Append to current packet
				int readAmount = Math.min(inputBuffer.remaining(), packetInputBuffer.size() - currentInputOffset);
				packetInputBuffer.getFrom(inputBuffer, currentInputOffset, readAmount);
				currentInputOffset += readAmount;
				
				// Packet is complete ?
				if (currentInputOffset == packetInputBuffer.size())
				{
					AbstractPacket packet = unserializePacket(packetInputBuffer);
					if (packet == null)
						return false; // Invalid packet
					packetInputBuffer.clear();
					currentInputOffset = 0;
					
					if (traceEnabled)
	                    log.trace("#"+id+" Received "+packet);
					
					if (listener != null)
						trustedConnection = listener.packetReceived(packet);
				}
			}
		}
		
		return true;
	}
1193636
private void handleDataAvailable() {
        InputStream inputStream = serialPort.getInputStream();
        try {
            while (inputStream.available() > 0) {
                byte inputByte = (byte) inputStream.read();

                if (inputByte == -1) {
                    log.error("Reached end of stream trying to read serial port.");
                    stop();
                    return;
                }

                Message message = configuration.getCommandParser().handleInputStream(inputByte, inputStream);

                if (message != null) {
                    log.debug("Routing message {}", message.getClass().getSimpleName());
                    routeMessage(message);
                }
            }
        } catch (IOException e) {
            log.error("IO Error reading from serial port. Closing connection.");
            e.printStackTrace();
            stop();
        }
    }
866449
public void handleData(String data) {
		try {
			sendEvent(new ClickEvent(this.user, getPayload()));
			if (clickHandler != null)
				clickHandler.clicked();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
226387
@Override
  public final void handle(final Map<String, Object> pReqVars,
    final IRequestData pRequestData) throws Exception {
    AccSettings as = srvAccSettings.lazyGetAccSettings(pReqVars);
    String curSign;
    if (as.getUseCurrencySign()) {
      curSign = as.getCurrency().getItsSign();
    } else {
      curSign = " " + as.getCurrency().getItsName() + " ";
    }
    pReqVars.put("quantityDp", as.getQuantityPrecision());
    pReqVars.put("priceDp", as.getPricePrecision());
    pReqVars.put("costDp", as.getCostPrecision());
    pReqVars.put("taxDp", as.getTaxPrecision());
    pReqVars.put("reportDp", as.getBalancePrecision());
    pReqVars.put("curSign", curSign);
    pReqVars.put("accSet", as);
    String lang = (String) pReqVars.get("lang");
    String langDef = (String) pReqVars.get("langDef");
    if (lang != null && langDef != null && !lang.equals(langDef)) {
      List<I18nAccounting> i18nAccTmp;
      List<I18nCurrency> i18nCurTmp;
      synchronized (this) {
        if (this.i18nAccountingList == null) {
          try {
            this.logger.info(null, HndlAccVarsRequest.class,
              "Refreshing I18N data...");
            this.srvDatabase.setIsAutocommit(false);
            this.srvDatabase.setTransactionIsolation(ISrvDatabase
              .TRANSACTION_READ_UNCOMMITTED);
            this.srvDatabase.beginTransaction();
            List<I18nAccounting> i18nac = this.srvOrm.retrieveList(pReqVars,
              I18nAccounting.class);
            List<I18nCurrency> i18ncur = this.srvOrm.retrieveList(pReqVars,
              I18nCurrency.class);
            this.srvDatabase.commitTransaction();
            //assigning fully initialized data:
            this.i18nAccountingList = i18nac;
            this.i18nCurrencyList = i18ncur;
          } catch (Exception ex) {
            if (!this.srvDatabase.getIsAutocommit()) {
              this.srvDatabase.rollBackTransaction();
            }
            throw ex;
          } finally {
            this.srvDatabase.releaseResources();
          }
        }
        i18nAccTmp = this.i18nAccountingList;
        i18nCurTmp = this.i18nCurrencyList;
      }
      for (I18nAccounting i18nAccounting : i18nAccTmp) {
        if (i18nAccounting.getLang().getItsId().equals(lang)) {
          pReqVars.put("i18nAccounting", i18nAccounting);
          break;
        }
      }
      for (I18nCurrency i18nCurrency : i18nCurTmp) {
        if (i18nCurrency.getHasName().getItsId()
          .equals(as.getCurrency().getItsId())
            && i18nCurrency.getLang().getItsId().equals(lang)) {
          pReqVars.put("i18nCurrency", i18nCurrency);
          break;
        }
      }
    }
    if (this.additionalI18nReqHndl != null) {
      this.additionalI18nReqHndl.handle(pReqVars, pRequestData);
    }
  }
1178869
void data(boolean outFinished, int streamId, Buffer source, boolean flush) {
    Preconditions.checkNotNull(source, "source");

    OkHttpClientStream stream = transport.getStream(streamId);
    if (stream == null) {
      // This is possible for a stream that has received end-of-stream from server (but hasn't sent
      // end-of-stream), and was removed from the transport stream map.
      // In such case, we just throw away the data.
      return;
    }

    OutboundFlowState state = state(stream);
    int window = state.writableWindow();
    boolean framesAlreadyQueued = state.hasPendingData();
    int size = (int) source.size();

    if (!framesAlreadyQueued && window >= size) {
      // Window size is large enough to send entire data frame
      state.write(source, size, outFinished);
    } else {
      // send partial data
      if (!framesAlreadyQueued && window > 0) {
        state.write(source, window, false);
      }
      // Queue remaining data in the buffer
      state.enqueue(source, (int) source.size(), outFinished);
    }

    if (flush) {
      flush();
    }
  }
668851
protected void handlePendingCallResult(RTMPConnection conn, Invoke invoke) {
        final IServiceCall call = invoke.getCall();
        final IPendingServiceCall pendingCall = conn.retrievePendingCall(invoke.getTransactionId());
        if (pendingCall != null) {
            // The client sent a response to a previously made call.
            Object[] args = call.getArguments();
            if (args != null && args.length > 0) {
                // TODO: can a client return multiple results?
                pendingCall.setResult(args[0]);
            }
            Set<IPendingServiceCallback> callbacks = pendingCall.getCallbacks();
            if (!callbacks.isEmpty()) {
                HashSet<IPendingServiceCallback> tmp = new HashSet<>();
                tmp.addAll(callbacks);
                for (IPendingServiceCallback callback : tmp) {
                    try {
                        callback.resultReceived(pendingCall);
                    } catch (Exception e) {
                        log.error("Error while executing callback {}", callback, e);
                    }
                }
            }
        }
    }
828417
protected void pushAttributeDataReadyEvent(final int counter, ZMQ.Socket eventSocket)
            throws DevFailed {
        xlogger.entry();
        try {
            final AttDataReady dataReady = new AttDataReady(attribute.getName(), attribute.getTangoType(), counter);
            synchronized (eventSocket) {
                EventUtilities.sendToSocket(eventSocket, fullName, counter, EventUtilities.marshall(dataReady));
            }
        } catch (final org.zeromq.ZMQException e) {
            throw DevFailedUtils.newDevFailed(e);
        }

        xlogger.exit();
    }
839361
@Override
  public final void process(final Map<String, Object> pReqVars,
    final IRequestData pRequestData) throws Exception {
    DatabaseInfo databaseInfo = getSrvOrm()
      .retrieveEntityWithConditions(pReqVars, DatabaseInfo.class, "");
    pRequestData.setAttribute("databaseInfo", databaseInfo);
    pRequestData.setAttribute("appVersion", getSrvOrm().getMngSettings()
      .getAppSettings().get("appVersion"));
  }
768978
@Override
    public void waitForData(long timeout, TimeUnit timeUnit) throws CouldNotPerformException, InterruptedException {
        try {
            if (isDataAvailable()) {
                return;
            }
            long startTime = System.currentTimeMillis();
            getDataFuture().get(timeout, timeUnit);
            long partialTimeout = timeUnit.toMillis(timeout) - (System.currentTimeMillis() - startTime);
            if (partialTimeout <= 0) {
                throw new java.util.concurrent.TimeoutException("Data timeout is reached!");
            }
            dataObservable.waitForValue(partialTimeout, TimeUnit.MILLISECONDS);
        } catch (java.util.concurrent.TimeoutException | CouldNotPerformException | ExecutionException | CancellationException ex) {
            if (shutdownInitiated) {
                throw new InterruptedException("Interrupt request because system shutdown was initiated!");
            }
            throw new NotAvailableException("Data is not yet available!", ex);
        }
    }
999437
void handleStorageException(final TSDB tsdb, final IncomingDataPoint dp, 
      final Exception e) {
    final StorageExceptionHandler handler = tsdb.getStorageExceptionHandler();
    if (handler != null) {
      handler.handleError(dp, e);
    }
  }
502045
@Override
	public void ZWaveIncomingEvent(ZWaveEvent event) {
		if (event.getEventType() != ZWaveEvent.ZWaveEventType.TRANSACTION_COMPLETED_EVENT)
			return;
		
		SerialMessage serialMessage = (SerialMessage)event.getEventValue();
		
		if (serialMessage.getMessageClass() != SerialMessage.SerialMessageClass.SendData && serialMessage.getMessageType() != SerialMessage.SerialMessageType.Request)
			return;
		
		byte[] payload = serialMessage.getMessagePayload();
		
		if (payload.length < 4)
			return;
		if ((payload[0] & 0xFF) != this.getNode().getNodeId())
			return;
		if ((payload[2] & 0xFF) != this.getCommandClass().getKey())
			return;
		if ((payload[3] & 0xFF) != WAKE_UP_NO_MORE_INFORMATION)
			return;
		
		logger.debug("Node {} went to sleep", this.getNode().getNodeId());
		this.setAwake(false);
	}
1157215
public void handleData(String data) {
		value = Double.valueOf(data);
		sendEvent(new SlideEvent(this.user, getPayload(), value));
		if (handler != null)
			handler.slide(value);
	}
649878
@Override
	public boolean appendOutgoingData()
	{
		while (outputBuffer.remaining() > 0)
		{
			if (packetOutputBuffer.size() == 0)
			{
				if (sendQueue.size() == 0)
					return true; // No more packet to send
				
				if (outputBuffer.remaining() < 4) // packet_size = sizeof(int) = 4
					return true; // Not enough space to proceed
				
				// Write packet size
				if (!serializePacket(sendQueue.getFirst(),packetOutputBuffer))
					return false; // Invalid packet
				outputBuffer.putInt(packetOutputBuffer.size());
				currentOutputOffset = 0;
			}
			else
			{
				int writeAmount = Math.min(outputBuffer.remaining(),packetOutputBuffer.size() - currentOutputOffset);
				packetOutputBuffer.putTo(outputBuffer, currentOutputOffset, writeAmount);
				currentOutputOffset += writeAmount;
				
				// Packet completly sent ?
				if (currentOutputOffset == packetOutputBuffer.size())
				{
					AbstractPacket sentPacket;
					synchronized (sendQueue)
					{
						sentPacket = sendQueue.removeFirst();
					}
					packetOutputBuffer.clear();
					
					if (listener != null)
						listener.packetSent(sentPacket);
				}
			}
		}
		return true;
	}
93957
private void handleNewGap(long startstamp, long endstamp)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(
                        tc,
                        "handleNewGap",
                        new Object[] { Long.valueOf(startstamp), Long.valueOf(endstamp) });

        TickRange tr = new TickRange(TickRange.Requested, startstamp, endstamp);
        oststream.writeRange(tr);

        // SIB0115 
        // Update Health State due to detected gap
        getControlAdapter().getHealthState().updateHealth(HealthStateListener.GAP_DETECTED_STATE,
                                                          HealthState.AMBER);

        NRTExpiryHandle nexphandle = new NRTExpiryHandle(tr, this);
        nexphandle.timer =
                        am.create(mp.getCustomProperties().getGapCuriosityThreshold(), nexphandle);

        addAlarm(this, nexphandle);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "handleNewGap");
    }
306212
function handleData(stream, asString, data, dataLimit) {
        var dataLen = data.length,
            i = dataLen,
            trailingDataIndex = -1, //index of data after the last delimiter match in data
            lastMatchIndex = 0,
            matchLimit  = dataLimit || Infinity,
            len = 0;

        //first start going back through data to find the last match
        //we do this loop separately so we can just store the index of the last match and then add that to the buffer at the end for the next packet
        while (i--) {
            if (data[i] === stream.delimiter) {
                //now that we found the match, store the index (+1 so we don't store the delimiter)
                trailingDataIndex = i + 1;
                break;
            }
        }

        //if we didn't find a match at all, just push the data onto the buffer
        if (trailingDataIndex === -1) {
            //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer
            stream.buffer = concatBuffer(stream.buffer, data, dataLimit);
            return;
        }
        lastMatchIndex = i;
        while (i--) {
            if (data[i] === stream.delimiter) {
                //make sure we ignore back-to-back delimiters
                len = lastMatchIndex - (i + 1); //i + 1 so we don't include the delimiter we just matched
                if (len > matchLimit) {
                    stream.matches.push(data.slice(lastMatchIndex - matchLimit, lastMatchIndex));
                } else if (len > 0) {
                    stream.matches.push(data.slice(i + 1, lastMatchIndex));
                }
                lastMatchIndex = i;
            }
        }
        //since the loop stops at the beginning of data we need to store the bytes before the first match in the string
        if (lastMatchIndex > 0) {
            stream.buffer = concatBuffer(stream.buffer, data.slice(0, lastMatchIndex), dataLimit);
        }
        //add the leftover buffer to the matches at the end (beginning when we emit events)
        if (asString) {
            if (isNode) {
                stream.matches.push(stream.buffer.toString());
                stream.buffer = new BUFFER_CONSTRUCTOR(0);
            } else {
                stream.matches.push(stream.buffer.splice(0, stream.buffer.length).join(''));
            }
        } else {
            stream.matches.push(stream.buffer);
            stream.buffer = new BUFFER_CONSTRUCTOR(0);
        }

        //todo: optimize this to not make an empty buffer just to fill it with a new thing immediately after
        //make sure the lastMatchIndex isn't the end
        if (lastMatchIndex < dataLen) {
            //don't use dataLimit here since we shouldn't pass in infinity to concatBuffer
            stream.buffer = concatBuffer(stream.buffer, data.slice(trailingDataIndex), dataLimit);
        }

        if (stream.emitEvents) {
            emitEvents(stream);
        }
    }
357254
private void flushData() {
    byte[] data = Arrays.copyOf(pendingBuffer, pendingLength);
    pendingLength = 0;
    handler.onData(data);
  }
103362
public void handleData(String data) {
		if (data == null) return;
		text = data;
		sendEvent(new TextInputEvent(this.user, getPayload(), data));
		if (handler != null)
			handler.onType(data);
	}