Example usage for org.bouncycastle.mail.smime.util CRLFOutputStream CRLFOutputStream

List of usage examples for org.bouncycastle.mail.smime.util CRLFOutputStream CRLFOutputStream

Introduction

In this page you can find the example usage for org.bouncycastle.mail.smime.util CRLFOutputStream CRLFOutputStream.

Prototype

public CRLFOutputStream(OutputStream outputstream) 

Source Link

Usage

From source file:mitm.common.security.smime.SMIMEUtils.java

License:Open Source License

public static void writeBodyPart(BodyPart bodyPart, OutputStream output, String defaultContentTransferEncoding)
        throws IOException, MessagingException {
    if (bodyPart instanceof MimeBodyPart) {
        MimeBodyPart mimeBodyPart = (MimeBodyPart) bodyPart;

        String[] contentTransferEncodings = bodyPart.getHeader("Content-Transfer-Encoding");

        String contentTransferEncoding = defaultContentTransferEncoding;

        if (contentTransferEncodings != null && contentTransferEncodings.length > 0) {
            contentTransferEncoding = contentTransferEncodings[0];
        }//w  w  w  .ja  v  a  2  s.co m

        /*
         * First try the raw input stream.
         * If message is created from a stream Javamail will return the raw stream. If
         * the message is created from 'scratch' getRawInputStream throws a
         * MessagingException. We will therefore first try the raw version and if
         * that fails we fallback on writeTo.
         */

        try {
            InputStream input = mimeBodyPart.getRawInputStream();

            Enumeration<?> lines = mimeBodyPart.getAllHeaderLines();

            /* step through all header lines */
            while (lines.hasMoreElements()) {
                String header = (String) lines.nextElement();

                output.write(MiscStringUtils.toAsciiBytes(header));
                output.write(MailUtils.CRLF_BYTES);
            }

            output.write(MailUtils.CRLF_BYTES);

            if (!contentTransferEncoding.equalsIgnoreCase("binary")) {
                output = new CRLFOutputStream(output);
            }

            IOUtils.copy(input, output);

            output.flush();
        } catch (MessagingException e) {
            /*
             * Fallback to writeTo
             */
            if (!contentTransferEncoding.equalsIgnoreCase("binary")) {
                output = new CRLFOutputStream(output);
            }

            bodyPart.writeTo(output);

            output.flush();
        }

    } else {
        if (!defaultContentTransferEncoding.equalsIgnoreCase("binary")) {
            output = new CRLFOutputStream(output);
        }

        bodyPart.writeTo(output);

        output.flush();
    }
}