/*
(non-Javadoc)
@see com.popbill.api.MessageService#sendLMS(java.lang.String, com.popbill.api.message.Message[], java.util.Date, java.lang.String)
962011
@Override
    public String sendLMS(String CorpNum, Message[] Messages, Date reserveDT,
                          String UserID) throws PopbillException {
        return sendLMS(CorpNum, null, null, null, Messages, reserveDT, UserID);
    }
1270503
private <M extends MessageHeaders<EmptyRequestBody, P, U>, U extends MessageParameters, P extends ResponseBody> CompletableFuture<P>
			sendRequest(M messageHeaders, U messageParameters) {
		return sendRequest(messageHeaders, messageParameters, EmptyRequestBody.getInstance());
	}
935500
@Override
    public String sendMMS(String CorpNum, Message[] Messages, File file,
                          Date reserveDT, String UserID, String requestNum) throws PopbillException {

        return sendMMS(CorpNum, null, null, null, Messages, file, reserveDT, UserID, requestNum);
    }
319434
@Override
    public void action(String queueUrl, List<String> receiptHandles) throws JMSException {
        if (receiptHandles == null || receiptHandles.isEmpty()) {
            return;
        }

        List<DeleteMessageBatchRequestEntry> deleteMessageBatchRequestEntries = new ArrayList<DeleteMessageBatchRequestEntry>();
        int batchId = 0;
        for (String receiptHandle : receiptHandles) {
            // Remove the message from queue of unAckMessages
            unAckMessages.poll();
            
            DeleteMessageBatchRequestEntry entry = new DeleteMessageBatchRequestEntry(
                    Integer.toString(batchId), receiptHandle);
            deleteMessageBatchRequestEntries.add(entry);
            batchId++;
        }
        
        DeleteMessageBatchRequest deleteMessageBatchRequest = new DeleteMessageBatchRequest(
                queueUrl, deleteMessageBatchRequestEntries);
        /**
         * TODO: If one of the batch calls fail, then the remaining messages on
         * the batch will not be deleted, and will be visible and delivered as
         * duplicate after visibility timeout expires.
         */
        amazonSQSClient.deleteMessageBatch(deleteMessageBatchRequest);
    }
262950
public void sendLinkMessage( MessageItem msgItem, boolean rollback) 
   throws SIResourceException
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "sendLinkMessage", msgItem);
        
    JsMessage jsMsg=null;
    try
    {
      //defect 245624
      jsMsg = msgItem.getMessage().getReceived();
    }
    catch(MessageCopyFailedException e)
    {
      FFDCFilter.processException(
        e,
        "com.ibm.ws.sib.processor.impl.PubSubOutputHandler.sendLinkMessage",
        "1:1097:1.164.1.5",
        this);
        
      if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
        SibTr.exit(tc, "sendLinkMessage", "SIErrorException");  
      throw new SIErrorException(e);
    }
     
    SIBUuid8[] fromTo = new SIBUuid8[1];
    fromTo[0] = _targetMEUuid;
  
    if( rollback )
    {
      ControlMessage cMsg = createSilenceMessage(jsMsg.getGuaranteedValueValueTick(),
                                                 jsMsg.getGuaranteedValueCompletedPrefix(),
                                                 msgItem.getPriority(),
                                                 msgItem.getReliability(),
                                                 jsMsg.getGuaranteedStreamUUID());   
      cMsg = addLinkProps(cMsg);
      cMsg.setRoutingDestination( _routingDestination );  
      
      //call MPIO to finally send the message to the remote MEs
      _mpio.sendDownTree(fromTo,                //the list of source target pairs
                        msgItem.getPriority(), //priority
                        cMsg);                 //the Silence Message  
 
    }
    else
    { 
      // Add Link specific properties to message
      jsMsg = addLinkProps(jsMsg);
      jsMsg.setRoutingDestination( _routingDestination );  
      jsMsg.setGuaranteedSourceMessagingEngineUUID( _messageProcessor.getMessagingEngineUuid() );
                     
      //call MPIO to finally send the message to the remote MEs
      _mpio.sendDownTree(fromTo,                //the list of source target pairs
                        msgItem.getPriority(), //priority
                        jsMsg);                //the JsMessage  
    }
            
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "sendLinkMessage");
     
  }
1020072
@Deprecated
    public static void setDate(HttpMessage message, Date value) {
        message.headers().set(HttpHeaderNames.DATE, value);
    }
847676
public function sendCollectorMessage($collectorId, $messageId, \DateTime $scheduledDate = null)
	{
		$data = $scheduledDate ? [ 'scheduled_date' => $scheduledDate->format(DATE_ATOM) ] : [];
		
		return $this->sendRequest(
			$this->createRequest('POST', sprintf('collectors/%s/messages/%s/send', $collectorId, $messageId), [], $data)
		);
	}
315401
@Override
	public String sendFAX(String corpNum, String sendNum, Receiver[] receivers,
			File file, Date reserveDT) throws PopbillException {

		return requestFax(corpNum, sendNum, null, receivers, new File[]{file}, 
				reserveDT, null, null, null, null);
	}
666534
@Override
	public final void send(Message message) throws JMSException
    {
    	if (this.destination == null)
    		throw new UnsupportedOperationException("Destination was not set at creation time");
    	
    	// Setup message fields
    	setupMessage(destination,message,defaultDeliveryMode,defaultPriority,defaultTimeToLive);
    	
    	// Handle foreign message implementations
        message = MessageTools.normalize(message);

        sendToDestination(destination,false,message,defaultDeliveryMode,defaultPriority,defaultTimeToLive);
    }
1355798
public void send(String destName, String messageText)
            throws MessagingException {
        this.send(destName, (Serializable) messageText);
    }
1309505
public void setDateExpires(long dateExpires) {

        m_dateExpires = dateExpires;
        if (LOG.isDebugEnabled()) {
            long now = System.currentTimeMillis();
            LOG.debug(
                Messages.get().getBundle().key(
                    Messages.LOG_FLEXCACHEENTRY_SET_EXPIRATION_DATE_3,
                    new Long(m_dateExpires),
                    new Long(now),
                    new Long(m_dateExpires - now)));
        }
    }
1138587
@Nonnull
  public ICommonsOrderedMap <IMutableEmailData, MailTransportError> send (@Nullable final Collection <IMutableEmailData> aAllMessages)
  {
    final ICommonsOrderedMap <IMutableEmailData, MailTransportError> aFailedMessages = new CommonsLinkedHashMap <> ();
    if (aAllMessages != null)
    {
      final ICommonsList <IMutableEmailData> aRemainingMessages = new CommonsArrayList <> (aAllMessages);
      MailSendException aExceptionToBeRemembered = null;

      try (final Transport aTransport = m_aSession.getTransport (m_bSMTPS ? SMTPS_PROTOCOL : SMTP_PROTOCOL))
      {
        // Add global listeners (if present)
        for (final ConnectionListener aConnectionListener : EmailGlobalSettings.getAllConnectionListeners ())
          aTransport.addConnectionListener (aConnectionListener);

        // Check if a detailed listener is present
        final ICommonsList <IEmailDataTransportListener> aEmailDataTransportListeners = EmailGlobalSettings.getAllEmailDataTransportListeners ();

        // Connect
        aTransport.connect (m_aSMTPSettings.getHostName (),
                            m_aSMTPSettings.getPort (),
                            m_aSMTPSettings.getUserName (),
                            m_aSMTPSettings.getPassword ());

        // For all messages
        for (final IMutableEmailData aEmailData : aAllMessages)
        {
          final MimeMessage aMimeMessage = new MimeMessage (m_aSession);
          try
          {
            // convert from IEmailData to MimeMessage
            MailConverter.fillMimeMessage (aMimeMessage, aEmailData, m_aSMTPSettings.getCharsetObj ());

            // Ensure a sent date is present
            if (aMimeMessage.getSentDate () == null)
              aMimeMessage.setSentDate (new Date ());

            // Get an explicitly specified message ID
            final String sMessageID = aMimeMessage.getMessageID ();

            // This creates a new message ID (besides other things)
            aMimeMessage.saveChanges ();

            if (sMessageID != null)
            {
              // Preserve explicitly specified message id...
              aMimeMessage.setHeader (HEADER_MESSAGE_ID, sMessageID);
            }
            aMimeMessage.setHeader ("X-Mailer", X_MAILER);

            if (LOGGER.isInfoEnabled ())
              LOGGER.info ("Delivering mail from " +
                              Arrays.toString (aMimeMessage.getFrom ()) +
                              " to " +
                              Arrays.toString (aMimeMessage.getAllRecipients ()) +
                              " with subject '" +
                              aMimeMessage.getSubject () +
                              "' and message ID '" +
                              aMimeMessage.getMessageID () +
                              "'");

            // Main transmit - always throws an exception
            aTransport.sendMessage (aMimeMessage, aMimeMessage.getAllRecipients ());
            throw new IllegalStateException ("Never expected to come beyong sendMessage!");
          }
          catch (final SendFailedException ex)
          {
            if (EmailGlobalSettings.isDebugSMTP ())
              LOGGER.error ("Error send mail - SendFailedException", ex);

            /*
             * Extract all addresses: the valid addresses to which the message
             * was sent, the valid address to which the message was not sent and
             * the invalid addresses
             */
            final ICommonsSet <String> aValidSent = CollectionHelper.newSetMapped (ex.getValidSentAddresses (),
                                                                                   Address::toString);
            final ICommonsSet <String> aValidUnsent = CollectionHelper.newSetMapped (ex.getValidUnsentAddresses (),
                                                                                     Address::toString);
            final ICommonsSet <String> aInvalid = CollectionHelper.newSetMapped (ex.getInvalidAddresses (),
                                                                                 Address::toString);

            final ICommonsList <MailSendDetails> aDetails = new CommonsArrayList <> ();
            Exception ex2;
            MessagingException bex = ex;
            while ((ex2 = bex.getNextException ()) != null && ex2 instanceof MessagingException)
            {
              if (ex2 instanceof SMTPAddressFailedException)
              {
                final SMTPAddressFailedException ssfe = (SMTPAddressFailedException) ex2;
                aDetails.add (new MailSendDetails (false,
                                                   ssfe.getAddress ().toString (),
                                                   ssfe.getCommand (),
                                                   ssfe.getMessage ().trim (),
                                                   ESMTPErrorCode.getFromIDOrDefault (ssfe.getReturnCode (),
                                                                                      ESMTPErrorCode.FALLBACK)));
              }
              else
                if (ex2 instanceof SMTPAddressSucceededException)
                {
                  final SMTPAddressSucceededException ssfe = (SMTPAddressSucceededException) ex2;
                  aDetails.add (new MailSendDetails (true,
                                                     ssfe.getAddress ().toString (),
                                                     ssfe.getCommand (),
                                                     ssfe.getMessage ().trim (),
                                                     ESMTPErrorCode.getFromIDOrDefault (ssfe.getReturnCode (),
                                                                                        ESMTPErrorCode.FALLBACK)));
                }

              bex = (MessagingException) ex2;
            }

            // Map addresses to details
            final ICommonsOrderedSet <MailSendDetails> aValidSentExt = new CommonsLinkedHashSet <> ();
            final ICommonsOrderedSet <MailSendDetails> aValidUnsentExt = new CommonsLinkedHashSet <> ();
            final ICommonsOrderedSet <MailSendDetails> aInvalidExt = new CommonsLinkedHashSet <> ();
            for (final MailSendDetails aFailure : aDetails)
            {
              final String sAddress = aFailure.getAddress ();
              if (aValidSent.contains (sAddress))
                aValidSentExt.add (aFailure);
              else
                if (aValidUnsent.contains (sAddress))
                  aValidUnsentExt.add (aFailure);
                else
                  aInvalidExt.add (aFailure);
            }

            final EmailDataTransportEvent aEvent = new EmailDataTransportEvent (m_aSMTPSettings,
                                                                                aEmailData,
                                                                                aMimeMessage,
                                                                                aValidSentExt,
                                                                                aValidUnsentExt,
                                                                                aInvalidExt);
            if (aValidUnsent.isEmpty () && aInvalid.isEmpty () && aValidSent.isNotEmpty ())
            {
              // Message delivered
              for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners)
                aEmailDataTransportListener.messageDelivered (aEvent);

              // Remove message from list of remaining
              s_aStatsCountSuccess.increment ();
            }
            else
            {
              // Message not delivered
              for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners)
                aEmailDataTransportListener.messageNotDelivered (aEvent);

              // Sending exactly this message failed
              aFailedMessages.put (aEmailData, new MailTransportError (ex, aDetails));
              s_aStatsCountFailed.increment ();
            }
            // Remove message from list of remaining as we put it in the
            // failed message list manually in case of error
            aRemainingMessages.remove (aEmailData);
          }
          catch (final MessagingException ex)
          {
            if (EmailGlobalSettings.isDebugSMTP ())
              LOGGER.error ("Error send mail - MessagingException", ex);

            final ICommonsOrderedSet <MailSendDetails> aInvalid = new CommonsLinkedHashSet <> ();
            final Consumer <IEmailAddress> aConsumer = a -> aInvalid.add (new MailSendDetails (false,
                                                                                               a.getAddress (),
                                                                                               "<generic error>",
                                                                                               ex.getMessage (),
                                                                                               ESMTPErrorCode.FALLBACK));
            aEmailData.forEachTo (aConsumer);
            aEmailData.forEachCc (aConsumer);
            aEmailData.forEachBcc (aConsumer);

            final EmailDataTransportEvent aEvent = new EmailDataTransportEvent (m_aSMTPSettings,
                                                                                aEmailData,
                                                                                aMimeMessage,
                                                                                new CommonsArrayList <> (),
                                                                                new CommonsArrayList <> (),
                                                                                aInvalid);
            // Message not delivered
            for (final IEmailDataTransportListener aEmailDataTransportListener : aEmailDataTransportListeners)
              aEmailDataTransportListener.messageNotDelivered (aEvent);

            // Sending exactly this message failed
            aFailedMessages.put (aEmailData, new MailTransportError (ex));
            // Remove message from list of remaining as we put it in the
            // failed message list manually
            aRemainingMessages.remove (aEmailData);
            s_aStatsCountFailed.increment ();
          }
        } // for all messages
      }
      catch (final AuthenticationFailedException ex)
      {
        // problem with the credentials
        aExceptionToBeRemembered = new MailSendException ("Mail server authentication failed", ex);
      }
      catch (final MessagingException ex)
      {
        if (WebExceptionHelper.isServerNotReachableConnection (ex.getCause ()))
          aExceptionToBeRemembered = new MailSendException ("Failed to connect to mail server: " +
                                                            ex.getCause ().getMessage ());
        else
          aExceptionToBeRemembered = new MailSendException ("Mail server connection failed", ex);
      }
      catch (final Exception ex)
      {
        // E.g. IllegalState from SMTPTransport ("Not connected")
        aExceptionToBeRemembered = new MailSendException ("Internal error sending mail", ex);
      }
      finally
      {
        // Was any message not sent
        if (aRemainingMessages.isNotEmpty ())
        {
          if (aExceptionToBeRemembered == null)
            aExceptionToBeRemembered = new MailSendException ("Internal error - messages are remaining but no Exception occurred!");
          for (final IMutableEmailData aRemainingMessage : aRemainingMessages)
            aFailedMessages.put (aRemainingMessage, new MailTransportError (aExceptionToBeRemembered));
        }
      }
    }
    return aFailedMessages;
  }
80672
protected int sendBundledMessages(final Message[] buf, final int read_index, final int write_index) {
        int       max_bundle_size=transport.getMaxBundleSize();
        byte[]    cluster_name=transport.cluster_name.chars();
        int       sent_msgs=0;

        for(int i=increment(read_index); i != write_index; i=increment(i)) {
            Message msg=buf[i];
            if(msg == NULL_MSG)
                continue;
            if(msg == null)
                break;

            Address dest=msg.dest();
            try {
                output.position(0);
                Util.writeMessageListHeader(dest, msg.src(), cluster_name, 1, output, dest == null);

                // remember the position at which the number of messages (an int) was written, so we can later set the
                // correct value (when we know the correct number of messages)
                int size_pos=output.position() - Global.INT_SIZE;
                int num_msgs=marshalMessagesToSameDestination(dest, buf, i, write_index, max_bundle_size);
                sent_msgs+=num_msgs;
                if(num_msgs > 1) {
                    int current_pos=output.position();
                    output.position(size_pos);
                    output.writeInt(num_msgs);
                    output.position(current_pos);
                }
                transport.doSend(output.buffer(), 0, output.position(), dest);
                if(transport.statsEnabled())
                    transport.incrBatchesSent(num_msgs);
            }
            catch(Exception ex) {
                log.error("failed to send message(s)", ex);
            }
        }
        return sent_msgs;
    }
294446
@Local
    public final CompletableFuture<Integer> sendMessage(final Convert convert, final Object message0, final boolean last, final Stream<? extends Serializable> userids) {
        Object[] array = userids.toArray();
        Serializable[] ss = new Serializable[array.length];
        for (int i = 0; i < array.length; i++) {
            ss[i] = (Serializable) array[i];
        }
        return sendMessage(convert, message0, last, ss);
    }
915307
public long send(String toUser, String templateId, MiniProgram miniProgram, Map<String, Data> messages) {
        return send(toUser, templateId, null, miniProgram, messages);
    }
1298947
public byte[] sendQuerySmResp(OutputStream os, int sequenceNumber,
            String messageId, String finalDate, MessageState messageState,
            byte errorCode) throws PDUStringException, IOException {
        synchronized (os) {
            return pduSender.sendQuerySmResp(os, sequenceNumber, messageId,
                    finalDate, messageState, errorCode);
        }
    }
1269050
@Override
  public FcmSendMessageResult sendMessageTo(final String to, final FcmSendMessageRequest request) {
    return proxy.sendMessageTo(to, request);
  }