Example usage for javax.mail.internet MimeMultipart MimeMultipart

List of usage examples for javax.mail.internet MimeMultipart MimeMultipart

Introduction

In this page you can find the example usage for javax.mail.internet MimeMultipart MimeMultipart.

Prototype

public MimeMultipart(DataSource ds) throws MessagingException 

Source Link

Document

Constructs a MimeMultipart object and its bodyparts from the given DataSource.

Usage

From source file:com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController.java

public String[] notifyExternals(InfoLetterPublicationPdC ilp, String server, List<String> emails) {
    // Retrieve SMTP server information
    String host = getSmtpHost();/* ww  w  .j av a  2s.c  om*/
    boolean isSmtpAuthentication = isSmtpAuthentication();
    int smtpPort = getSmtpPort();
    String smtpUser = getSmtpUser();
    String smtpPwd = getSmtpPwd();
    boolean isSmtpDebug = isSmtpDebug();

    List<String> emailErrors = new ArrayList<String>();

    if (emails.size() > 0) {

        // Corps et sujet du message
        String subject = getString("infoLetter.emailSubject") + ilp.getName();
        // Email du publieur
        String from = getUserDetail().geteMail();
        // create some properties and get the default Session
        Properties props = System.getProperties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", String.valueOf(isSmtpAuthentication));

        Session session = Session.getInstance(props, null);
        session.setDebug(isSmtpDebug); // print on the console all SMTP messages.

        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "subject = " + subject);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "from = " + from);
        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                "root.MSG_GEN_PARAM_VALUE", "host= " + host);

        try {
            // create a message
            MimeMessage msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.setSubject(subject, CharEncoding.UTF_8);
            ForeignPK foreignKey = new ForeignPK(ilp.getPK().getId(), getComponentId());
            // create and fill the first message part
            MimeBodyPart mbp1 = new MimeBodyPart();
            List<SimpleDocument> contents = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.wysiwyg,
                            I18NHelper.defaultLanguage);
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            for (SimpleDocument content : contents) {
                AttachmentServiceFactory.getAttachmentService().getBinaryContent(buffer, content.getPk(),
                        content.getLanguage());
            }
            mbp1.setDataHandler(
                    new DataHandler(new ByteArrayDataSource(
                            replaceFileServerWithLocal(
                                    IOUtils.toString(buffer.toByteArray(), CharEncoding.UTF_8), server),
                            MimeTypes.HTML_MIME_TYPE)));
            IOUtils.closeQuietly(buffer);
            // Fichiers joints
            WAPrimaryKey publiPK = ilp.getPK();
            publiPK.setComponentName(getComponentId());
            publiPK.setSpace(getSpaceId());

            // create the Multipart and its parts to it
            String mimeMultipart = getSettings().getString("SMTPMimeMultipart", "related");
            Multipart mp = new MimeMultipart(mimeMultipart);
            mp.addBodyPart(mbp1);

            // Images jointes
            List<SimpleDocument> fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.image, null);
            for (SimpleDocument attachment : fichiers) {
                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                // attach the file to the message
                FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                mbp2.setDataHandler(new DataHandler(fds));
                // For Displaying images in the mail
                mbp2.setFileName(attachment.getFilename());
                mbp2.setHeader("Content-ID", attachment.getFilename());
                SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                        "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                // create the Multipart and its parts to it
                mp.addBodyPart(mbp2);
            }

            // Fichiers joints
            fichiers = AttachmentServiceFactory.getAttachmentService()
                    .listDocumentsByForeignKeyAndType(foreignKey, DocumentType.attachment, null);

            if (!fichiers.isEmpty()) {
                for (SimpleDocument attachment : fichiers) {
                    // create the second message part
                    MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                    FileDataSource fds = new FileDataSource(attachment.getAttachmentPath());
                    mbp2.setDataHandler(new DataHandler(fds));
                    mbp2.setFileName(attachment.getFilename());
                    // For Displaying images in the mail
                    mbp2.setHeader("Content-ID", attachment.getFilename());
                    SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "content-ID= " + mbp2.getContentID());

                    // create the Multipart and its parts to it
                    mp.addBodyPart(mbp2);
                }
            }

            // add the Multipart to the message
            msg.setContent(mp);
            // set the Date: header
            msg.setSentDate(new Date());
            // create a Transport connection (TCP)
            Transport transport = session.getTransport("smtp");

            InternetAddress[] address = new InternetAddress[1];
            for (String email : emails) {
                try {
                    address[0] = new InternetAddress(email);
                    msg.setRecipients(Message.RecipientType.TO, address);
                    // add Transport Listener to the transport connection.
                    if (isSmtpAuthentication) {
                        SilverTrace.info("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                "root.MSG_GEN_PARAM_VALUE",
                                "host = " + host + " m_Port=" + smtpPort + " m_User=" + smtpUser);
                        transport.connect(host, smtpPort, smtpUser, smtpPwd);
                        msg.saveChanges();
                    } else {
                        transport.connect();
                    }
                    transport.sendMessage(msg, address);
                } catch (Exception ex) {
                    SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                            "root.MSG_GEN_PARAM_VALUE", "Email = " + email,
                            new InfoLetterException(
                                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                                    SilverpeasRuntimeException.ERROR, ex.getMessage(), ex));
                    emailErrors.add(email);
                } finally {
                    if (transport != null) {
                        try {
                            transport.close();
                        } catch (Exception e) {
                            SilverTrace.error("infoLetter", "InfoLetterSessionController.notifyExternals()",
                                    "root.EX_IGNORED", "ClosingTransport", e);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new InfoLetterException(
                    "com.stratelia.silverpeas.infoLetter.control.InfoLetterSessionController",
                    SilverpeasRuntimeException.ERROR, e.getMessage(), e);
        }
    }
    return emailErrors.toArray(new String[emailErrors.size()]);
}

From source file:org.georchestra.ldapadmin.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server// w  w w . j a va2s.  c  o  m
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Properties props = System.getProperties();
    props.put("mail.smtp.host", this.emailFactory.getSmtpHost());
    props.put("mail.protocol.port", this.emailFactory.getSmtpPort());

    final Session session = Session.getInstance(props, null);
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:immf.MyHtmlEmail.java

/**
 * @throws EmailException EmailException
 * @throws MessagingException MessagingException
 *///  w  w  w . j a va2s  .  com
private void build() throws MessagingException, EmailException {
    MimeMultipart rootContainer = this.getContainer();
    MimeMultipart bodyEmbedsContainer = rootContainer;
    MimeMultipart bodyContainer = rootContainer;
    BodyPart msgHtml = null;
    BodyPart msgText = null;

    rootContainer.setSubType("mixed");

    // determine how to form multiparts of email

    if (StringUtils.isNotEmpty(this.html) && this.inlineEmbeds.size() > 0) {
        //If HTML body and embeds are used, create a related container and add it to the root container
        bodyEmbedsContainer = new MimeMultipart("related");
        bodyContainer = bodyEmbedsContainer;
        this.addPart(bodyEmbedsContainer, 0);

        //If TEXT body was specified, create a alternative container and add it to the embeds container
        if (StringUtils.isNotEmpty(this.text)) {
            bodyContainer = new MimeMultipart("alternative");
            BodyPart bodyPart = createBodyPart();
            try {
                bodyPart.setContent(bodyContainer);
                bodyEmbedsContainer.addBodyPart(bodyPart, 0);
            } catch (MessagingException me) {
                throw new EmailException(me);
            }
        }
    } else if (StringUtils.isNotEmpty(this.text) && StringUtils.isNotEmpty(this.html)) {
        //If both HTML and TEXT bodies are provided, create a alternative container and add it to the root container
        bodyContainer = new MimeMultipart("alternative");
        this.addPart(bodyContainer, 0);
    }

    if (StringUtils.isNotEmpty(this.html)) {
        msgHtml = new MimeBodyPart();
        bodyContainer.addBodyPart(msgHtml, 0);

        // apply default charset if one has been set
        if (StringUtils.isNotEmpty(this.charset)) {
            msgHtml.setContent(this.html, Email.TEXT_HTML + "; charset=" + this.charset);
        } else {
            msgHtml.setContent(this.html, Email.TEXT_HTML);
        }
        if (contentTransferEncoding != null) {
            msgHtml.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
        }

        Iterator<InlineImage> iter = this.inlineEmbeds.values().iterator();
        while (iter.hasNext()) {
            InlineImage ii = (InlineImage) iter.next();
            bodyEmbedsContainer.addBodyPart(ii.getMbp());
        }
    }

    if (StringUtils.isNotEmpty(this.text)) {
        msgText = new MimeBodyPart();
        bodyContainer.addBodyPart(msgText, 0);

        // apply default charset if one has been set
        if (StringUtils.isNotEmpty(this.charset)) {
            msgText.setContent(this.text, Email.TEXT_PLAIN + "; charset=" + this.charset);
        } else {
            msgText.setContent(this.text, Email.TEXT_PLAIN);
        }
        if (contentTransferEncoding != null) {
            msgText.setHeader("Content-Transfer-Encoding", contentTransferEncoding);
        }
    }
}

From source file:org.georchestra.console.ws.emails.EmailController.java

/**
 * Send EmailEntry to smtp server/*from w  ww  .  j  a  v a 2 s  .  c om*/
 *
 * @param email email to send
 * @throws NameNotFoundException if recipient cannot be found in LDAP server
 * @throws DataServiceException if LDAP server is not available
 * @throws MessagingException if some field of email cannot be encoded (malformed email address)
 */
private void send(EmailEntry email) throws NameNotFoundException, DataServiceException, MessagingException {

    final Session session = Session.getInstance(System.getProperties(), null);
    session.getProperties().setProperty("mail.smtp.host", this.emailFactory.getSmtpHost());
    session.getProperties().setProperty("mail.smtp.port",
            (new Integer(this.emailFactory.getSmtpPort())).toString());
    final MimeMessage message = new MimeMessage(session);

    Account recipient = this.accountDao.findByUID(email.getRecipient());
    InternetAddress[] senders = {
            new InternetAddress(this.accountDao.findByUID(email.getSender()).getEmail()) };

    message.addFrom(senders);
    message.addRecipient(Message.RecipientType.TO, new InternetAddress(recipient.getEmail()));
    message.setSubject(email.getSubject());
    message.setHeader("Date", (new MailDateFormat()).format(email.getDate()));

    // Mail content
    Multipart multiPart = new MimeMultipart("alternative");

    // attachments
    for (Attachment att : email.getAttachments()) {
        MimeBodyPart mbp = new MimeBodyPart();
        mbp.setDataHandler(new DataHandler(new ByteArrayDataSource(att.getContent(), att.getMimeType())));
        mbp.setFileName(att.getName());
        multiPart.addBodyPart(mbp);
    }

    // html part
    MimeBodyPart htmlPart = new MimeBodyPart();
    htmlPart.setContent(email.getBody(), "text/html; charset=utf-8");
    multiPart.addBodyPart(htmlPart);

    message.setContent(multiPart);

    // Send message
    Transport.send(message);
}

From source file:org.apache.camel.component.mail.MailBinding.java

protected void createMultipartAlternativeMessage(MimeMessage mimeMessage, MailConfiguration configuration,
        Exchange exchange) throws MessagingException, IOException {

    MimeMultipart multipartAlternative = new MimeMultipart("alternative");
    mimeMessage.setContent(multipartAlternative);

    MimeBodyPart plainText = new MimeBodyPart();
    plainText.setText(getAlternativeBody(configuration, exchange), determineCharSet(configuration, exchange));
    // remove the header with the alternative mail now that we got it
    // otherwise it might end up twice in the mail reader
    exchange.getIn().removeHeader(configuration.getAlternativeBodyHeader());
    multipartAlternative.addBodyPart(plainText);

    // if there are no attachments, add the body to the same mulitpart message
    if (!exchange.getIn().hasAttachments()) {
        addBodyToMultipart(configuration, multipartAlternative, exchange);
    } else {/* ww w.j  a va2s . co m*/
        // if there are attachments, but they aren't set to be inline, add them to
        // treat them as normal. It will append a multipart-mixed with the attachments and the body text
        if (!configuration.isUseInlineAttachments()) {
            BodyPart mixedAttachments = new MimeBodyPart();
            mixedAttachments.setContent(createMixedMultipartAttachments(configuration, exchange));
            multipartAlternative.addBodyPart(mixedAttachments);
        } else {
            // if the attachments are set to be inline, attach them as inline attachments
            MimeMultipart multipartRelated = new MimeMultipart("related");
            BodyPart related = new MimeBodyPart();

            related.setContent(multipartRelated);
            multipartAlternative.addBodyPart(related);

            addBodyToMultipart(configuration, multipartRelated, exchange);

            addAttachmentsToMultipart(multipartRelated, Part.INLINE, exchange);
        }
    }
}

From source file:fr.xebia.cloud.amazon.aws.iam.AmazonAwsIamAccountCreator.java

private void sendEmail(Map<String, String> templatesParams, List<BodyPart> attachments, String toAddress)
        throws MessagingException {

    MimeBodyPart htmlAndPlainTextAlternativeBody = new MimeBodyPart();

    // TEXT AND HTML MESSAGE (gmail requires plain text alternative, otherwise, it displays the 1st plain text attachment in the preview)
    MimeMultipart cover = new MimeMultipart("alternative");
    htmlAndPlainTextAlternativeBody.setContent(cover);
    BodyPart textHtmlBodyPart = new MimeBodyPart();
    String textHtmlBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".html.ftl");
    textHtmlBodyPart.setContent(textHtmlBody, "text/html");
    cover.addBodyPart(textHtmlBodyPart);

    BodyPart textPlainBodyPart = new MimeBodyPart();
    cover.addBodyPart(textPlainBodyPart);
    String textPlainBody = FreemarkerUtils.generate(templatesParams,
            "/fr/xebia/cloud/amazon/aws/iam/amazon-aws-iam-credentials-email-" + environment.getIdentifier()
                    + ".txt.ftl");
    textPlainBodyPart.setContent(textPlainBody, "text/plain");

    MimeMultipart content = new MimeMultipart("related");
    content.addBodyPart(htmlAndPlainTextAlternativeBody);

    // ATTACHMENTS
    for (BodyPart bodyPart : attachments) {
        content.addBodyPart(bodyPart);//from  w  ww  .j av a2 s.co  m
    }

    MimeMessage msg = new MimeMessage(mailSession);

    msg.setFrom(mailFrom);
    msg.addRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(toAddress));
    msg.addRecipient(javax.mail.Message.RecipientType.CC, mailFrom);

    String subject = "[Xebia Amazon AWS " + environment.getIdentifier() + "] Credentials";

    msg.setSubject(subject);
    msg.setContent(content);

    mailTransport.sendMessage(msg, msg.getAllRecipients());
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.support.attachments.AttachmentUtils.java

/**
 * Adds a mulitpart MimeBodyPart from an array of attachments
 *//* ww w  .j a v a2s  . c o m*/

public static void addMultipartAttachment(MimeMultipart mp, StringToStringMap contentIds,
        List<Attachment> attachments) throws MessagingException {
    MimeMultipart multipart = new MimeMultipart("mixed");
    long totalSize = 0;

    for (int c = 0; c < attachments.size(); c++) {
        Attachment att = attachments.get(c);
        String contentType = att.getContentType();
        totalSize += att.getSize();

        MimeBodyPart part = contentType.startsWith("text/") ? new MimeBodyPart()
                : new PreencodedMimeBodyPart("binary");

        part.setDataHandler(new DataHandler(new AttachmentDataSource(att)));
        initPartContentId(contentIds, part, att, false);
        multipart.addBodyPart(part);
    }

    MimeBodyPart part = new PreencodedMimeBodyPart("binary");

    if (totalSize > MAX_SIZE_IN_MEMORY_ATTACHMENT) {
        part.setDataHandler(new DataHandler(new MultipartAttachmentFileDataSource(multipart)));
    } else {
        part.setDataHandler(new DataHandler(new MultipartAttachmentDataSource(multipart)));
    }

    Attachment attachment = attachments.get(0);
    initPartContentId(contentIds, part, attachment, true);

    mp.addBodyPart(part);
}

From source file:voldemort.restclient.R2Store.java

private Map<ByteArray, List<Versioned<byte[]>>> parseGetAllResults(ByteString entity) {
    Map<ByteArray, List<Versioned<byte[]>>> results = new HashMap<ByteArray, List<Versioned<byte[]>>>();

    try {//from  w ww.j av  a2  s  . co  m
        // Build the multipart object
        byte[] bytes = new byte[entity.length()];
        entity.copyBytes(bytes, 0);

        // Get the outer multipart object
        ByteArrayDataSource ds = new ByteArrayDataSource(bytes, "multipart/mixed");
        MimeMultipart mp = new MimeMultipart(ds);
        for (int i = 0; i < mp.getCount(); i++) {

            // Get an individual part. This contains all the versioned
            // values for a particular key referenced by content-location
            MimeBodyPart part = (MimeBodyPart) mp.getBodyPart(i);

            // Get the key
            String contentLocation = part.getHeader("Content-Location")[0];
            String base64Key = contentLocation.split("/")[2];
            ByteArray key = new ByteArray(RestUtils.decodeVoldemortKey(base64Key));

            if (logger.isDebugEnabled()) {
                logger.debug("Content-Location : " + contentLocation);
                logger.debug("Base 64 key : " + base64Key);
            }

            // Create an array list for holding all the (versioned values)
            List<Versioned<byte[]>> valueResultList = new ArrayList<Versioned<byte[]>>();

            // Get the nested Multi-part object. This contains one part for
            // each unique versioned value.
            ByteArrayDataSource nestedDS = new ByteArrayDataSource((String) part.getContent(),
                    "multipart/mixed");
            MimeMultipart valueParts = new MimeMultipart(nestedDS);

            for (int valueId = 0; valueId < valueParts.getCount(); valueId++) {

                MimeBodyPart valuePart = (MimeBodyPart) valueParts.getBodyPart(valueId);
                String serializedVC = valuePart.getHeader(RestMessageHeaders.X_VOLD_VECTOR_CLOCK)[0];
                int contentLength = Integer.parseInt(valuePart.getHeader(RestMessageHeaders.CONTENT_LENGTH)[0]);

                if (logger.isDebugEnabled()) {
                    logger.debug("Received serialized Vector Clock : " + serializedVC);
                }

                VectorClockWrapper vcWrapper = mapper.readValue(serializedVC, VectorClockWrapper.class);

                // get the value bytes
                InputStream input = valuePart.getInputStream();
                byte[] bodyPartBytes = new byte[contentLength];
                input.read(bodyPartBytes);

                VectorClock clock = new VectorClock(vcWrapper.getVersions(), vcWrapper.getTimestamp());
                valueResultList.add(new Versioned<byte[]>(bodyPartBytes, clock));

            }
            results.put(key, valueResultList);
        }

    } catch (MessagingException e) {
        throw new VoldemortException("Messaging exception while trying to parse GET response " + e.getMessage(),
                e);
    } catch (JsonParseException e) {
        throw new VoldemortException(
                "JSON parsing exception while trying to parse GET response " + e.getMessage(), e);
    } catch (JsonMappingException e) {
        throw new VoldemortException(
                "JSON mapping exception while trying to parse GET response " + e.getMessage(), e);
    } catch (IOException e) {
        throw new VoldemortException("IO exception while trying to parse GET response " + e.getMessage(), e);
    }
    return results;

}

From source file:com.mirth.connect.connectors.http.HttpReceiver.java

private HttpRequestMessage createRequestMessage(Request request, boolean ignorePayload)
        throws IOException, MessagingException {
    HttpRequestMessage requestMessage = new HttpRequestMessage();
    requestMessage.setMethod(request.getMethod());
    requestMessage.setHeaders(HttpMessageConverter.convertFieldEnumerationToMap(request));
    requestMessage.setParameters(extractParameters(request));

    ContentType contentType;//from w  w w.  j  a v a  2  s  . c o  m
    try {
        contentType = ContentType.parse(request.getContentType());
    } catch (RuntimeException e) {
        contentType = ContentType.TEXT_PLAIN;
    }
    requestMessage.setContentType(contentType);

    requestMessage.setRemoteAddress(StringUtils.trimToEmpty(request.getRemoteAddr()));
    requestMessage.setQueryString(StringUtils.trimToEmpty(request.getQueryString()));
    requestMessage.setRequestUrl(StringUtils.trimToEmpty(getRequestURL(request)));
    requestMessage.setContextPath(StringUtils.trimToEmpty(new URL(requestMessage.getRequestUrl()).getPath()));

    if (!ignorePayload) {
        InputStream requestInputStream = request.getInputStream();
        // If a security handler already consumed the entity, get it from the request attribute instead
        try {
            byte[] entity = (byte[]) request.getAttribute(EntityProvider.ATTRIBUTE_NAME);
            if (entity != null) {
                requestInputStream = new ByteArrayInputStream(entity);
            }
        } catch (Exception e) {
        }

        // If the request is GZIP encoded, uncompress the content
        List<String> contentEncodingList = requestMessage.getCaseInsensitiveHeaders()
                .get(HTTP.CONTENT_ENCODING);
        if (CollectionUtils.isNotEmpty(contentEncodingList)) {
            for (String contentEncoding : contentEncodingList) {
                if (contentEncoding != null && (contentEncoding.equalsIgnoreCase("gzip")
                        || contentEncoding.equalsIgnoreCase("x-gzip"))) {
                    requestInputStream = new GZIPInputStream(requestInputStream);
                    break;
                }
            }
        }

        /*
         * First parse out the body of the HTTP request. Depending on the connector settings,
         * this could end up being a string encoded with the request charset, a byte array
         * representing the raw request payload, or a MimeMultipart object.
         */

        // Only parse multipart if XML Body is selected and Parse Multipart is enabled
        if (connectorProperties.isXmlBody() && connectorProperties.isParseMultipart()
                && ServletFileUpload.isMultipartContent(request)) {
            requestMessage.setContent(
                    new MimeMultipart(new ByteArrayDataSource(requestInputStream, contentType.toString())));
        } else if (isBinaryContentType(contentType)) {
            requestMessage.setContent(IOUtils.toByteArray(requestInputStream));
        } else {
            requestMessage.setContent(IOUtils.toString(requestInputStream,
                    HttpMessageConverter.getDefaultHttpCharset(request.getCharacterEncoding())));
        }
    }

    return requestMessage;
}

From source file:de.mendelson.comm.as2.message.AS2MessageParser.java

/**Writes a passed payload part to the passed message object. 
 *//*from www .jav a 2s .com*/
public void writePayloadsToMessage(Part payloadPart, AS2Message message, Properties header) throws Exception {
    List<Part> attachmentList = new ArrayList<Part>();
    AS2Info info = message.getAS2Info();
    if (!info.isMDN()) {
        AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
        if (payloadPart.isMimeType("multipart/*")) {
            //check if it is a CEM
            if (payloadPart.getContentType().toLowerCase().contains("application/ediint-cert-exchange+xml")) {
                messageInfo.setMessageType(AS2Message.MESSAGETYPE_CEM);
                if (this.logger != null) {
                    this.logger.log(Level.FINE, this.rb.getResourceString("found.cem",
                            new Object[] { messageInfo.getMessageId(), message }), info);
                }
            }
            ByteArrayOutputStream mem = new ByteArrayOutputStream();
            payloadPart.writeTo(mem);
            mem.flush();
            mem.close();
            MimeMultipart multipart = new MimeMultipart(
                    new ByteArrayDataSource(mem.toByteArray(), payloadPart.getContentType()));
            //add all attachments to the message
            for (int i = 0; i < multipart.getCount(); i++) {
                //its possible that one of the bodyparts is the signature (for compressed/signed messages), skip the signature
                if (!multipart.getBodyPart(i).getContentType().toLowerCase().contains("pkcs7-signature")) {
                    attachmentList.add(multipart.getBodyPart(i));
                }
            }
        } else {
            attachmentList.add(payloadPart);
        }
    } else {
        //its a MDN, write whole part
        attachmentList.add(payloadPart);
    }
    //write the parts
    for (Part attachmentPart : attachmentList) {
        ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
        InputStream payloadIn = attachmentPart.getInputStream();
        this.copyStreams(payloadIn, payloadOut);
        payloadOut.flush();
        payloadOut.close();
        byte[] data = payloadOut.toByteArray();
        AS2Payload as2Payload = new AS2Payload();
        as2Payload.setData(data);
        String[] contentIdHeader = attachmentPart.getHeader("content-id");
        if (contentIdHeader != null && contentIdHeader.length > 0) {
            as2Payload.setContentId(contentIdHeader[0]);
        }
        String[] contentTypeHeader = attachmentPart.getHeader("content-type");
        if (contentTypeHeader != null && contentTypeHeader.length > 0) {
            as2Payload.setContentType(contentTypeHeader[0]);
        }
        try {
            as2Payload.setOriginalFilename(payloadPart.getFileName());
        } catch (MessagingException e) {
            if (this.logger != null) {
                this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                        new Object[] { info.getMessageId(), e.getMessage(), }), info);
            }
        }
        if (as2Payload.getOriginalFilename() == null) {
            String filenameheader = header.getProperty("content-disposition");
            if (filenameheader != null) {
                //test part for convinience: extract file name
                MimeBodyPart filenamePart = new MimeBodyPart();
                filenamePart.setHeader("content-disposition", filenameheader);
                try {
                    as2Payload.setOriginalFilename(filenamePart.getFileName());
                } catch (MessagingException e) {
                    if (this.logger != null) {
                        this.logger.log(Level.WARNING, this.rb.getResourceString("filename.extraction.error",
                                new Object[] { info.getMessageId(), e.getMessage(), }), info);
                    }
                }
            }
        }
        message.addPayload(as2Payload);
    }
}