Write message with attachments to stream

@param msg
@return
341323
public static InputStream toInputStream(SOAPMessage msg){
        if(msg==null)
            return null;
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            msg.writeTo(os);
        } catch (Exception e) {
            throw S1SystemError.wrap(e);
        }
        return new ByteArrayInputStream(os.toByteArray());
    }
1134758
public static <MSG extends Message> void writeStream(Iterable<MSG> messages, OutputStream output) {
    try {
      for (Message message : messages) {
        message.writeDelimitedTo(output);
      }
    } catch (Exception e) {
      throw ContextException.of("Unable to write messages", e);
    }
  }
129620
public static <T> int writeListTo(OutputStream out, List<T> messages, Schema<T> schema,
            LinkedBuffer buffer) throws IOException
    {
        if (buffer.start != buffer.offset)
            throw new IllegalArgumentException("Buffer previously used and had not been reset.");

        final ProtobufOutput output = new ProtobufOutput(buffer);
        int totalSize = 0;
        for (T m : messages)
        {
            schema.writeTo(output, m);
            final int size = output.getSize();
            ProtobufOutput.writeRawVarInt32Bytes(out, size);
            final int msgSize = LinkedBuffer.writeTo(out, buffer);

            assert size == msgSize;

            totalSize += size;
            output.clear();
        }
        return totalSize;
    }
183016
private void sendLayoutMessage(final String msg) {
      if (sqw != null) {
          String packet = msg;
          String hdr = getPacketHeader(new Date().getTime());
          if(facilityPrinting || hdr.length() > 0) {
              StringBuffer buf = new StringBuffer(hdr);
              if(facilityPrinting) {
                  buf.append(facilityStr);
              }
              buf.append(msg);
              packet = buf.toString();
          }
          sqw.setLevel(6);
          sqw.write(packet);
      }
  }
488047
public void printRawLines(String msg) {
        PrintWriter noticeWriter = writers.get(WriterKind.NOTICE);
        printRawLines(noticeWriter, msg);
    }
137518
public RequestContext renderMsg(final String msg) {
        if (renderer instanceof JsonRenderer) {
            final JsonRenderer r = (JsonRenderer) renderer;

            final JSONObject ret = r.getJSONObject();
            ret.put(Keys.MSG, msg);
        }

        return this;
    }
824890
private void sendMessages(final List<MessageEnvelope> msgEnvelopes) {
        try {
            boolean success=BackendOperation.execute(new BackendOperation.Transactional<Boolean>() {
                @Override
                public Boolean call(StoreTransaction txh) throws BackendException {
                    ListMultimap<StaticBuffer,Entry> mutations = ArrayListMultimap.create();
                    for (MessageEnvelope env : msgEnvelopes) {
                        mutations.put(env.key,env.entry);
                        long ts = env.entry.getColumn().getLong(0);
                        log.debug("Preparing to write {} to storage with column/timestamp {}", env, times.getTime(ts));
                    }

                    Map<StaticBuffer,KCVMutation> muts = new HashMap<StaticBuffer, KCVMutation>(mutations.keySet().size());
                    for (StaticBuffer key : mutations.keySet()) {
                        muts.put(key,new KCVMutation(mutations.get(key),KeyColumnValueStore.NO_DELETIONS));
                        log.debug("Built mutation on key {} with {} additions", key, mutations.get(key).size());
                    }
                    manager.storeManager.mutateMany(ImmutableMap.of(store.getName(),muts),txh);
                    log.debug("Wrote {} total envelopes with operation timestamp {}", msgEnvelopes.size(), txh.getConfiguration().getCommitTime());
                    return Boolean.TRUE;
                }
                @Override
                public String toString() {
                    return "messageSending";
                }
            },this, times, maxWriteTime);
            Preconditions.checkState(success);
            log.debug("Wrote {} messages to backend",msgEnvelopes.size());
            for (MessageEnvelope msgEnvelope : msgEnvelopes)
                msgEnvelope.message.delivered();
        } catch (TitanException e) {
            for (MessageEnvelope msgEnvelope : msgEnvelopes)
                msgEnvelope.message.failed(e);
            throw e;
        }
    }
1013267
@Override
    public void sendMsg(String msg)
    {
        DbConn cnx = Helpers.getNewDbSession();
        try
        {
            Message.create(cnx, msg, ji.getId());
            cnx.commit();
        }
        finally
        {
            Helpers.closeQuietly(cnx);
        }
    }
837648
protected byte[] getTransportPayload(AuditEventMessage msg)
	{
		if (msg == null) {
			return null;
		}
		
		byte[] msgBytes = msg.getSerializedMessage(false);
		if (EventUtils.isEmptyOrNull(msgBytes)) {
			return null;
		}
		
		// Format message with transport-specific headers
		StringBuilder sb = new StringBuilder();
		sb.append("<");
		sb.append(TRANSPORT_DEFAULT_PRIORITY);
		sb.append(">");
		
		sb.append(TimestampUtils.getBSDSyslogDate(msg.getDateTime()));
		sb.append(" ");
		sb.append(getSystemHostName());
		sb.append(" ");
		sb.append("<?xml version=\"1.0\" encoding=\"ASCII\"?>");
		sb.append(new String(msgBytes));

		return sb.toString().trim().getBytes();
	}
374011
def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True):
    # check if closed!!!!!! XXX
    
    if isinstance(contents, text_type):
        contents = [contents]
    if isinstance(attachments, text_type):
        attachments = [attachments]

    # merge contents and attachments for now.
    if attachments is not None:
        for a in attachments:
            if not os.path.isfile(a):
                raise TypeError("'{0}' is not a valid filepath".format(a))
        contents = attachments if contents is None else contents + attachments

    has_included_images, content_objects = prepare_contents(contents, encoding)
    msg = MIMEMultipart()
    if headers is not None:
        # Strangely, msg does not have an update method, so then manually.
        for k, v in headers.items():
            msg[k] = v
    if headers is None or "Date" not in headers:
        msg["Date"] = formatdate()

    msg_alternative = MIMEMultipart("alternative")
    msg_related = MIMEMultipart("related")
    msg_related.attach("-- HTML goes here --")
    msg.attach(msg_alternative)
    add_subject(msg, subject)
    add_recipients_headers(user, useralias, msg, addresses)
    htmlstr = ""
    altstr = []
    if has_included_images:
        msg.preamble = "This message is best displayed using a MIME capable email reader."

    if contents is not None:
        for content_object, content_string in zip(content_objects, contents):
            if content_object["main_type"] == "image":
                # all image objects need base64 encoding, so do it now
                email.encoders.encode_base64(content_object["mime_object"])
                # aliased image {'path' : 'alias'}
                if isinstance(content_string, dict) and len(content_string) == 1:
                    for key in content_string:
                        hashed_ref = str(abs(hash(key)))
                        alias = content_string[key]
                    # pylint: disable=undefined-loop-variable
                    content_string = key
                else:
                    alias = os.path.basename(str(content_string))
                    hashed_ref = str(abs(hash(alias)))

                # TODO: I should probably remove inline now that there is "attachments"
                # if string is `inline`, inline, else, attach
                # pylint: disable=unidiomatic-typecheck
                if type(content_string) == inline:
                    htmlstr += '<img src="cid:{0}" title="{1}"/>'.format(hashed_ref, alias)
                    content_object["mime_object"].add_header(
                        "Content-ID", "<{0}>".format(hashed_ref)
                    )
                    altstr.append("-- img {0} should be here -- ".format(alias))
                    # inline images should be in related MIME block
                    msg_related.attach(content_object["mime_object"])
                else:
                    # non-inline images get attached like any other attachment
                    msg.attach(content_object["mime_object"])

            else:
                if content_object["encoding"] == "base64":
                    email.encoders.encode_base64(content_object["mime_object"])
                    msg.attach(content_object["mime_object"])
                elif content_object["sub_type"] not in ["html", "plain"]:
                    msg.attach(content_object["mime_object"])
                else:
                    if newline_to_break:
                        content_string = content_string.replace("\n", "<br>")
                    try:
                        htmlstr += "<div>{0}</div>".format(content_string)
                    except UnicodeEncodeError:
                        htmlstr += u"<div>{0}</div>".format(content_string)
                    altstr.append(content_string)

    msg_related.get_payload()[0] = MIMEText(htmlstr, "html", _charset=encoding)
    msg_alternative.attach(MIMEText("\n".join(altstr), _charset=encoding))
    msg_alternative.attach(msg_related)
    return msg
243176
public void putreq(String msg)
    throws SoccomException
    {
    byte msgbytes[] = SoccomMessage.makeMessage(msg, null);
    logline("SEND: " + new String(msgbytes));
    copy_msgid(_msgid, msgbytes);
    try {
        // _out.print(msg);
        _out.write(msgbytes);
    } catch (IOException e) {
        throw new SoccomException(SoccomException.REQUEST);
    }
    }
551216
public MessageBuilder addAttachmentAsSpoiler(InputStream stream, String fileName) {
        delegate.addAttachment(stream, "SPOILER_" + fileName);
        return this;
    }
1325609
public boolean writeOutbound(Object... msgs) {
        ensureOpen();
        if (msgs.length == 0) {
            return isNotEmpty(outboundMessages);
        }

        RecyclableArrayList futures = RecyclableArrayList.newInstance(msgs.length);
        try {
            for (Object m: msgs) {
                if (m == null) {
                    break;
                }
                futures.add(write(m));
            }

            flushOutbound0();

            int size = futures.size();
            for (int i = 0; i < size; i++) {
                ChannelFuture future = (ChannelFuture) futures.get(i);
                if (future.isDone()) {
                    recordException(future);
                } else {
                    // The write may be delayed to run later by runPendingTasks()
                    future.addListener(recordExceptionListener);
                }
            }

            checkException();
            return isNotEmpty(outboundMessages);
        } finally {
            futures.recycle();
        }
    }
838717
def do_write(msg)
      Thread.new do
	begin
	  tuple, sec = Marshal.load(msg)
	  @ts.write(tuple, sec)
	rescue
	end
      end
    end
20315
public JsJmsStreamMessage createJmsStreamMessage() throws MessageCreateFailedException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createJmsStreamMessage");
    JsJmsStreamMessage msg = null;
    try {
      msg = new JsJmsStreamMessageImpl(MfpConstants.CONSTRUCTOR_NO_OP);
    }
    catch (MessageDecodeFailedException e) {
      /* No need to FFDC this as JsMsgObject will already have done so */
      // No FFDC code needed
      throw new MessageCreateFailedException(e);
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createJmsStreamMessage");
    return msg;
  }
846848
public void putreq_vline(String msg)
    throws SoccomException
    {
    int length = msg.length();
    if (msg.charAt(length-1) == '\n') {
        logline("SEND: " + msg.substring(0,length-1));
    } else {
        logline("SEND: " + msg);
        msg += "\n";
    }
    byte msgbytes[] = msg.getBytes();
    try {
        _out.write(msgbytes);
    } catch (IOException e) {
        throw new SoccomException(SoccomException.REQUEST);
    }
    }
907403
public LogNode log(final Collection<String> msgs) {
        LogNode last = null;
        for (final String m : msgs) {
            last = log(m);
        }
        return last;
    }