/*
@see com.ibm.ws.http.channel.internal.HttpServiceContextImpl#
checkIncomingMessageLimit(int)
185907
@Override
    protected void checkIncomingMessageLimit(long addition) throws MessageTooLargeException {
        super.addToIncomingMsgSize(addition);
        // check if we even need to bother comparing sizes against limits
        if (HttpConfigConstants.UNLIMITED == getHttpConfig().getMessageSizeLimit()) {
            return;
        }
        if (queryIncomingMsgSize() > getHttpConfig().getMessageSizeLimit()) {
            // over channel limit, see if the factory has a system wide "large" limit
            HttpInboundChannelFactory factory = this.myLink.getChannel().getFactory();
            if (factory.getConfig().areMessagesLimited() && factory.allowLargeMessage(queryIncomingMsgSize())) {
                this.bContainsLargeMessage = true;
            } else {
                throw new MessageTooLargeException("Size=" + queryIncomingMsgSize());
            }
        }
    }
1024597
private void checkMessage(Message msg) throws MessagingException {
        if (msg == null) {
            throw new MessagingException("Message is null");
        }
        if (!(msg instanceof MimeMessage)) {
            throw new MessagingException(
                    "AWS Mail Service can only send MimeMessages");
        }
    }
481845
protected static void checkMessageSize(Object message, long maxMessageSize) {
        if (maxMessageSize != -1) {
            final long messageSize =
                    (message instanceof String ? ((String) message).getBytes(Charset.defaultCharset()).length
                            : ((ByteBuffer) message).remaining());

            if (messageSize > maxMessageSize) {
                throw new MessageTooBigException(
                        Messages.get("web.socket.error.message.too.long", maxMessageSize, messageSize)
                );
            }
        }
    }
275330
@Override
    public void messageReceived(NextFilter nextFilter, S session,
            AmqpSecureMessage message) throws Exception {
        nextFilter.messageReceived(session, message); 
    }
974998
private MessageType checkMessageInitialized(MessageType message)
      throws InvalidProtocolBufferException {
    if (message != null && !message.isInitialized()) {
      throw newUninitializedMessageException(message)
          .asInvalidProtocolBufferException()
          .setUnfinishedMessage(message);
    }
    return message;
  }
109624
private MessageProcessorSearchResults matchMessage(MessageItem msg)
                    throws SIDiscriminatorSyntaxException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(
                        tc,
                        "matchMessage",
                        new Object[] { msg });

        //Extract the message from the MessageItem
        JsMessage jsMsg = msg.getMessage();

        //  Match Consumers is only called for PubSub targets.
        TopicAuthorization topicAuth = _messageProcessor.getDiscriminatorAccessChecker();
        MessageProcessorSearchResults searchResults = new MessageProcessorSearchResults(topicAuth);

        // Defect 382250, set the unlockCount from MsgStore into the message
        // in the case where the message is being redelivered.
        int redelCount = msg.guessRedeliveredCount();

        if (redelCount > 0)
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, "Set deliverycount into message: " + redelCount);
            jsMsg.setDeliveryCount(redelCount);
        }

        // Get the matching consumers from the matchspace
        _matchspace.retrieveMatchingOutputHandlers(
                                                   _destination,
                                                   jsMsg.getDiscriminator(),
                                                   (MatchSpaceKey) jsMsg,
                                                   searchResults);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(
                       tc,
                       "matchMessage",
                       new Object[] { searchResults });

        return searchResults;
    }
1307979
Object proceedAndSendMessage(InvocationContext ctx, String topic, boolean jsonPayload) throws Exception {
		MessageToClient messageToClient = new MessageToClient();
		messageToClient.setId(topic);
		Object result = ctx.proceed();
		if(jsonPayload) {
			if(!String.class.isInstance(result)) {
				throw new UnsupportedOperationException("Method annotated JsTopic(jsonPayload=true) must return String type and correct Json.");
			}
			messageToClient.setJson((String) result);
		} else {
			messageToClient.setResponse(result);
		}
		wsEvent.fire(messageToClient);
		return result;
	}
174696
static boolean isStartOfIcuMessage(String part) {
    // ICU messages start with a '{' followed by an identifier, followed by a ',' and then 'plural'
    // or 'select' follows by another comma.
    // the 'startsWith' check is redundant but should allow us to skip using the matcher
    if (!part.startsWith("{")) {
      return false;
    }
    int commaIndex = part.indexOf(',', 1);
    // if commaIndex == 1 that means the identifier is empty, which isn't allowed.
    if (commaIndex <= 1) {
      return false;
    }
    int nextBracketIndex = part.indexOf('{', 1);
    return (nextBracketIndex == -1 || nextBracketIndex > commaIndex)
        && (part.startsWith("plural,", commaIndex + 1)
            || part.startsWith("select,", commaIndex + 1));
  }
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;
	}
349879
public AppValidator succeedsWith(String expectedMessage) {
        stringsToFind.add(expectedMessage);
        stringsToFind.add(APP_START_CODE);
        server.addIgnoredErrors(Collections.singletonList(expectedMessage));
        return this;
    }
624558
public void displayNewIncomingMessageItem(ApptentiveMessage message) {
		messagingActionHandler.sendEmptyMessage(MSG_REMOVE_STATUS);
		// Determine where to insert the new incoming message. It will be in front of any eidting
		// area, i.e. composing, Who Card ...
		int insertIndex = listItems.size(); // If inserted onto the end, then the list will have grown by one.

		outside_loop:
		// Starting at end of list, go back up the list to find the proper place to insert the incoming message.
		for (int i = listItems.size() - 1; i > 0; i--) {
			MessageCenterListItem item = listItems.get(i);
			switch (item.getListItemType()) {
				case MESSAGE_COMPOSER:
				case MESSAGE_CONTEXT:
				case WHO_CARD:
				case STATUS:
					insertIndex--;
					break;
				default:
					// Any other type means we are past the temporary items.
					break outside_loop;
			}
		}
		listItems.add(insertIndex, message);
		messageCenterRecyclerViewAdapter.notifyItemInserted(insertIndex);

		int firstIndex = messageCenterRecyclerView.getFirstVisiblePosition();
		int lastIndex = messageCenterRecyclerView.getLastVisiblePosition();
		boolean composingAreaTakesUpVisibleArea = firstIndex <= insertIndex && insertIndex < lastIndex;
		if (composingAreaTakesUpVisibleArea) {
			View v = messageCenterRecyclerView.getChildAt(0);
			int top = (v == null) ? 0 : v.getTop();
			updateMessageSentStates();
			// Restore the position of listview to composing view
			messagingActionHandler.sendMessage(messagingActionHandler.obtainMessage(MSG_SCROLL_FROM_TOP, insertIndex, top));
		} else {
			updateMessageSentStates();
		}
	}
1196514
private UndeliverableReturnCode checkMessage(SIMPMessage message)
    {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "checkMessage", message);

        UndeliverableReturnCode rc = UndeliverableReturnCode.OK;

        // F001333:E3
        // If the message's reliability equals or is less than the configured ExceptionDiscardReliability
        // then the message shouldn't be sent on to the exception destination, instead it should simply
        // be thrown away (the default setting is BestEffort).

        // We'll always chuck away BestEffort messages, but if we have the original destination we'll base
        // our decision on its configuration
        // (If the _originalDestination is null then we do not have the original destination's config to hand,
        // for example, in the case of  cleaning up a deleted destination)

        Reliability discardReliabilityThreshold = Reliability.BEST_EFFORT_NONPERSISTENT;
        if (_originalDestination != null)
            discardReliabilityThreshold = _originalDestination.getExceptionDiscardReliability();

        if (message.getReliability().compareTo(discardReliabilityThreshold) <= 0)
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, "Message reliability (" + message.getReliability() + ") <= Exception reliability (" +
                                discardReliabilityThreshold + ")");

            rc = UndeliverableReturnCode.DISCARD;
        }

        // Discard messages from temporary destinations.
        else if (_originalDestination != null &&
                 _originalDestination.isTemporary())
            rc = UndeliverableReturnCode.DISCARD;

        // If the discardMessage option is set, then we discard the message rather
        // than send to the exception destination
        else if (Boolean.TRUE.equals(message.getMessage().getReportDiscardMsg()))
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                SibTr.debug(tc, "Message discarded at sender's request");

            rc = UndeliverableReturnCode.DISCARD;
        }

        // Decide whether we want to block the message or not.
        else if (isBlockRequired(message))
            rc = UndeliverableReturnCode.BLOCK;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "checkMessage", rc);

        return rc;
    }
294162
public void setBasicTraceDetail(SIDestinationAddress destinationAddress, 
                                  DestinationType destinationType,
                                  SIBusMessage message)
  {
    if (destinationAddress == null)
    {
      validateAndPutProperty("BusName", "");
      validateAndPutProperty("DestinationName", "");
    }
    else
    {
      validateAndPutProperty("BusName", destinationAddress.getBusName());
      validateAndPutProperty("DestinationName", destinationAddress.getDestinationName());
    }
    
    validateAndPutProperty("DestinationType", destinationType);
    
    if (message == null)
    {
      validateAndPutProperty("SystemMessageID", "");
      validateAndPutProperty("Priority", "");
      validateAndPutProperty("Reliability", "");
      validateAndPutProperty("Discriminator","");
    }
    else
    {
      validateAndPutProperty("SystemMessageID", message.getSystemMessageId());
      validateAndPutProperty("Priority", message.getPriority());
      validateAndPutProperty("Reliability", message.getReliability());
      validateAndPutProperty("Discriminator",message.getDiscriminator());
    }
  }
827296
private int getUnSeenMessageCount() 
   {
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc,"getUnseenMessageCount");
      
      int remain = 0;
      for (int x = nextIndex; x < messages.length; x++)
      {
         if (messages[x] != null) remain++;
      }
      
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc,"getUnseenMessageCount", ""+remain);
      return remain;
   }
738622
public boolean checkInputMessageNumbering(SccpConnectionImpl conn, SequenceNumber sendSequenceNumber,
                                              SequenceNumber receiveSequenceNumber) throws Exception {
        if (sendSequenceNumber != null) {
            if (expectingFirstMessageInputAfterInit && !sendSequenceNumber.equals(new SequenceNumberImpl(0))) {
                // local procedure error
                conn.reset(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
                return false;

            } else if (sendSequenceNumber.equals(sendSequenceNumberExpectedAtInput) && inputWindow.contains(sendSequenceNumber)) {
                sendSequenceNumberExpectedAtInput = sendSequenceNumberExpectedAtInput.nextNumber();

            } else {
                if (!inputWindow.contains(sendSequenceNumber)) {
                    conn.reset(new ResetCauseImpl(ResetCauseValue.REMOTE_PROCEDURE_ERROR_MESSAGE_OUT_OF_WINDOW));

                } else if (!sendSequenceNumber.equals(sendSequenceNumberExpectedAtInput)) {
                    // local procedure error
                    conn.resetSection(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
                }
                return false;
            }
        }

        if (rangeContains(lastReceiveSequenceNumberReceived, this.sendSequenceNumber.nextNumber(), receiveSequenceNumber)) {
            outputWindow.setLowerEdge(receiveSequenceNumber);
        } else {
            conn.resetSection(new ResetCauseImpl(ResetCauseValue.MESSAGE_OUT_OF_ORDER_INCORRECT_PS));
            return false;
        }

        lastReceiveSequenceNumberReceived = receiveSequenceNumber;
        expectingFirstMessageInputAfterInit = false;
        return true;
    }
165940
private final void checkRefCount() 
  {
    if (_refCount < 0)
    {
      SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0001",      
        new Object[] {
          "com.ibm.ws.sib.processor.proxyhandler.MESubscription",
          "1:298:1.55" }) ;
           
      throw new SIErrorException(
          nls.getFormattedMessage(
            "INTERNAL_MESSAGING_ERROR_CWSIP0001",
            new Object[] {
              "com.ibm.ws.sib.processor.proxyhandler.MESubscription",
              "1:305:1.55" },
            null));
    }
  }
997019
public SIBusMessage peek() 
  
  throws SISessionUnavailableException, SIResourceException, SIIncorrectCallException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "peek");
    
    checkValidState("peek");
    
    _localConsumerPoint.checkNotClosed();

    SIBusMessage nextMessage = null;
    
    if(!_seenSingleMessage)
    {
      // Because this message is not in the message store there is no need to copy it
      // before giving it to a caller unless this is pubsub, in which case there may be
      // other subscriptions referencing the same message, in which case we must copy the
      // message (unless the caller indicates that they won't be altering it)
      if(_isPubsub &&
         ((ConnectionImpl)(_localConsumerPoint.getConsumerSession().getConnection())).getMessageCopiedWhenReceived())
      {
        try
        {
          nextMessage = (_singleMessage.getMessage()).getReceived();
        }
        catch (MessageCopyFailedException e)
        {
          FFDCFilter.processException(
            e,
            "com.ibm.ws.sib.processor.impl.SingleLockedMessageEnumerationImpl.peek",
            "1:456:1.44",
            this);
              
          SibTr.exception(tc, e);
          SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0002",
            new Object[] {
              "com.ibm.ws.sib.processor.impl.SingleLockedMessageEnumerationImpl",
              "1:463:1.44",
              e });
            
          _seenSingleMessage = false;
          _messageAvailable = false;
    
          if (TraceComponent.isAnyTracingEnabled() && CoreSPILockedMessageEnumeration.tc.isEntryEnabled())
            SibTr.exit(CoreSPILockedMessageEnumeration.tc, "peek", e);
    
          throw new SIResourceException(
            nls.getFormattedMessage(
              "INTERNAL_MESSAGING_ERROR_CWSIP0002",
              new Object[] {
                "com.ibm.ws.sib.processor.impl.SingleLockedMessageEnumerationImpl",
                "1:477:1.44",
                e },
              null),
            e);
        }
      }
      else
        nextMessage = _singleMessage.getMessage();
    }
    
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "peek", nextMessage);
    return nextMessage;
  }