Pops and returns the first outgoing message from the list.

        If message list currently has no messages, the calling thread will
        be put to sleep until we have at-least one message in the list that
        can be popped and returned.
170529
def next(self):
        
        # We pick the first outgoing available and send it.
        outgoing_msg = self.outgoing_msg_list.pop_first()
        # If we do not have any outgoing msg., we wait.
        if outgoing_msg is None:
            self.outgoing_msg_event.clear()
            self.outgoing_msg_event.wait()
            outgoing_msg = self.outgoing_msg_list.pop_first()

        return outgoing_msg
580401
def PopItem(self):
    
    try:
      # If no timeout is specified the queue will block if empty otherwise
      # a Queue.Empty exception is raised.
      return self._queue.get(timeout=self._timeout)

    except KeyboardInterrupt:
      raise errors.QueueClose

    # If close() is called on the multiprocessing.Queue while it is blocking
    # on get() it will raise IOError.
    except IOError:
      raise errors.QueueClose

    except Queue.Empty:
      raise errors.QueueEmpty
373821
def _parallel_receive_loop(self, seconds_to_wait):
        """"""
        sleep(seconds_to_wait)
        with self._lock:
            self._number_of_threads_receiving_messages += 1
        try:
            with self._lock:
                if self.state.is_waiting_for_start():
                    self.start()
            while True:
                with self.lock:
                    if self.state.is_connection_closed():
                        return
                    self.receive_message()
        finally:
            with self._lock:
                self._number_of_threads_receiving_messages -= 1
1110346
def pop_message(self, till=None):
        

        if till is not None and not isinstance(till, Signal):
            Log.error("Expecting a signal")
        return Null, self.pop(till=till)
751339
public static <T> T getFirstOrNull(List<T> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }
1293106
def _pushMessages(self):
        
        # This continues to get itself called until no msgs are left in list.
        self.showStatus('')
        if len(self._statusMsgsToShow) > 0:
            self.top.after(200, self._pushMessages)
131241
def recv_msg(self):
        ''''''
        if self._index >= self._count:
            return None
        m = self._msgs[self._index]
        self._index += 1
        self.percent = (100.0 * self._index) / self._count
        self.messages[m.get_type()] = m
        return m
726646
def recv(self):
        

        # See if we have a message to process...
        if self._recvbuf:
            return self._recvbuf_pop()

        # If it's closed, don't try to read more data
        if not self._sock:
            raise ConnectionClosed("Connection closed")

        # OK, get some data from the socket
        while True:
            try:
                data = self._sock.recv(4096)
            except socket.error:
                # We'll need to re-raise
                e_type, e_value, e_tb = sys.exc_info()

                # Make sure the socket is closed
                self.close()

                # Re-raise
                raise e_type, e_value, e_tb

            # Did the connection get closed?
            if not data:
                # There can never be anything in the buffer here
                self.close()
                raise ConnectionClosed("Connection closed")

            # Begin parsing the read-in data
            partial = self._recvbuf_partial + data
            self._recvbuf_partial = ''
            while partial:
                msg, sep, partial = partial.partition('\n')

                # If we have no sep, then it's not a complete message,
                # and the remainder is in msg
                if not sep:
                    self._recvbuf_partial = msg
                    break

                # Parse the message
                try:
                    self._recvbuf.append(json.loads(msg))
                except ValueError as exc:
                    # Error parsing the message; save the exception,
                    # which we will re-raise
                    self._recvbuf.append(exc)

            # Make sure we have a message to return
            if self._recvbuf:
                return self._recvbuf_pop()
293262
def messaging(self):
        
        if self._messaging is None:
            self._messaging = MessagingList(self)
        return self._messaging
753196
void recivedMessage(final ByteBuffer message, final SynchronizeFXTomcatConnection sender) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Received a message in thread: id: " + Thread.currentThread().getName() + ", name: "
                    + Thread.currentThread().getName());
        }
        List<Command> commands;
        try {
            commands = serializer.deserialize(message.array());
        } catch (final SynchronizeFXException e) {
            try {
                sender.getWsOutbound().close(0, null);
            } catch (final IOException e1) {
                callback.onClientConnectionError(sender, new SynchronizeFXException(e1));
            }
            callback.onClientConnectionError(sender, e);
            return;
        }
        synchronized (callback) {
            callback.recive(commands, sender);
        }
    }
939577
private int lockMessages(boolean isolatedRun) throws SIResourceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "lockMessages", new Object[] { this, Boolean.valueOf(isolatedRun) });

        int numOfMsgs = 0;

        _transferredConsumer = null;
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "GatherMessages: " + Boolean.valueOf(_gatherMessages)
                            + ", instance isolatedRun: " + Boolean.valueOf(_isolatedRun)
                            + ", _hasLocalQP: " + Boolean.valueOf(_hasLocalQP));
        // If we're doing an isolated run then we don't want to become ready
        // but we do still want to drain the queue. Unfortunately, if we're remote
        // from the queue we probably won't have a message sat there waiting and
        // therefore we do need to make ourselves ready and issue a request back
        // to the DME. (unless we are gathering in which case we have to treat 
        // the consumer as if it is local)
        if (!isolatedRun || (!_hasLocalQP || _gatherMessages))
        {
            // If the LCP is stopped then do nothing (unless we're an isolated run)
            if (_stopped && !isolatedRun)
            {
                //we're not ready for more messages
                unsetReady();
                //don't try and get any more
                _drainQueue = false;
            }
            else
            {
                // we are ready for new messages, before we look for one on the ItemStream
                // we tell teh COnsumerDispatcher that we're available for messages just to
                // make sure we don't miss one coming in while we're looking on the ItemStream
                // (and not finding any). If we do find a suitable message on the ItemStream
                // we mark ourselves as unready. This obviously introduces the possibility of
                // the ConsumerDispatcher trying to give us a message, but better a false
                // possitive than a message falling down the gap.
                try
                {
                    setReady();
                } catch (SINotPossibleInCurrentConfigurationException e)
                {
                    // No FFDC code needed
                    //don't try and get any more
                    _drainQueue = false;
                }
            }

            // Remember we're in the middle of an isolated run (so that put() knows
            // what to do)
            if (isolatedRun)
                _isolatedRun = isolatedRun;
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, "Instance isolatedRun: " + Boolean.valueOf(_isolatedRun));
        }

        if ((_keyGroup != null) && !_keyGroup.isStarted())
            _drainQueue = false;

        boolean consumerReady = true;

        // If the consumer has asked for batches of messages we'll look for that number
        // of available messages on the queue and give them to the asynch consumer all in
        // one go. If this is a stoppable consumer we'd like to keep the number of messages
        // being processed within the number of possible hidden messages (which equals the
        // maxSequentialFailuresThreshold). So we crop the batch size to the remaining
        // space we have left for hidden messages (or one) whichever is the larger.
        // However, that would limit the batch size when there are no problems which is a little
        // rough so we only do the cropping once we've started hiding messages (which can result
        // in a few more messages being processed/hidden to start with but that's life). 
        int currentMaxBatchSize = _maxBatchSize;
        if (_consumerStoppable && (currentMaxBatchSize > 1) && (_hiddenMessages.size() > 0))
        {
            int remainingHiddenSpace = _maxSequentialFailuresThreshold - _hiddenMessages.size();
            if (remainingHiddenSpace < 1)
                remainingHiddenSpace = 1;
            if (remainingHiddenSpace < currentMaxBatchSize)
                currentMaxBatchSize = remainingHiddenSpace;

            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, "lockMessages", "Cropped maxBatchSize to " + currentMaxBatchSize);
        }

        //while we still want more messages
        while ((numOfMsgs < currentMaxBatchSize) && // filled the batch
               _drainQueue && // emptied the queue
               (!_lockRequested || (numOfMsgs == 0)) && // Asked to interupt
               (!_interruptConsumer || (numOfMsgs == 0)) && // Interrupted (ignore first time round)
               (_transferredConsumer == null)) // switched ordered consumer
        {
            SIMPMessage msg = null;

            if (_keyGroup != null)
            {
                // If we are part of a group, we want to remember which member of the group actually gets matched
                // when the filter is called.
                _keyGroup.setConsumerActive(true);
            }

            //try and get a locked eligible message
            msg = getEligibleMsgLocked(null);

            if (msg != null)
            {
                JSLocalConsumerPoint matchingConsumer = this;

                // We've found a message that matches. If we are a member of
                // an ordering group it is possible that this message matches
                // a different member of the group from us. If that is that is
                // the case we have to possibilities....
                // i) If this is the fist message in the batch we can pass the locked
                // message to the matching consumer for them to process.
                // ii) If we already have messages in our batch we will have to
                // unlock this message and process the batch first.
                if (_keyGroup != null)
                {
                    // find out which member of the group actually got matched
                    matchingConsumer = (JSLocalConsumerPoint) _keyGroup.getMatchingMember(_consumerKey).getConsumerPoint();
                    // and show that we're done with the filter for now
                    _keyGroup.setConsumerActive(false);
                }

                // The message is intended for this consumer
                if (matchingConsumer == this)
                {
                    // If we've got a message then we're no longer interested
                    // in messages straight from the ConsumerDispatcher but if
                    // looking for a batch of messages we may take a long time
                    // to exit this loop, so take ourselves out of the runnin
                    // as soon as possible.
                    if (consumerReady)
                    {
                        consumerReady = false;
                        unsetReady();
                    }

                    // Do we really need this message in the MS?
                    boolean isRecoverable = true;
                    if ((_unrecoverableOptions != Reliability.NONE) &&
                        (msg.getReliability().compareTo(_unrecoverableOptions) <= 0))
                        isRecoverable = false;

                    registerForEvents(msg);

                    //store a reference to the locked message in the LME
                    _allLockedMessages.addNewMessage(msg, true, isRecoverable);

                    //If we were successful, increment our counter
                    numOfMsgs++;

                    // We check for an interupt after every message is locked
                    if (_externalConsumerLock != null)
                        _interruptConsumer = _externalConsumerLock.isLockYieldRequested();
                }
                // The message is intended for another member of the key group
                else
                {
                    // If we already have messages locked to this consumer we must
                    // unlock the last message and process the others first. Then
                    // we can come back and pick this one up later (if it is still
                    // available)
                    if (numOfMsgs > 0)
                    {
                        try
                        {
                            msg.unlockMsg(msg.getLockID(), null, true);
                            msg = null;
                        } catch (MessageStoreException e)
                        {
                            // MessageStoreException shouldn't occur so FFDC.
                            FFDCFilter.processException(
                                                        e,
                                                        "com.ibm.ws.sib.processor.impl.JSLocalConsumerPoint.lockMessages",
                                                        "1:2995:1.22.5.1",
                                                        this);

                            SibTr.exception(tc, e);

                            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                                SibTr.exit(tc, "lockMessages", e);

                            throw new SIResourceException(
                                            nls.getFormattedMessage(
                                                                    "INTERNAL_MESSAGING_ERROR_CWSIP0002",
                                                                    new Object[] {
                                                                                  "com.ibm.ws.sib.processor.impl.JSLocalConsumerPoint",
                                                                                  "1:3008:1.22.5.1",
                                                                                  e },
                                                                    null),
                                            e);
                        }
                    }
                    // This is the only message locked so we can just drive the
                    // correct consumer
                    else
                    {
                        numOfMsgs++;

                        // Mark the fact that we've transferred ownership of a locked message
                        // so that it can be processed by the calling method (outside of any
                        // LCP locks)
                        _transferredConsumer = matchingConsumer;

                        _transferredConsumer.lock();
                        try
                        {
                            _transferredConsumer.unsetReady();
                            _transferredConsumer.addLockedMessage(msg);
                        } finally
                        {
                            _transferredConsumer.unlock();
                        }

                        // We now want to drop out of the loop so we can process this message
                        // with the correct consumer

                        // We check for an interupt after every message is locked
                        if (_externalConsumerLock != null)
                            _interruptConsumer = _externalConsumerLock.isLockYieldRequested();
                    }
                }
            }
            if (msg == null)
            {
                // We have all the messages currently on the
                // queue so we are about to callack to
                // get them processed.

                //stop trying to get any more
                _drainQueue = false;
            }

            // We check for an interupt after every message is locked
            if (_externalConsumerLock != null)
                _interruptConsumer = _externalConsumerLock.isLockYieldRequested();
        } // end while

        // If we're an isolated run and we found a message (i.e. not ready) then
        // no-one will try to deliver a message to us and therefore we can forget
        // that we were ever here. On the other hand, if we couldn't find a message
        // and the queue is remote we need to signal that we're still waiting.
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            SibTr.debug(tc, "Instance isolatedRun: " + Boolean.valueOf(_isolatedRun) +
                            ", method isolatedRun: " + Boolean.valueOf(isolatedRun) +
                            ", ready: " + Boolean.valueOf(_ready));
        if (isolatedRun && !_ready)
            _isolatedRun = false;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "lockMessages", Integer.valueOf(numOfMsgs));

        return numOfMsgs;
    }
919096
public Message receiveMessage()
    {
        while ((m_stack != null) && (m_stack.isEmpty()))
        {
            m_thread = Thread.currentThread();
            synchronized(m_thread)
            {
                m_bWaiting = true;
                if (m_stack.isEmpty())      // In case a message was added outside the sync block.
                {
                    try {
                        m_thread.wait();
                    } catch (InterruptedException ex)   {
                        m_stack = null; // This causes a null message to return, which tells the receiving loop to stop (halting this thread).
                        m_thread = null;    // Don't free this twice.
                    }
                }
                m_bWaiting = false;     // Notified
            }
        }
        Message message = null;
        if (m_stack != null)
            if (!m_stack.isEmpty())
                message = m_stack.remove(0);
        return message;
    }
1006869
private static <T> T firstOf(final List<T> list) {
        return list.isEmpty()? null: list.get(0);
    }
1055845
function onMessage(obj) {
    var id = obj.id;
    if (!self._matchesPrefix(id)) {
      debug('discarding unscoped message %s', id);
      return;
    }
    var cb = self._registry.get(id);
    if (cb) {
      process.nextTick(function () {
        debug('received message %s', id);
        // Ensure that the initial callback gets called asynchronously, even
        // for completely synchronous transports (otherwise the number of
        // pending requests will sometimes be inconsistent between stateful and
        // stateless transports).
        cb(null, Buffer.concat(obj.payload), self._adapter);
      });
    }
  }
361889
def next(self):
        """"""
        if len(self.__data) or self._refresh():
            coll = self.__collection
            return coll.database._fix_outgoing(self.__data.popleft(), coll)
        else:
            raise StopIteration
1050535
def last(sequence, message=None):
    
    try:
        return sequence.pop()
    except AttributeError:
        return list(sequence).pop()
    except IndexError:
        raise ValueError(message or f'Sequence is empty: {sequence}')
476210
def _check_and_send(self):
        
        if self.transport._stop_event.ready() or not self.transport.greenlet:
            self.log.error("Can't retry - stopped")
            return

        if self.transport._prioritize_global_messages:
            # During startup global messages have to be sent first
            self.transport._global_send_queue.join()

        self.log.debug('Retrying message', receiver=to_normalized_address(self.receiver))
        status = self.transport._address_mgr.get_address_reachability(self.receiver)
        if status is not AddressReachability.REACHABLE:
            # if partner is not reachable, return
            self.log.debug(
                'Partner not reachable. Skipping.',
                partner=pex(self.receiver),
                status=status,
            )
            return
        # sort output by channel_identifier (so global/unordered queue goes first)
        # inside queue, preserve order in which messages were enqueued
        ordered_queue = sorted(
            self._message_queue,
            key=lambda d: d.queue_identifier.channel_identifier,
        )
        message_texts = [
            data.text
            for data in ordered_queue
            # if expired_gen generator yields False, message was sent recently, so skip it
            if next(data.expiration_generator)
        ]

        def message_is_in_queue(data: _RetryQueue._MessageData) -> bool:
            return any(
                isinstance(data.message, RetrieableMessage) and
                send_event.message_identifier == data.message.message_identifier
                for send_event in self.transport._queueids_to_queues[data.queue_identifier]
            )

        # clean after composing, so any queued messages (e.g. Delivered) are sent at least once
        for msg_data in self._message_queue[:]:
            remove = False
            if isinstance(msg_data.message, (Delivered, Ping, Pong)):
                # e.g. Delivered, send only once and then clear
                # TODO: Is this correct? Will a missed Delivered be 'fixed' by the
                #       later `Processed` message?
                remove = True
            elif msg_data.queue_identifier not in self.transport._queueids_to_queues:
                remove = True
                self.log.debug(
                    'Stopping message send retry',
                    queue=msg_data.queue_identifier,
                    message=msg_data.message,
                    reason='Raiden queue is gone',
                )
            elif not message_is_in_queue(msg_data):
                remove = True
                self.log.debug(
                    'Stopping message send retry',
                    queue=msg_data.queue_identifier,
                    message=msg_data.message,
                    reason='Message was removed from queue',
                )

            if remove:
                self._message_queue.remove(msg_data)

        if message_texts:
            self.log.debug('Send', receiver=pex(self.receiver), messages=message_texts)
            self.transport._send_raw(self.receiver, '\n'.join(message_texts))