Process a sent message. This is used internally to the SDK and should not be called directly by your client application.

@param message The body of the message
@param timestamp The message timestamp
180931
public void didSendMessage(final String message, final Date timestamp) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (null != listenerReference) {
                    Listener listener = listenerReference.get();
                    if (null != listener) {
                        listener.onMessage(message, timestamp, RespokeEndpoint.this, true);
                    }
                }
            }
        });
    }
634776
public void sendMessage(final byte[] message) {
        try {
            session.sendMessage(new BinaryMessage(message));
        }
        catch (IOException e) {
            logger.error("[sendBinaryMessage]", e);
        }
    }
79128
void handleFragmentTaskMessage(FragmentTaskMessage message)
    {
        FragmentTaskMessage msg = message;
        long newSpHandle;
        //The site has been marked as non-leader. The follow-up batches or fragments are processed here
        if (!message.isForReplica() && (m_isLeader || message.isExecutedOnPreviousLeader())) {
            // message processed on leader
            // Quick hack to make progress...we need to copy the FragmentTaskMessage
            // before we start mucking with its state (SPHANDLE).  We need to revisit
            // all the messaging mess at some point.
            msg = new FragmentTaskMessage(message.getInitiatorHSId(),
                    message.getCoordinatorHSId(), message);
            //Not going to use the timestamp from the new Ego because the multi-part timestamp is what should be used
            msg.setTimestamp(message.getTimestamp());
            msg.setExecutedOnPreviousLeader(message.isExecutedOnPreviousLeader());
            if (!message.isReadOnly()) {
                TxnEgo ego = advanceTxnEgo();
                newSpHandle = ego.getTxnId();

                if (m_outstandingTxns.get(msg.getTxnId()) == null) {
                    updateMaxScheduledTransactionSpHandle(newSpHandle);
                }
            } else {
                newSpHandle = getMaxScheduledTxnSpHandle();
            }

            msg.setSpHandle(newSpHandle);
            msg.setLastSpUniqueId(m_uniqueIdGenerator.getLastUniqueId());
            logRepair(msg);
            if (msg.getInitiateTask() != null) {
                msg.getInitiateTask().setSpHandle(newSpHandle);//set the handle
                //Trigger reserialization so the new handle is used
                msg.setStateForDurability(msg.getInitiateTask(), msg.getInvolvedPartitions());
            }

            /*
             * If there a replicas to send it to, forward it!
             * Unless... it's read only AND not a sysproc. Read only sysprocs may expect to be sent
             * everywhere.
             * In that case don't propagate it to avoid a determinism check and extra messaging overhead
             */
            if (IS_KSAFE_CLUSTER && (!message.isReadOnly() || msg.isSysProcTask())) {
                for (long hsId : m_sendToHSIds) {
                    FragmentTaskMessage finalMsg = msg;
                    final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.SPI);
                    if (traceLog != null) {
                        traceLog.add(() -> VoltTrace.beginAsync("replicatefragment",
                                                                MiscUtils.hsIdPairTxnIdToString(m_mailbox.getHSId(), hsId, finalMsg.getSpHandle(), finalMsg.getTxnId()),
                                                                "txnId", TxnEgo.txnIdToString(finalMsg.getTxnId()),
                                                                "dest", CoreUtils.hsIdToString(hsId)));
                    }
                }

                FragmentTaskMessage replmsg =
                    new FragmentTaskMessage(m_mailbox.getHSId(),
                            m_mailbox.getHSId(), msg);
                replmsg.setForReplica(true);
                replmsg.setTimestamp(msg.getTimestamp());
                // K-safety cluster doesn't always mean partition has replicas,
                // node failure may reduce the number of replicas for each partition.
                if (m_sendToHSIds.length > 0) {
                    m_mailbox.send(m_sendToHSIds,replmsg);
                }
                DuplicateCounter counter;
                /*
                 * Non-determinism should be impossible to happen with MP fragments.
                 * if you see "MP_DETERMINISM_ERROR" as procedure name in the crash logs
                 * something has horribly gone wrong.
                 */
                if (message.getFragmentTaskType() != FragmentTaskMessage.SYS_PROC_PER_SITE) {
                    counter = new DuplicateCounter(
                            msg.getCoordinatorHSId(),
                            msg.getTxnId(),
                            m_replicaHSIds,
                            replmsg);
                }
                else {
                    counter = new SysProcDuplicateCounter(
                            msg.getCoordinatorHSId(),
                            msg.getTxnId(),
                            m_replicaHSIds,
                            replmsg);
                }
                safeAddToDuplicateCounterMap(new DuplicateCounterKey(message.getTxnId(), newSpHandle), counter);
            }
        } else {
            // message processed on replica
            logRepair(msg);
            newSpHandle = msg.getSpHandle();
            setMaxSeenTxnId(newSpHandle);
        }

        Iv2Trace.logFragmentTaskMessage(message, m_mailbox.getHSId(), newSpHandle, false);
        doLocalFragmentOffer(msg);
    }
739959
@Override
	public void receiveResponse(Tree message) {

		// Verify protocol version
		if (checkVersion) {
			String ver = message.get("ver", "unknown");
			if (!PROTOCOL_VERSION.equals(ver)) {
				logger.warn("Invalid protocol version (" + ver + ")!");
				return;
			}
		}

		// Get response's unique ID
		String id = message.get("id", (String) null);
		if (id == null || id.isEmpty()) {
			logger.warn("Missing \"id\" property!", message);
			return;
		}

		// Incoming (response) stream handling
		IncomingStream responseStream;
		responseStreamReadLock.lock();
		try {
			responseStream = responseStreams.get(id);
		} finally {
			responseStreamReadLock.unlock();
		}
		if (responseStream != null) {
			boolean remove = false;
			try {
				if (responseStream.receive(message)) {
					remove = true;
				}
			} catch (Throwable error) {
				remove = true;

				// Write error to log file
				if (writeErrorsToLog) {
					logger.error("Unexpected error occurred while streaming!", error);
				}
			}
			if (remove) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			return;
		}
		if (message.get("stream", false)) {
			responseStreamWriteLock.lock();
			try {
				responseStream = responseStreams.get(id);
				if (responseStream == null) {
					responseStream = new IncomingStream(nodeID, scheduler, streamTimeout);
					responseStreams.put(id, responseStream);
				}
			} finally {
				responseStreamWriteLock.unlock();
			}
			if (responseStream.receive(message)) {
				responseStreamWriteLock.lock();
				try {
					responseStreams.remove(id);
				} finally {
					responseStreamWriteLock.unlock();
				}
			}
			message.putObject("data", responseStream.getPacketStream());
		}

		// Get stored promise
		PendingPromise pending = promises.remove(id);
		if (pending == null) {
			logger.warn("Unknown (maybe timeouted) response received!", message);
			return;
		}
		try {

			// Get response status (successed or not?)
			boolean success = message.get("success", true);
			if (success) {

				// Ok -> resolve
				pending.promise.complete(message.get("data"));

			} else {

				// Failed -> reject
				Tree error = message.get("error");
				MoleculerError moleculerError;
				if (error == null) {
					moleculerError = new MoleculerError("Remote invocation failed!", null, "MoleculerError",
							pending.nodeID, false, 500, "UNKNOWN_ERROR", message);
				} else {
					moleculerError = MoleculerErrorUtils.create(error);
				}

				pending.promise.complete(moleculerError);
				logger.error(moleculerError.getMessage(), moleculerError);

				return;
			}
		} catch (Throwable cause) {
			logger.error("Unable to pass on incoming response!", cause);
		}
	}
1119929
private void send( String message ) {

		if( ! this.enabled.get()) {
			this.logger.finest( "Notifications were disabled by the DM." );

		} else if( message == null ) {
			this.logger.finest( "No message to send to web socket clients." );

		} else synchronized( SESSIONS ) {
			for( Session session : SESSIONS ) {
				try {
					this.logger.finest( "Sending a message to a web socket client..." );
					session.getRemote().sendString( message );

				} catch( IOException e ) {
					StringBuilder sb = new StringBuilder( "A notification could not be propagated for session " );
					sb.append( session.getRemoteAddress());
					sb.append( "." );
					if( ! Utils.isEmptyOrWhitespaces( e.getMessage()))
						sb.append( " " + e.getMessage());

					this.logger.severe( sb.toString());
					Utils.logException( this.logger, e );
				}
			}
		}
	}
531477
@Override
  public void writePayload(InputStream message) {
    verifyNotClosed();
    messagesBuffered++;
    currentMessageSeqNo++;
    currentMessageWireSize = 0;
    statsTraceCtx.outboundMessage(currentMessageSeqNo);
    boolean compressed = messageCompression && compressor != Codec.Identity.NONE;
    int written = -1;
    int messageLength = -2;
    try {
      messageLength = getKnownLength(message);
      if (messageLength != 0 && compressed) {
        written = writeCompressed(message, messageLength);
      } else {
        written = writeUncompressed(message, messageLength);
      }
    } catch (IOException e) {
      // This should not be possible, since sink#deliverFrame doesn't throw.
      throw Status.INTERNAL
          .withDescription("Failed to frame message")
          .withCause(e)
          .asRuntimeException();
    } catch (RuntimeException e) {
      throw Status.INTERNAL
          .withDescription("Failed to frame message")
          .withCause(e)
          .asRuntimeException();
    }

    if (messageLength != -1 && written != messageLength) {
      String err = String.format("Message length inaccurate %s != %s", written, messageLength);
      throw Status.INTERNAL.withDescription(err).asRuntimeException();
    }
    statsTraceCtx.outboundUncompressedSize(written);
    statsTraceCtx.outboundWireSize(currentMessageWireSize);
    statsTraceCtx.outboundMessageSent(currentMessageSeqNo, currentMessageWireSize, written);
  }
173714
public void processThisMessage()
    {
        Utility.getLogger().info("On message called in receiving process");
        try {
            BaseMessage messageIn = this.getMessage();
            if (messageIn != null)
            {
                BaseMessage messageReply = this.createReplyMessage(messageIn);
                this.moveScreenParamsToMessage(messageReply);
                // Step 2 - Get the body part of the message
                this.getTransport().setupReplyMessage(messageReply, messageIn, MessageInfoTypeModel.REPLY, MessageTypeModel.MESSAGE_IN);
            
                this.getTransport().processIncomingMessage(messageReply, null);
            }
        } catch(Exception ex) {
            ex.printStackTrace();
            Debug.print(ex, "Error in processing or replying to a message");
        }
    }
1135105
public void send(Message message)
  {
    Transport smtp = null;

    try {
      smtp = _session.getTransport("smtp");

      smtp.connect();

      smtp.send(message, _to);

      log.fine(this + " sent mail to " + _to[0]);
    } catch (RuntimeException e) {
      throw e;
    } catch (Exception e) {
      throw new RuntimeException(e);
    } finally {
      try {
        if (smtp != null)
          smtp.close();
      } catch (Exception e) {
        log.log(Level.FINER, e.toString(), e);
      }
    }
  }
148606
def process_message(self, message):
        
        try:
            self.logger.debug("Received message %s with id %r.", message, message.message_id)
            self.broker.emit_before("process_message", message)

            res = None
            if not message.failed:
                actor = self.broker.get_actor(message.actor_name)
                res = actor(*message.args, **message.kwargs)

            self.broker.emit_after("process_message", message, result=res)

        except SkipMessage:
            self.logger.warning("Message %s was skipped.", message)
            self.broker.emit_after("skip_message", message)

        except BaseException as e:
            # Stuff the exception into the message [proxy] so that it
            # may be used by the stub broker to provide a nicer
            # testing experience.
            message.stuff_exception(e)

            if isinstance(e, RateLimitExceeded):
                self.logger.warning("Rate limit exceeded in message %s: %s.", message, e)
            else:
                self.logger.warning("Failed to process message %s with unhandled exception.", message, exc_info=True)

            self.broker.emit_after("process_message", message, exception=e)

        finally:
            # NOTE: There is no race here as any message that was
            # processed must have come off of a consumer.  Therefore,
            # there has to be a consumer for that message's queue so
            # this is safe.  Probably.
            self.consumers[message.queue_name].post_process_message(message)
            self.work_queue.task_done()
949509
@Override
    public void sendMsg(Message message) {
        try {
            message.setSender(this.getID());
            ShanksAgent receiver = this.simulation.getAgent(message
                    .getReceiver());
            receiver.putMessegaInInbox(message);
            logger.finer("Sent message from Agent: " + this.getID()
                    + " to Agent: " + message.getReceiver());
        } catch (UnkownAgentException e) {
            logger.severe("UnkownAgentException: " + e.getMessage());
            e.printStackTrace();
        } catch (ShanksException e) {
            e.printStackTrace();
        }
    }
1199194
public void handleIv2InitiateTaskMessage(Iv2InitiateTaskMessage message)
    {
        final String procedureName = message.getStoredProcedureName();

        /*
         * If this is CL replay, use the txnid from the CL and use it to update the current txnid
         */
        long mpTxnId;
        //Timestamp is actually a pre-IV2ish style time based transaction id
        long timestamp = Long.MIN_VALUE;

        // Update UID if it's for replay
        if (message.isForReplay()) {
            timestamp = message.getUniqueId();
            m_uniqueIdGenerator.updateMostRecentlyGeneratedUniqueId(timestamp);
        } else  {
            timestamp = m_uniqueIdGenerator.getNextUniqueId();
        }

        TxnEgo ego = advanceTxnEgo();
        mpTxnId = ego.getTxnId();

        final String threadName = Thread.currentThread().getName(); // Thread name has to be materialized here
        final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.MPI);
        if (traceLog != null) {
            traceLog.add(() -> VoltTrace.meta("process_name", "name", CoreUtils.getHostnameOrAddress()))
                    .add(() -> VoltTrace.meta("thread_name", "name", threadName))
                    .add(() -> VoltTrace.meta("thread_sort_index", "sort_index", Integer.toString(100)))
                    .add(() -> VoltTrace.beginAsync("initmp", mpTxnId,
                                                    "txnId", TxnEgo.txnIdToString(mpTxnId),
                                                    "ciHandle", message.getClientInterfaceHandle(),
                                                    "name", procedureName,
                                                    "read", message.isReadOnly()));
        }

        // Don't have an SP HANDLE at the MPI, so fill in the unused value
        Iv2Trace.logIv2InitiateTaskMessage(message, m_mailbox.getHSId(), mpTxnId, Long.MIN_VALUE);

        // Handle every-site system procedures (at the MPI)
        final Config sysprocConfig = SystemProcedureCatalog.listing.get(procedureName);
        if (sysprocConfig != null &&  sysprocConfig.getEverysite()) {
            // Send an SP initiate task to all remote sites
            final Long localId = m_mailbox.getHSId();
            Iv2InitiateTaskMessage sp = new Iv2InitiateTaskMessage(
                    localId, // make the MPI the initiator.
                    message.getCoordinatorHSId(),
                    m_repairLogTruncationHandle,
                    mpTxnId,
                    timestamp,
                    message.isReadOnly(),
                    true, // isSinglePartition
                    null,
                    message.getStoredProcedureInvocation(),
                    message.getClientInterfaceHandle(),
                    message.getConnectionId(),
                    message.isForReplay());
            DuplicateCounter counter = new DuplicateCounter(
                    message.getInitiatorHSId(),
                    mpTxnId,
                    m_iv2Masters,
                    message);
            safeAddToDuplicateCounterMap(mpTxnId, counter);
            EveryPartitionTask eptask =
                new EveryPartitionTask(m_mailbox, m_pendingTasks, sp,
                        m_iv2Masters);
            m_pendingTasks.offer(eptask);
            return;
        }
        // Create a copy so we can overwrite the txnID so the InitiateResponse will be
        // correctly tracked.
        Iv2InitiateTaskMessage mp =
            new Iv2InitiateTaskMessage(
                    message.getInitiatorHSId(),
                    message.getCoordinatorHSId(),
                    m_repairLogTruncationHandle,
                    mpTxnId,
                    timestamp,
                    message.isReadOnly(),
                    message.isSinglePartition(),
                    null,
                    message.getStoredProcedureInvocation(),
                    message.getClientInterfaceHandle(),
                    message.getConnectionId(),
                    message.isForReplay());
        // Multi-partition initiation (at the MPI)
        MpProcedureTask task = null;
        if (isNpTxn(message) && NP_PROCEDURE_CLASS.hasProClass()) {
            Set<Integer> involvedPartitions = getBalancePartitions(message);
            if (involvedPartitions != null) {
                HashMap<Integer, Long> involvedPartitionMasters = Maps.newHashMap(m_partitionMasters);
                involvedPartitionMasters.keySet().retainAll(involvedPartitions);

                task = instantiateNpProcedureTask(m_mailbox, procedureName,
                        m_pendingTasks, mp, involvedPartitionMasters,
                        m_buddyHSIds.get(m_nextBuddy), false, m_hostId);
            }

            // if cannot figure out the involved partitions, run it as an MP txn
        }

        int[] nPartitionIds = message.getNParitionIds();
        if (nPartitionIds != null) {
            HashMap<Integer, Long> involvedPartitionMasters = new HashMap<>();
            for (int partitionId : nPartitionIds) {
                involvedPartitionMasters.put(partitionId, m_partitionMasters.get(partitionId));
            }

            task = instantiateNpProcedureTask(m_mailbox, procedureName,
                    m_pendingTasks, mp, involvedPartitionMasters,
                    m_buddyHSIds.get(m_nextBuddy), false, m_hostId);
        }


        if (task == null) {
            task = new MpProcedureTask(m_mailbox, procedureName,
                    m_pendingTasks, mp, m_iv2Masters, m_partitionMasters,
                    m_buddyHSIds.get(m_nextBuddy), false, m_hostId, false);
        }

        m_nextBuddy = (m_nextBuddy + 1) % m_buddyHSIds.size();
        m_outstandingTxns.put(task.m_txnState.txnId, task.m_txnState);
        m_pendingTasks.offer(task);
    }
613351
public int handleMessage(BaseMessage message)
    {
        Utility.getLogger().info("RemoteQueue handling message " + message);
        if (message.getProcessedByClientSession() == this.getParentSession())
            return DBConstants.NORMAL_RETURN;     // Do not process this message (the client has already taken care of it).
//?        if (message.getProcessedByClientSession() instanceof RemoteObject)
//?            if (this.getParentSession() instanceof RemoteObject) // Always
//?                if (((RemoteObject)this.getParentSession()).getRef().remoteEquals(((RemoteObject)message.getProcessedByClientSession()).getRef()))
//?                    return DBConstants.NORMAL_RETURN;   // Same client.
        if (message == m_messageLastMessage)
            return DBConstants.NORMAL_RETURN;   // Don't send a message to the same client twice.
        m_messageLastMessage = message;
        this.getMessageStack().sendMessage(message);
        return DBConstants.NORMAL_RETURN;
    }
777997
@Override
    public void onReceive(Object message) {
        if (message instanceof NewMessage) {
            NewMessage newMessage = (NewMessage) message;
            onNewMessage(newMessage.getPeer(), newMessage.getSender(), newMessage.getSortDate(),
                    newMessage.getContentDescription(), newMessage.getHasCurrentUserMention(),
                    newMessage.getUnreadMessagesCount(), newMessage.getUnreadDialogsCount());
        } else if (message instanceof MessagesRead) {
            MessagesRead read = (MessagesRead) message;
            onMessagesRead(read.getPeer(), read.getFromDate());
        } else if (message instanceof PauseNotifications) {
            onNotificationsPaused();
        } else if (message instanceof ResumeNotifications) {
            onNotificationsResumed();
        } else {
            super.onReceive(message);
        }
    }
608275
@Override
  public void consume(final RawMessage message) {
    interest.handleInboundStreamMessage(addressType, RawMessage.copy(message));
  }
446941
@Override
    public void onMessage(Message message) {
        StandardLogger logger = LoggerUtil.getStandardLogger();
        String logtag = "EngineDriver.T" + Thread.currentThread().getId() + " - ";

        try {
            String txt = ((TextMessage) message).getText();
            if (logger.isDebugEnabled()) {
                logger.debug("JMS Spring InternalEvent Listener receives request: " + txt);
            }
            logger.info(logtag + "starts processing");
            String messageId = message.getJMSCorrelationID();
            ProcessEngineDriver driver = new ProcessEngineDriver();
            driver.processEvents(messageId, txt);
        } catch (Throwable e) { // only possible when failed to get ProcessManager ejb
            logger.severeException(logtag + "process exception " + e.getMessage(), e);
        }

    }
776168
async def _process_message(self, message):
        
        self._pending_ack.add(message.msg_id)
        handler = self._handlers.get(message.obj.CONSTRUCTOR_ID,
                                     self._handle_update)
        await handler(message)
209289
public static void pass(String message) {
        if (Boolean.getBoolean("visibleassertions.silence") || Boolean.getBoolean("visibleassertions.silence.passes")) {
            return;
        }
        System.out.println("        " + green(TICK_MARK + " " + message));
    }