/*
(non-Javadoc)

@see akka.actor.UntypedActor#onReceive(java.lang.Object)
493298
@Override
    public void onReceive(Object message) throws Exception {
        try {
            if (message instanceof OperationWorkerMsgType) {
                switch ((OperationWorkerMsgType) message) {

                case PROCESS_REQUEST:
                    processMainRequest();
                    break;
                case POLL_PROGRESS:
                    pollProgress();
                    break;
                case OPERATION_TIMEOUT:
                    operationTimeout();
                    break;
                case CANCEL:
                    // use the same function
                    cancel();
                    break;
                }// end switch
            } else if (message instanceof ResponseOnSingeRequest) {
                final ResponseOnSingeRequest myResponse = (ResponseOnSingeRequest) message;
                handleHttpWorkerResponse(myResponse);
            } else {
                unhandled(message);
                throw new ActorMessageTypeInvalidException(
                        "invalid message type to OperationWorker");
            }
        } catch (Exception e) {
            replyErrors(e.toString(), PcStringUtils.printStackTrace(e),
                    PcConstants.NA, PcConstants.NA_INT);
        }
    }
922139
def dataReceived(self, data):
        
        self.connection._iobuf.write(data)
        self.connection.handle_read()
1284030
@Override
    public void doExecute(TestContext context) {
        try {
            Message receivedMessage;
            String selector = MessageSelectorBuilder.build(messageSelector, messageSelectorMap, context);

            //receive message either selected or plain with message receiver
            if (StringUtils.hasText(selector)) {
                receivedMessage = receiveSelected(context, selector);
            } else {
                receivedMessage = receive(context);
            }

            if (receivedMessage == null) {
                throw new CitrusRuntimeException("Failed to receive message - message is not available");
            }

            //validate the message
            validateMessage(receivedMessage, context);
        } catch (IOException e) {
            throw new CitrusRuntimeException(e);
        }
    }
696043
public  void  execute() throws ActivityException{
        isSynchronized = checkIfSynchronized();
        if (!isSynchronized) {
            EventWaitInstance received = registerWaitEvents(false, true);
            if (received!=null)
                resume(getExternalEventInstanceDetails(received.getMessageDocumentId()), received.getCompletionCode());
        }
    }
248052
protected void notifyListener(final ExecutorService executor,
    final Future<?> future, final GenericCompletionListener listener) {
    executor.submit(new Runnable() {
      @Override
      public void run() {
        try {
          listener.onComplete(future);
        } catch(Throwable t) {
          getLogger().warn(
            "Exception thrown wile executing " + listener.getClass().getName()
              + ".operationComplete()", t);
        }
      }
    });
  }
1145212
@Override
    public void onEvent(final ResponseEvent event, long sequence, boolean endOfBatch) throws Exception {
        try {
            CouchbaseMessage message = event.getMessage();
            if (message instanceof SignalConfigReload) {
                configurationProvider.signalOutdated();
            } else if (message instanceof CouchbaseResponse) {
                final CouchbaseResponse response = (CouchbaseResponse) message;
                ResponseStatus status = response.status();
                if (status == ResponseStatus.RETRY) {
                    retry(event, true);
                } else {
                    final Scheduler.Worker worker = environment.scheduler().createWorker();
                    final Subject<CouchbaseResponse, CouchbaseResponse> obs = event.getObservable();
                    worker.schedule(new Action0() {
                        @Override
                        public void call() {
                            try {
                                obs.onNext(response);
                                obs.onCompleted();
                            } catch(Exception ex) {
                                obs.onError(ex);
                            } finally {
                                worker.unsubscribe();
                            }
                        }
                    });
                }
            } else if (message instanceof CouchbaseRequest) {
                retry(event, false);
            } else {
                throw new IllegalStateException("Got message type I do not understand: " + message);
            }
        } finally {
           event.setMessage(null);
           event.setObservable(null);
        }
    }
532425
protected void triggerMediaReceived(String participant) {
        List<JingleListener> listeners = getListenersList();
        for (JingleListener li : listeners) {
            if (li instanceof JingleSessionListener) {
                JingleSessionListener sli = (JingleSessionListener) li;
                sli.sessionMediaReceived(this, participant);
            }
        }
    }
737189
@Override
    public void onReceive(Object message) throws Exception {
        try {
            if (message instanceof RequestWorkerMsgType) {
                switch ((RequestWorkerMsgType) message) {
                case PROCESS_REQUEST:
                    tryCount++;

                    if (tryCount == 1) {
                        sender = getSender();

                        ConnectionlessBootstrap udpClient = bootStrapUdpClient();

                        // Start the connection attempt.
                        ChannelFuture future = udpClient
                                .connect(new InetSocketAddress(targetHost,
                                        udpMeta.getUdpPort()));

                        // first schedule timeout before the sync wait
                        timeoutDuration = Duration.create(
                                actorMaxOperationTimeoutSec, TimeUnit.SECONDS);

                        timeoutMessageCancellable = getContext()
                                .system()
                                .scheduler()
                                .scheduleOnce(
                                        timeoutDuration,
                                        getSelf(),
                                        RequestWorkerMsgType.PROCESS_ON_TIMEOUT,
                                        getContext().system().dispatcher(),
                                        getSelf());

                        // Wait until the connection attempt succeeds or fails.
                        channel = future.awaitUninterruptibly().getChannel();
                        ChannelFuture requestFuture = null;

                        // Sends the line to server need. line ending
                        requestFuture = channel.write(udpMeta.getCommand()
                                + "\r\n");

                        // Wait until all messages are flushed before closing
                        // the channel.
                        if (requestFuture != null) {
                            requestFuture.await();
                        }
                    } else {
                        getLogger().error(
                                "duplicated PROCESS_REQUEST msg. ignore...");
                    }
                    break;

                case CANCEL:
                    if (sender == null)
                        sender = getSender();
                    getLogger().info(
                            "UDP Request was CANCELLED.................{}",
                            targetHost);
                    cancelCancellable();
                    reply(null, true, PcConstants.REQUEST_CANCELED,
                            PcConstants.REQUEST_CANCELED, PcConstants.NA,
                            PcConstants.NA_INT);
                    break;

                case PROCESS_ON_EXCEPTION:

                    String errorSummary = PcErrorMsgUtils.replaceErrorMsg(cause
                            .toString());
                    String stackTrace = PcStringUtils.printStackTrace(cause);
                    cancelCancellable();
                    reply(null, true, errorSummary, stackTrace, PcConstants.NA,
                            PcConstants.NA_INT);

                    break;

                case PROCESS_ON_TIMEOUT:

                    getLogger().error("PROCESS_ON_TIMEOUT.................{}",
                            targetHost);
                    cancelCancellable();

                    String errorMsg = String
                            .format("UdpWorker Timedout after %d SEC (no response but no exception catched). Check URL: may be very slow or stuck.",
                                    actorMaxOperationTimeoutSec);

                    reply(null, true, errorMsg, errorMsg, PcConstants.NA,
                            PcConstants.NA_INT);
                    break;

                case CHECK_FUTURE_STATE:
                default:
                    sender = getSender();
                    this.cause = new ActorMessageTypeInvalidException(
                            "ActorMessageTypeInvalidException error for on "
                                    + this.targetHost);
                    getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION,
                            getSelf());
                    break;
                }
            } else {
                unhandled(message);
                sender = getSender();
                this.cause = new ActorMessageTypeInvalidException(
                        "ActorMessageTypeInvalidException error for UDP on "
                                + this.targetHost);
                getSelf().tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION,
                        getSelf());
            }
        } catch (Exception e) {
            this.cause = e;
            getSelf()
                    .tell(RequestWorkerMsgType.PROCESS_ON_EXCEPTION, getSelf());
        }
    }
1284867
@Override
    public void messageReceived(IoSession session, Object message)
            throws Exception {
        chain.execute(null, session, message);
    }
569567
protected void fireFrameReceived(final CEMI frame)
	{
		final FrameEvent fe = new FrameEvent(this, frame);
		listeners.fire(l -> l.frameReceived(fe));
	}
1104629
private static function onReceivedMessage(string $event, $data)
    {
        foreach (self::$onMessage[$event] ?? [] as $callback) {
            asyncCall($callback, $data);
        }
    }
290228
@Override
  public void onNext(final RemoteMessage<EvaluatorShimProtocol.EvaluatorShimControlProto> remoteMessage) {
    final EvaluatorShimProtocol.EvaluatorShimCommand command = remoteMessage.getMessage().getCommand();
    switch (command) {
    case LAUNCH_EVALUATOR:
      LOG.log(Level.INFO, "Received a command to launch the Evaluator.");
      this.threadPool.submit(new Runnable() {
        @Override
        public void run() {
          EvaluatorShim.this.onEvaluatorLaunch(remoteMessage.getMessage().getEvaluatorLaunchCommand(),
              remoteMessage.getMessage().getEvaluatorConfigString(),
              remoteMessage.getMessage().getEvaluatorFileResourcesUrl());
        }
      });
      break;

    case TERMINATE:
      LOG.log(Level.INFO, "Received a command to terminate the EvaluatorShim.");
      this.threadPool.submit(new Runnable() {
        @Override
        public void run() {
          EvaluatorShim.this.onStop();
        }
      });
      break;

    default:
      LOG.log(Level.WARNING, "An unknown command was received by the EvaluatorShim: {0}.", command);
      throw new IllegalArgumentException("An unknown command was received by the EvaluatorShim.");
    }
  }
273811
@Override
	public void on(String name, Tree payload, Groups groups, boolean broadcast) throws Exception {

		// A.) Async invocation
		if (asyncLocalInvocation) {
			executor.execute(() -> {
				try {
					listener.on(payload);
				} catch (Exception cause) {
					logger.warn("Unable to invoke local listener!", cause);
				}
			});
			return;
		}

		// B.) Faster in-process (direct) invocation
		listener.on(payload);
	}
720861
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
        byte[] rpcResponse = (byte[]) e.getMessage();
        // remove marking
        Xdr x = RecordMarkingUtil.removeRecordMarking(rpcResponse);
        // remove the request from timeout manager map
        int xid = x.getXid();
        _connection.notifySender(Integer.valueOf(xid), x);
    }
420176
public void process(final boolean asynch)
          throws NotificationException {
    if (asynch) {
      try {
        consumer.setMessageListener(this);
        return;
      } catch (final JMSException je) {
        throw new NotificationException(je);
      }
    }

    while (running) {
      final Message m = conn.receive();

      if (m == null) {
        running = false;
        return;
      }
      onMessage(m);
    }
  }
1215401
public void connectedReceived() {
        if (null != listenerReference) {
            final Listener listener = listenerReference.get();
            if (null != listener) {
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    public void run() {
                        if (isActive()) {
                            listener.onConnected(RespokeCall.this);
                        }
                    }
                });
            }
        }
    }
274282
public void setPresence(Object newPresence, final Respoke.TaskCompletionListener completionListener) {
        if (isConnected()) {
            Object presenceToSet = newPresence;

            if (null == presenceToSet) {
                presenceToSet = "available";
            }

            JSONObject typeData = new JSONObject();
            JSONObject data = new JSONObject();

            try {
                typeData.put("type", presenceToSet);
                data.put("presence", typeData);

                final Object finalPresence = presenceToSet;

                signalingChannel.sendRESTMessage("post", "/v1/presence", data, new RespokeSignalingChannel.RESTListener() {
                    @Override
                    public void onSuccess(Object response) {
                        presence = finalPresence;

                       Respoke.postTaskSuccess(completionListener);
                    }

                    @Override
                    public void onError(final String errorMessage) {
                        Respoke.postTaskError(completionListener, errorMessage);
                    }
                });
            } catch (JSONException e) {
                Respoke.postTaskError(completionListener, "Error encoding presence to json");
            }
        } else {
            Respoke.postTaskError(completionListener, "Can't complete request when not connected. Please reconnect!");
        }
    }