Example usage for javax.mail.internet ContentType ContentType

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

Introduction

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

Prototype

public ContentType(String s) throws ParseException 

Source Link

Document

Constructor that takes a Content-Type string.

Usage

From source file:org.nuxeo.cm.mail.actionpipe.ExtractMessageInformation.java

@SuppressWarnings("unchecked")
protected static void getAttachmentParts(Part p, String defaultFilename, MimetypeRegistry mimeService,
        ExecutionContext context) throws MessagingException, IOException {
    String filename = getFilename(p, defaultFilename);
    List<Blob> blobs = (List<Blob>) context.get(ATTACHMENTS_KEY);

    if (!p.isMimeType("multipart/*")) {
        String disp = p.getDisposition();
        // no disposition => consider it may be body
        if (disp == null && !context.containsKey(BODY_KEY)) {
            // this will need to be parsed
            context.put(BODY_KEY, p.getContent());
        } else if (disp != null
                && (disp.equalsIgnoreCase(Part.ATTACHMENT) || (disp.equalsIgnoreCase(Part.INLINE)
                        && !(p.isMimeType("text/*") || p.isMimeType("image/*"))))) {
            log.debug("Saving attachment to file " + filename);
            Blob blob = Blobs.createBlob(p.getInputStream());
            String mime = DEFAULT_BINARY_MIMETYPE;
            try {
                if (mimeService != null) {
                    ContentType contentType = new ContentType(p.getContentType());
                    mime = mimeService.getMimetypeFromFilenameAndBlobWithDefault(filename, blob,
                            contentType.getBaseType());
                }//from  www .ja v a  2  s . com
            } catch (MimetypeDetectionException e) {
                log.error(e);
            }
            blob.setMimeType(mime);

            blob.setFilename(filename);

            blobs.add(blob);

            // for debug
            // File f = new File(filename);
            // ((MimeBodyPart) p).saveFile(f);

            log.debug("---------------------------");

        } else {
            log.debug(String.format("Ignoring part with type %s", p.getContentType()));
        }
    }

    if (p.isMimeType("multipart/*")) {
        log.debug("This is a Multipart");
        log.debug("---------------------------");
        Multipart mp = (Multipart) p.getContent();

        int count = mp.getCount();
        for (int i = 0; i < count; i++) {
            getAttachmentParts(mp.getBodyPart(i), defaultFilename, mimeService, context);
        }
    } else if (p.isMimeType(MESSAGE_RFC822_MIMETYPE)) {
        log.debug("This is a Nested Message");
        log.debug("---------------------------");
        getAttachmentParts((Part) p.getContent(), defaultFilename, mimeService, context);
    }

}

From source file:org.mule.module.http.internal.HttpParser.java

/**
 * Extracts the subtype from a content type
 *
 * @param contentType the content type//from  www  . j ava 2 s .c  o  m
 * @return subtype of the content type.
 */
public static String getContentTypeSubType(String contentType) {
    final ContentType contentTypeValue;
    try {
        contentTypeValue = new ContentType(contentType);
        return contentTypeValue.getSubType();
    } catch (ParseException e) {
        throw new MuleRuntimeException(e);
    }
}

From source file:org.silverpeas.util.mail.EMLExtractor.java

private boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {//from  ww w. j a  v  a 2 s  .  com
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    e);
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    e);
        }
    }
    return false;
}

From source file:org.silverpeas.util.mail.EMLExtractor.java

private static String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (!StringUtil.isDefined(fileName)) {
        try {//from   w  w w .  j a  v  a  2s  . co m
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    e);
        }
    }
    if (StringUtil.isDefined(fileName) && fileName.startsWith("=?") && fileName.endsWith("?=")) {
        try {
            fileName = MimeUtility.decodeText(part.getFileName());
        } catch (UnsupportedEncodingException e) {
            SilverTrace.error("util", EMLExtractor.class.getSimpleName() + ".getFileName", "root.EX_NO_MESSAGE",
                    e);
        }
    }
    return fileName;
}

From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java

private boolean isTextPart(Part part) throws MessagingException {
    String disposition = part.getDisposition();
    if (!Part.ATTACHMENT.equals(disposition) && !Part.INLINE.equals(disposition)) {
        try {/*from   w ww .j a v a 2 s  .c o  m*/
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType());
        } catch (ParseException e) {
            SilverLogger.getLogger(this).error(e);
        }
    } else if (Part.INLINE.equals(disposition)) {
        try {
            ContentType type = new ContentType(part.getContentType());
            return "text".equalsIgnoreCase(type.getPrimaryType()) && getFileName(part) == null;
        } catch (ParseException e) {
            SilverLogger.getLogger(this).error(e);
        }
    }
    return false;
}

From source file:mailbox.CreationViaEmail.java

@Transactional
protected static ReviewComment saveReviewComment(Resource target, User sender, Content content,
        String messageID, Address[] allRecipients)
        throws MessagingException, IOException, NoSuchAlgorithmException {
    ReviewComment comment;//w  w  w. j  a  va 2 s  . co  m
    CommentThread thread = CommentThread.find.byId(Long.valueOf(target.getId()));

    if (thread == null) {
        throw new IllegalArgumentException();
    }

    comment = new ReviewComment();
    comment.setContents(content.body);
    comment.author = new UserIdent(sender);
    comment.thread = thread;
    comment.save();

    Map<String, Attachment> relatedAttachments = saveAttachments(content.attachments, comment.asResource());

    if (new ContentType(content.type).match(MimeType.HTML)) {
        // replace cid with attachments
        comment.setContents(replaceCidWithAttachments(comment.getContents(), relatedAttachments));
        comment.update();
    }

    new OriginalEmail(messageID, comment.asResource()).save();

    // Add the event
    if (thread.isOnPullRequest()) {
        addEvent(NotificationEvent.forNewComment(sender, thread.pullRequest, comment), allRecipients, sender);
    } else {
        try {
            String commitId;

            if (thread instanceof CodeCommentThread) {
                commitId = ((CodeCommentThread) thread).commitId;
            } else if (thread instanceof NonRangedCodeCommentThread) {
                commitId = ((NonRangedCodeCommentThread) thread).commitId;
            } else {
                throw new IllegalArgumentException();
            }

            addEvent(NotificationEvent.forNewCommitComment(target.getProject(), comment, commitId, sender),
                    allRecipients, sender);
        } catch (Exception e) {
            Logger.warn("Failed to send a notification", e);
        }
    }

    return comment;
}

From source file:immf.SendMailBridge.java

/**
 * SMTP???????/*from   w  w  w  . j  a  v a2s.c  o  m*/
 * @param msg
 * @throws IOException
 */
public void receiveMail(MyWiserMessage msg) throws IOException {
    try {
        SenderMail senderMail = new SenderMail();

        log.info("==== SMTP???????====");
        log.info("From       " + msg.getEnvelopeSender());
        log.info("Recipients  " + msg.getEnvelopeReceiver());

        MimeMessage mime = msg.getMimeMessage();

        String messageId = mime.getHeader("Message-ID", null);
        log.info("messageID  " + messageId);
        List<String> recipients;
        if (messageId != null && receivedMessageTable != null) {
            synchronized (receivedMessageTable) {
                recipients = receivedMessageTable.get(messageId);
                if (recipients != null) {
                    recipients.addAll(msg.getEnvelopeReceiver());
                    log.info("Duplicated message ignored");
                    return;
                }

                recipients = msg.getEnvelopeReceiver();
                receivedMessageTable.put(messageId, recipients);
                receivedMessageTable.wait(this.duplicationCheckTimeSec * 1000);
                receivedMessageTable.remove(messageId);
            }
        } else {
            recipients = msg.getEnvelopeReceiver();
        }

        List<InternetAddress> to = getRecipients(mime, "To");
        List<InternetAddress> cc = getRecipients(mime, "Cc");
        List<InternetAddress> bcc = getBccRecipients(recipients, to, cc);

        int maxRecipients = MaxRecipient;
        if (this.alwaysBcc != null) {
            log.debug("add alwaysbcc " + this.alwaysBcc);
            bcc.add(new InternetAddress(this.alwaysBcc));
        }
        log.info("To   " + StringUtils.join(to, " / "));
        log.info("cc   " + StringUtils.join(cc, " / "));
        log.info("bcc   " + StringUtils.join(bcc, " / "));

        senderMail.setTo(to);
        senderMail.setCc(cc);
        senderMail.setBcc(bcc);

        if (maxRecipients < (to.size() + cc.size() + bcc.size())) {
            log.warn("??????i.net???5??");
            throw new IOException("Too Much Recipients");
        }

        String contentType = mime.getContentType().toLowerCase();
        log.info("ContentType:" + contentType);

        String charset = (new ContentType(contentType)).getParameter("charset");
        log.info("charset:" + charset);

        String mailer = mime.getHeader("X-Mailer", null);
        log.info("mailer  " + mailer);

        String subject = mime.getHeader("Subject", null);
        log.info("subject  " + subject);
        if (subject != null)
            subject = this.charConv.convertSubject(subject);
        log.debug(" conv " + subject);

        if (this.useGoomojiSubject) {
            String goomojiSubject = mime.getHeader("X-Goomoji-Subject", null);
            if (goomojiSubject != null)
                subject = this.googleCharConv.convertSubject(goomojiSubject);
        }

        boolean editRe = false;
        if (this.editDocomoSubjectPrefix) {
            for (InternetAddress addr : to) {
                String[] toString = addr.getAddress().split("@", 2);
                if (subject != null && toString[1].equals("docomo.ne.jp")) {
                    editRe = true;
                }
            }
        }
        if (editRe) {
            if (subject.matches("^R[eE]: ?R[eE].*$")) {
                log.info("?subject: " + subject);
                String reCounterStr = subject.replaceAll("^R[eE]: ?R[eE](\\d*):.*$", "$1");
                int reCounter = 2;
                if (!reCounterStr.isEmpty()) {
                    reCounter = Integer.parseInt(reCounterStr);
                    reCounter++;
                }
                subject = subject.replaceAll("^R[eE]: ?R[eE]\\d*:", "Re" + Integer.toString(reCounter) + ":");
                log.info("subject: " + subject);
            }
        }

        senderMail.setSubject(subject);

        Object content = mime.getContent();
        if (content instanceof String) {
            // 
            String strContent = (String) content;
            if (contentType.toLowerCase().startsWith("text/html")) {
                log.info("Single html part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setHtmlContent(strContent);
            } else {
                log.info("Single plainText part " + strContent);
                strContent = this.charConv.convert(strContent, charset);
                log.debug(" conv " + strContent);
                senderMail.setPlainTextContent(strContent);
            }
        } else if (content instanceof Multipart) {
            Multipart mp = (Multipart) content;
            parseMultipart(senderMail, mp, getSubtype(contentType), null);
            if (senderMail.getHtmlContent() == null && senderMail.getHtmlWorkingContent() != null) {
                senderMail.setHtmlContent(senderMail.getHtmlWorkingContent());
            }

        } else {
            log.warn("? " + content.getClass().getName());
            throw new IOException("Unsupported type " + content.getClass().getName() + ".");
        }

        if (stripAppleQuote) {
            Util.stripAppleQuotedLines(senderMail);
        }
        Util.stripLastEmptyLines(senderMail);

        log.info("Content  " + mime.getContent());
        log.info("====");

        if (this.sendAsync) {
            // ??
            // ?????OK?
            this.picker.add(senderMail);
        } else {
            // ??????
            this.client.sendMail(senderMail, this.forcePlainText);
            if (isForwardSent) {
                status.setNeedConnect();
            }
        }

    } catch (IOException e) {
        log.warn("Bad Mail Received.", e);
        throw e;
    } catch (Exception e) {
        log.error("ReceiveMail Error.", e);
        throw new IOException("ReceiveMail Error." + e.getMessage(), e);
    }
}

From source file:org.trancecode.xproc.step.UnEscapeMarkupStepProcessor.java

private static ContentType getContentType(final String content_type, final Step inputStep) {
    try {/* w w w . jav  a2  s .c  o  m*/
        final ContentType ct = new ContentType(content_type);
        if (!Steps.SUPPORTED_CONTENTTYPE.contains(ct.getBaseType())) {
            throw XProcExceptions.xc0051(inputStep.getLocation());
        }
        return ct;
    } catch (final ParseException e) {
        throw XProcExceptions.xc0051(inputStep.getLocation());
    }
}

From source file:com.predic8.membrane.core.http.Header.java

/**
 * @return An object describing the value of the "Content-Type" HTTP header.
 *    Null, if the header is not present.
 * @throws ParseException if the value of the header could not be parsed.
 *//*from   www. j a v  a  2 s  .  com*/
public ContentType getContentTypeObject() throws ParseException {
    String contentType = getContentType();
    return contentType == null ? null : new ContentType(contentType);
}

From source file:org.silverpeas.core.mail.extractor.EMLExtractor.java

private String getFileName(Part part) throws MessagingException {
    String fileName = part.getFileName();
    if (!StringUtil.isDefined(fileName)) {
        try {// ww  w.  ja v  a  2 s. com
            ContentType type = new ContentType(part.getContentType());
            fileName = type.getParameter("name");
        } catch (ParseException e) {
            SilverLogger.getLogger(this).error(e);
        }
    }
    if (StringUtil.isDefined(fileName) && fileName.startsWith("=?") && fileName.endsWith("?=")) {
        try {
            fileName = MimeUtility.decodeText(part.getFileName());
        } catch (UnsupportedEncodingException e) {
            SilverLogger.getLogger(this).error(e);
        }
    }
    return fileName;
}