Example usage for javax.mail BodyPart getContentType

List of usage examples for javax.mail BodyPart getContentType

Introduction

In this page you can find the example usage for javax.mail BodyPart getContentType.

Prototype

public String getContentType() throws MessagingException;

Source Link

Document

Returns the Content-Type of the content of this part.

Usage

From source file:org.nuxeo.ecm.automation.server.jaxrs.io.MultiPartFormRequestReader.java

public static Blob readBlob(HttpServletRequest request, BodyPart part) throws Exception {
    String ctype = part.getContentType();
    String fname = part.getFileName();
    InputStream pin = part.getInputStream();
    final File tmp = File.createTempFile("nx-automation-upload-", ".tmp");
    FileUtils.copyToFile(pin, tmp);// w w  w.  j  a  v a2s  .co m
    FileBlob blob = new FileBlob(tmp, ctype, null, fname, null);
    RequestContext.getActiveContext(request).addRequestCleanupHandler(new RequestCleanupHandler() {
        @Override
        public void cleanup(HttpServletRequest req) {
            tmp.delete();
        }
    });
    return blob;
}

From source file:org.obm.sync.server.mailer.EventChangeMailerTest.java

private InvitationParts checkInvitationStructure(MimeMessage mimeMessage)
        throws UnsupportedEncodingException, IOException, MessagingException {
    InvitationParts parts = new InvitationParts();
    parts.rawMessage = getRawMessage(mimeMessage);
    assertThat(mimeMessage.getContentType()).startsWith("multipart/mixed");
    assertThat(mimeMessage.getContent()).isInstanceOf(Multipart.class);
    Multipart mixed = (Multipart) mimeMessage.getContent();
    assertThat(mixed.getCount()).isEqualTo(2);
    BodyPart firstPart = mixed.getBodyPart(0);
    assertThat(firstPart.getContentType()).startsWith("multipart/alternative");
    assertThat(firstPart.getContent()).isInstanceOf(Multipart.class);
    Multipart alternative = (Multipart) firstPart.getContent();
    assertThat(alternative.getCount()).isEqualTo(3);
    parts.plainText = alternative.getBodyPart(0);
    assertThat(parts.plainText.getContentType()).startsWith("text/plain; charset=UTF-8");
    parts.htmlText = alternative.getBodyPart(1);
    assertThat(parts.htmlText.getContentType()).startsWith("text/html; charset=UTF-8");
    parts.textCalendar = alternative.getBodyPart(2);
    parts.applicationIcs = mixed.getBodyPart(1);
    assertThat(parts.applicationIcs.getContentType()).isEqualTo("application/ics; name=meeting.ics");
    return parts;
}

From source file:org.openhim.mediator.normalization.XDSbMimeProcessorActor.java

private void parseMimeMessage(String msg, String contentType)
        throws IOException, MessagingException, SOAPPartNotFound, UnprocessableContentFound {
    mimeMessage = new MimeMultipart(new ByteArrayDataSource(msg, contentType));
    for (int i = 0; i < mimeMessage.getCount(); i++) {
        BodyPart part = mimeMessage.getBodyPart(i);

        if (part.getContentType().contains("application/soap+xml")) {
            _soapPart = getValue(part);/*from   w w w  .j a  va 2  s  .  co  m*/
        } else {
            _documents.add(getValue(part));
        }
    }

    if (_soapPart == null) {
        throw new SOAPPartNotFound();
    }
}

From source file:org.openhim.mediator.normalization.XDSbMimeProcessorActor.java

private String buildEnrichedMimeMessage(String enrichedSOAPMessage) throws MessagingException, IOException {
    for (int i = 0; i < mimeMessage.getCount(); i++) {
        BodyPart part = mimeMessage.getBodyPart(i);
        if (part.getContentType().contains("application/soap+xml")) {
            Enumeration copyOfHeaders = createCopyOfHeaders(part);
            part.setContent(enrichedSOAPMessage, part.getContentType());
            copyHeadersToPart(copyOfHeaders, part);
            break;
        }/*from w  ww.  j  av  a 2  s .com*/
    }

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    mimeMessage.writeTo(out);
    mimeMessage = null;
    return out.toString();
}

From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java

private boolean isTextType(BodyPart part) throws MessagingException {
    return part.getSize() < MAX_PROPERTY_SIZE && part.getContentType().toLowerCase().startsWith("text/");
}

From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java

private void createChildNodeForPart(Session session, int index, BodyPart part, Content message)
        throws MessagingException, AccessDeniedException, StorageClientException, IOException {
    ContentManager contentManager = session.getContentManager();
    String childName = String.format("part%1$03d", index);
    String childPath = message.getPath() + "/" + childName;
    // multipart message
    if (part.getContentType().toLowerCase().startsWith("multipart/")) {
        contentManager.update(new Content(childPath, EMPTY_MAP));
        Content childNode = contentManager.get(childPath);
        writePartPropertiesToNode(part, childNode);
        contentManager.update(childNode);
        MimeMultipart multi = new MimeMultipart(
                new SMTPDataSource(part.getContentType(), part.getInputStream()));
        writeMultipartToNode(session, childNode, multi);
        return;//from   w  w  w  . ja  va 2 s.  co m
    }

    // text
    if (!isTextType(part)) {
        writePartAsFile(session, part, childName, message);
        return;
    }

    // not multipart; not text
    contentManager.update(new Content(childPath, EMPTY_MAP));
    Content childNode = contentManager.get(childPath);
    writePartPropertiesToNode(part, childNode);
    contentManager.update(childNode);
    // childNode.setProperty(MessageConstants.PROP_SAKAI_BODY, part.getInputStream());
    contentManager.writeBody(childNode.getPath(), part.getInputStream());
}

From source file:org.sakaiproject.nakamura.smtp.SakaiSmtpServer.java

private void writePartAsFile(Session session, BodyPart part, String nodeName, Content parentNode)
        throws AccessDeniedException, StorageClientException, MessagingException, IOException {
    // String filePath = parentNode.getPath() + "/nt:file";
    // String fileContentPath = filePath + "/jcr:content";
    // session.getContentManager().update(
    // new Content(filePath, new HashMap<String, Object>()));
    // session.getContentManager().update(new Content(fileContentPath, new HashMap<String,
    // Object>()));
    // Content resourceNode = session.getContentManager().get(fileContentPath);
    // resourceNode.setProperty("jcr:primaryType", "nt:resource");

    /*/*from   w w  w . ja  v  a2 s .  c  o m*/
     * Instead of creating a child node, just write the body part to the parentNode. I
     * think this will work, but may collide/override properties already set on the
     * message content. Let's ensure there are no collisions.
     */
    if (!parentNode.hasProperty(Content.MIMETYPE_FIELD)) {
        parentNode.setProperty(Content.MIMETYPE_FIELD, part.getContentType());
    } else {
        if (part.getContentType().equals(parentNode.getProperty(Content.MIMETYPE_FIELD))) {
            LOGGER.debug("Same mimeType; no worries");
        } else {
            throw new IllegalStateException(
                    "This sparse approach is bust; must create a subpath for file body");
        }
    }
    // parentNode.setProperty("jcr:data", part.getInputStream());
    session.getContentManager().writeBody(parentNode.getPath(), part.getInputStream());
}

From source file:org.sourceforge.net.javamail4ews.transport.EwsTransport.java

private MessageBody createBodyFromPart(EmailMessage msg, Part part, boolean treatAsAttachement)
        throws MessagingException, IOException, ServiceLocalException {

    MessageBody mb = new MessageBody();
    if (part.isMimeType(TEXT_PLAIN)) {
        String s = (String) part.getContent();
        mb.setBodyType(BodyType.Text);
        mb.setText(s);/*from   w w  w  .j  ava  2  s.c o m*/
    } else if (part.isMimeType(TEXT_STAR)) {
        logger.debug("mime-type is '" + part.getContentType() + "' handling as " + TEXT_HTML);
        String s = (String) part.getContent();
        mb.setBodyType(BodyType.HTML);
        mb.setText(s);
    } else if (part.isMimeType(MULTIPART_ALTERNATIVE) && !treatAsAttachement) {
        logger.debug("mime-type is '" + part.getContentType() + "'");
        Multipart mp = (Multipart) part.getContent();
        String text = "";
        for (int i = 0; i < mp.getCount(); i++) {
            Part p = mp.getBodyPart(i);
            if (p.isMimeType(TEXT_HTML)) {
                text += p.getContent();
            }
        }
        mb.setText(text);
        mb.setBodyType(BodyType.HTML);
        if (!treatAsAttachement)
            createBodyFromPart(msg, part, true);
    } else if (part.isMimeType(MULTIPART_STAR) && !part.isMimeType(MULTIPART_ALTERNATIVE)) {
        logger.debug("mime-type is '" + part.getContentType() + "'");
        Multipart mp = (Multipart) part.getContent();
        int start = 0;
        if (!treatAsAttachement) {
            mb = createBodyFromPart(msg, mp.getBodyPart(start), false);
            start++;
        }
        for (int i = start; i < mp.getCount(); i++) {
            BodyPart lBodyPart = mp.getBodyPart(i);
            byte[] lContentBytes = bodyPart2ByteArray(lBodyPart);

            FileAttachment lNewAttachment;

            String lContentId = getFirstHeaderValue(lBodyPart, "Content-ID");
            if (lContentId != null) {
                lNewAttachment = msg.getAttachments().addFileAttachment(lContentId, lContentBytes);
                lNewAttachment.setContentId(lContentId);
                lNewAttachment.setIsInline(true);

                logger.debug("Attached {} bytes as content {}", lContentBytes.length, lContentId);
            } else {
                String fileName = lBodyPart.getFileName();
                fileName = (fileName == null ? "" + i : fileName);
                lNewAttachment = msg.getAttachments().addFileAttachment(fileName, lContentBytes);
                lNewAttachment.setIsInline(false);
                lNewAttachment.setContentType(lBodyPart.getContentType());

                logger.debug("Attached {} bytes as file {}", lContentBytes.length, fileName);
                logger.debug("content type is {} ", lBodyPart.getContentType());
            }
            lNewAttachment.setIsContactPhoto(false);
        }
    }
    return mb;
}

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * Drag the content from the message into a String
 * /* www.j a v  a  2 s  .  co m*/
 * @param m
 * @return
 */
private String getContent(Message m) {
    try {
        Object content = m.getContent();
        if (content instanceof String) {
            return (String) content;
        } else if (content instanceof Multipart) {

            Multipart multipart = (Multipart) content;
            int partCount = multipart.getCount();
            StringBuffer result = new StringBuffer();

            for (int j = 0; j < partCount; j++) {

                BodyPart bodyPart = multipart.getBodyPart(j);
                String mimeType = bodyPart.getContentType();

                Object partContent = bodyPart.getContent();
                if (partContent instanceof String) {
                    result.append((String) partContent);
                } else if (partContent instanceof Multipart) {

                    Multipart innerMultiPartContent = (Multipart) partContent;
                    int innerPartCount = innerMultiPartContent.getCount();
                    result.append("*** It has " + innerPartCount + "further BodyParts in it ***");
                } else if (partContent instanceof InputStream) {
                    result.append(IOUtils.toString((InputStream) partContent));

                }
            } // End of for
            return result.toString();
        } else if (content instanceof InputStream)
            return IOUtils.toString((InputStream) content);

    } catch (Exception e) {
        return "ERROR reading mail content " + e.getMessage();
    }
    return "ERROR reading mail content - unknown format";
}

From source file:se.inera.axel.shs.processor.ShsMessageMarshaller.java

public ShsMessage unmarshal(InputStream stream) throws IllegalMessageStructureException {
    log.trace("unmarshal(InputStream)");

    try {//from  w  w  w.j a  v a 2s. c  om
        stream = SharedDeferredStream.toSharedInputStream(stream);
        MimeMessage mimeMessage = new MimeMessage(session, stream);
        Object msgContent = mimeMessage.getContent();

        if (!(msgContent instanceof MimeMultipart)) {
            throw new IllegalMessageStructureException(
                    "Expected a multipart mime message, got " + msgContent.getClass());
        }

        MimeMultipart multipart = (MimeMultipart) msgContent;

        if (multipart.getCount() < 2) {
            throw new IllegalMessageStructureException("SHS message must contain at least two mime bodyparts");
        }

        ShsMessage shsMessage = new ShsMessage();

        BodyPart labelPart = multipart.getBodyPart(0);
        if (!labelPart.isMimeType("text/xml") && !labelPart.isMimeType("text/plain")) {
            throw new IllegalMessageStructureException(
                    "First bodypart is not text/xml nor text/plain but was " + labelPart.getContentType());
        }

        ShsLabel label = shsLabelMarshaller.unmarshal((String) labelPart.getContent());

        shsMessage.setLabel(label);

        Content content = label.getContent();
        if (content == null) {
            throw new IllegalMessageStructureException("Label contains no content elements");
        }

        // this reads only as many mime body parts as there are content/data elements in the label
        int i = 1;
        for (Object o : content.getDataOrCompound()) {
            MimeBodyPart dp = (MimeBodyPart) multipart.getBodyPart(i);
            DataHandler dh = dp.getDataHandler();
            DataPart dataPart = new DataPart();
            dataPart.setDataHandler(new DataHandler(
                    new InputStreamDataSource(dh.getDataSource().getInputStream(), dh.getContentType())));

            dataPart.setContentType(dh.getContentType());

            String encoding = dp.getEncoding();
            if (encoding != null) {
                dataPart.setTransferEncoding(encoding);
            }

            dataPart.setFileName(dp.getFileName());

            if (o instanceof Data) {
                Data data = (Data) o;
                dataPart.setDataPartType(data.getDatapartType());
            } else if (o instanceof Compound) {
                continue;
            }
            shsMessage.addDataPart(dataPart);
            i++;
        }

        return shsMessage;

    } catch (Exception e) {
        if (e instanceof IllegalMessageStructureException) {
            throw (IllegalMessageStructureException) e;
        }

        throw new IllegalMessageStructureException(e);
    }
}