Example usage for javax.mail Header getValue

List of usage examples for javax.mail Header getValue

Introduction

In this page you can find the example usage for javax.mail Header getValue.

Prototype

public String getValue() 

Source Link

Document

Returns the value of this header.

Usage

From source file:org.apache.jsieve.mailet.SieveMailboxMailet.java

/**
 * Delivers a mail to a local mailbox.//from  w  ww  .  j  av  a 2  s.co m
 * 
 * @param mail
 *            the mail being processed
 * 
 * @throws MessagingException
 *             if an error occurs while storing the mail
 */
@SuppressWarnings("unchecked")
@Override
public void service(Mail mail) throws MessagingException {
    Collection<MailAddress> recipients = mail.getRecipients();
    Collection<MailAddress> errors = new Vector<MailAddress>();

    MimeMessage message = null;
    if (deliveryHeader != null || resetReturnPath) {
        message = mail.getMessage();
    }

    if (resetReturnPath) {
        // Set Return-Path and remove all other Return-Path headers from the
        // message
        // This only works because there is a placeholder inserted by
        // MimeMessageWrapper
        message.setHeader(RFC2822Headers.RETURN_PATH,
                (mail.getSender() == null ? "<>" : "<" + mail.getSender() + ">"));
    }

    Enumeration headers;
    InternetHeaders deliveredTo = new InternetHeaders();
    if (deliveryHeader != null) {
        // Copy any Delivered-To headers from the message
        headers = message.getMatchingHeaders(new String[] { deliveryHeader });
        while (headers.hasMoreElements()) {
            Header header = (Header) headers.nextElement();
            deliveredTo.addHeader(header.getName(), header.getValue());
        }
    }

    for (Iterator<MailAddress> i = recipients.iterator(); i.hasNext();) {
        MailAddress recipient = i.next();
        try {
            if (deliveryHeader != null) {
                // Add qmail's de facto standard Delivered-To header
                message.addHeader(deliveryHeader, recipient.toString());
            }

            storeMail(mail.getSender(), recipient, mail);

            if (deliveryHeader != null) {
                if (i.hasNext()) {
                    // Remove headers but leave all placeholders
                    message.removeHeader(deliveryHeader);
                    headers = deliveredTo.getAllHeaders();
                    // And restore any original Delivered-To headers
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        message.addHeader(header.getName(), header.getValue());
                    }
                }
            }
        } catch (Exception ex) {
            log("Error while storing mail.", ex);
            errors.add(recipient);
        }
    }

    if (!errors.isEmpty()) {
        // If there were errors, we redirect the email to the ERROR
        // processor.
        // In order for this server to meet the requirements of the SMTP
        // specification, mails on the ERROR processor must be returned to
        // the sender. Note that this email doesn't include any details
        // regarding the details of the failure(s).
        // In the future we may wish to address this.
        getMailetContext().sendMail(mail.getSender(), errors, mail.getMessage(), Mail.ERROR);
    }
    if (consume) {
        // Consume this message
        mail.setState(Mail.GHOST);
    }
}

From source file:org.apache.jsieve.utils.SieveMailAdapter.java

/**
 * Parses the value from the given message into addresses.
 * /*from www .  j a va  2s  .c o m*/
 * @param headerName
 *            header name, to be matched case insensitively
 * @param message
 *            <code>Message</code>, not null
 * @return <code>Address</code> array, not null possibly empty
 * @throws SieveMailException
 */
public Address[] parseAddresses(final String headerName, final Message message) throws SieveMailException {
    try {
        final SieveAddressBuilder builder = new SieveAddressBuilder();

        for (Enumeration en = message.getAllHeaders(); en.hasMoreElements();) {
            final Header header = (Header) en.nextElement();
            final String name = header.getName();
            if (name.trim().equalsIgnoreCase(headerName)) {
                builder.addAddresses(header.getValue());
            }
        }

        final Address[] results = builder.getAddresses();
        return results;

    } catch (MessagingException ex) {
        throw new SieveMailException(ex);
    } catch (org.apache.jsieve.parser.generated.address.ParseException ex) {
        throw new SieveMailException(ex);
    }
}

From source file:org.apache.juddi.v3.tck.UDDI_090_Smtp_ExternalTest.java

/**
 * gets all current messages from the mail server and returns the number
 * of messages containing the string, messages containing the string are
 * deleted from the mail server String is the body of each message
 *
 * @return number of matching and deleted messages
 * @param contains a string to search for
 *//* w ww. j  ava2 s .  c o m*/
private static int fetchMail(String contains) {

    //final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

    /* Set the mail properties */
    Properties properties = TckPublisher.getProperties();
    // Set manual Properties

    int found = 0;
    Session session = Session.getDefaultInstance(properties, null);
    Store store = null;
    try {
        store = session.getStore("pop3");

        store.connect(properties.getProperty("mail.pop3.host"),
                Integer.parseInt(properties.getProperty("mail.pop3.port", "110")),
                properties.getProperty("mail.pop3.username"), properties.getProperty("mail.pop3.password"));
        /* Mention the folder name which you want to read. */
        // inbox = store.getDefaultFolder();
        // inbox = inbox.getFolder("INBOX");
        Folder inbox = store.getFolder("INBOX");

        /* Open the inbox using store. */
        inbox.open(Folder.READ_WRITE);

        Message messages[] = inbox.getMessages();

        for (int i = 0; i < messages.length; i++) {

            MimeMessageParser p = new MimeMessageParser(new MimeMessage(session, messages[i].getInputStream()));
            Enumeration allHeaders = p.getMimeMessage().getAllHeaders();
            while (allHeaders.hasMoreElements()) {
                Object j = allHeaders.nextElement();
                if (j instanceof javax.mail.Header) {
                    javax.mail.Header msg = (javax.mail.Header) j;
                    logger.info("XML as message header is " + msg.getValue());
                    if (msg.getValue().contains(contains)) {
                        //found it
                        messages[i].setFlag(Flags.Flag.DELETED, true);
                        found++;
                    }
                }
            }
            for (int k = 0; k < p.getAttachmentList().size(); k++) {
                InputStream is = p.getAttachmentList().get((k)).getInputStream();
                QuotedPrintableCodec qp = new QuotedPrintableCodec();
                // If "is" is not already buffered, wrap a BufferedInputStream
                // around it.
                if (!(is instanceof BufferedInputStream)) {
                    is = new BufferedInputStream(is);
                }
                int c;
                StringBuilder sb = new StringBuilder();
                System.out.println("Message : ");
                while ((c = is.read()) != -1) {
                    sb.append(c);
                    System.out.write(c);
                }
                is.close();
                String decoded = qp.decode(sb.toString());
                logger.info("decode message is " + decoded);
                if (decoded.contains(contains)) {
                    //found it
                    messages[i].setFlag(Flags.Flag.DELETED, true);
                    found++;
                }
            }

        }
        inbox.close(true);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if (store != null) {
            try {
                store.close();
            } catch (Exception ex) {
            }
        }
    }
    return found;
}

From source file:org.apache.nifi.processors.email.ExtractEmailHeaders.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) {
    final ComponentLog logger = getLogger();

    final List<FlowFile> invalidFlowFilesList = new ArrayList<>();
    final List<FlowFile> processedFlowFilesList = new ArrayList<>();

    final FlowFile originalFlowFile = session.get();
    if (originalFlowFile == null) {
        return;/*from   www.j  av  a2  s .c o m*/
    }

    final List<String> capturedHeadersList = Arrays
            .asList(context.getProperty(CAPTURED_HEADERS).getValue().toLowerCase().split(":"));

    final Map<String, String> attributes = new HashMap<>();
    session.read(originalFlowFile, new InputStreamCallback() {
        @Override
        public void process(final InputStream rawIn) throws IOException {
            try (final InputStream in = new BufferedInputStream(rawIn)) {
                Properties props = new Properties();
                Session mailSession = Session.getDefaultInstance(props, null);
                MimeMessage originalMessage = new MimeMessage(mailSession, in);
                MimeMessageParser parser = new MimeMessageParser(originalMessage).parse();
                // RFC-2822 determines that a message must have a "From:" header
                // if a message lacks the field, it is flagged as invalid
                Address[] from = originalMessage.getFrom();
                Date sentDate = originalMessage.getSentDate();
                if (from == null || sentDate == null) {
                    // Throws MessageException due to lack of minimum required headers
                    throw new MessagingException("Message failed RFC2822 validation");
                } else if (capturedHeadersList.size() > 0) {
                    Enumeration headers = originalMessage.getAllHeaders();
                    while (headers.hasMoreElements()) {
                        Header header = (Header) headers.nextElement();
                        if (StringUtils.isNotEmpty(header.getValue())
                                && capturedHeadersList.contains(header.getName().toLowerCase())) {
                            attributes.put("email.headers." + header.getName().toLowerCase(),
                                    header.getValue());
                        }
                    }
                }
                if (Array.getLength(originalMessage.getAllRecipients()) > 0) {
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.TO)); toCount++) {
                        attributes.put(EMAIL_HEADER_TO + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.TO)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.BCC)); toCount++) {
                        attributes.put(EMAIL_HEADER_BCC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.BCC)[toCount].toString());
                    }
                    for (int toCount = 0; toCount < ArrayUtils
                            .getLength(originalMessage.getRecipients(Message.RecipientType.CC)); toCount++) {
                        attributes.put(EMAIL_HEADER_CC + "." + toCount,
                                originalMessage.getRecipients(Message.RecipientType.CC)[toCount].toString());
                    }
                }
                // Incredibly enough RFC-2822 specified From as a "mailbox-list" so an array I returned by getFrom
                for (int toCount = 0; toCount < ArrayUtils.getLength(originalMessage.getFrom()); toCount++) {
                    attributes.put(EMAIL_HEADER_FROM + "." + toCount,
                            originalMessage.getFrom()[toCount].toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getMessageID())) {
                    attributes.put(EMAIL_HEADER_MESSAGE_ID, originalMessage.getMessageID());
                }
                if (originalMessage.getReceivedDate() != null) {
                    attributes.put(EMAIL_HEADER_RECV_DATE, originalMessage.getReceivedDate().toString());
                }
                if (originalMessage.getSentDate() != null) {
                    attributes.put(EMAIL_HEADER_SENT_DATE, originalMessage.getSentDate().toString());
                }
                if (StringUtils.isNotEmpty(originalMessage.getSubject())) {
                    attributes.put(EMAIL_HEADER_SUBJECT, originalMessage.getSubject());
                }
                // Zeroes EMAIL_ATTACHMENT_COUNT
                attributes.put(EMAIL_ATTACHMENT_COUNT, "0");
                // But insert correct value if attachments are present
                if (parser.hasAttachments()) {
                    attributes.put(EMAIL_ATTACHMENT_COUNT, String.valueOf(parser.getAttachmentList().size()));
                }

            } catch (Exception e) {
                // Message is invalid or triggered an error during parsing
                attributes.clear();
                logger.error("Could not parse the flowfile {} as an email, treating as failure",
                        new Object[] { originalFlowFile, e });
                invalidFlowFilesList.add(originalFlowFile);
            }
        }
    });

    if (attributes.size() > 0) {
        FlowFile updatedFlowFile = session.putAllAttributes(originalFlowFile, attributes);
        logger.info("Extracted {} headers into {} file", new Object[] { attributes.size(), updatedFlowFile });
        processedFlowFilesList.add(updatedFlowFile);
    }

    session.transfer(processedFlowFilesList, REL_SUCCESS);
    session.transfer(invalidFlowFilesList, REL_FAILURE);

}

From source file:org.apache.olingo.fit.AbstractServices.java

protected Response bodyPartRequest(final MimeBodyPart body, final Map<String, String> references)
        throws Exception {
    @SuppressWarnings("unchecked")
    final Enumeration<Header> en = body.getAllHeaders();

    Header header = en.nextElement();
    final String request = header.getName()
            + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : "");

    final Matcher matcher = REQUEST_PATTERN.matcher(request);
    final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request);

    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>();

    while (en.hasMoreElements()) {
        header = en.nextElement();/*  ww  w  . j  a  v a 2  s .c  o m*/
        headers.putSingle(header.getName(), header.getValue());
    }

    final Response res;
    final String url;
    final String method;

    if (matcher.find()) {
        url = matcher.group(2);
        method = matcher.group(1);
    } else if (matcherRef.find()) {
        url = references.get(matcherRef.group(2)) + matcherRef.group(3);
        method = matcherRef.group(1);
    } else {
        url = null;
        method = null;
    }

    if (url == null) {
        res = null;
    } else {
        final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null);
        client.headers(headers);

        if ("DELETE".equals(method)) {
            res = client.delete();
        } else {
            final InputStream is = body.getDataHandler().getInputStream();
            String content = IOUtils.toString(is);
            IOUtils.closeQuietly(is);

            final Matcher refs = REF_PATTERN.matcher(content);

            while (refs.find()) {
                content = content.replace(refs.group(1), references.get(refs.group(1)));
            }

            if ("PATCH".equals(method) || "MERGE".equals(method)) {
                client.header("X-HTTP-METHOD", method);
                res = client.invoke("POST", IOUtils.toInputStream(content));
            } else {
                res = client.invoke(method, IOUtils.toInputStream(content));
            }
        }

        // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865
        //client.close();
    }

    return res;
}

From source file:org.apache.olingo.fit.Services.java

private Response bodyPartRequest(final MimeBodyPart body, final Map<String, String> references)
        throws Exception {
    @SuppressWarnings("unchecked")
    final Enumeration<Header> en = body.getAllHeaders();

    Header header = en.nextElement();
    final String request = header.getName()
            + (StringUtils.isNotBlank(header.getValue()) ? ":" + header.getValue() : "");

    final Matcher matcher = REQUEST_PATTERN.matcher(request);
    final Matcher matcherRef = BATCH_REQUEST_REF_PATTERN.matcher(request);

    final MultivaluedMap<String, String> headers = new MultivaluedHashMap<String, String>();

    while (en.hasMoreElements()) {
        header = en.nextElement();//from w w  w  .  j  av  a  2  s . co m
        headers.putSingle(header.getName(), header.getValue());
    }

    final Response res;
    final String url;
    final String method;

    if (matcher.find()) {
        url = matcher.group(2);
        method = matcher.group(1);
    } else if (matcherRef.find()) {
        url = references.get(matcherRef.group(2)) + matcherRef.group(3);
        method = matcherRef.group(1);
    } else {
        url = null;
        method = null;
    }

    if (url == null) {
        res = null;
    } else {
        final WebClient client = WebClient.create(url, "odatajclient", "odatajclient", null);
        client.headers(headers);

        if ("DELETE".equals(method)) {
            res = client.delete();
        } else {
            final InputStream is = body.getDataHandler().getInputStream();
            String content = IOUtils.toString(is);
            IOUtils.closeQuietly(is);

            final Matcher refs = REF_PATTERN.matcher(content);

            while (refs.find()) {
                content = content.replace(refs.group(1), references.get(refs.group(1)));
            }

            if ("PATCH".equals(method) || "MERGE".equals(method)) {
                client.header("X-HTTP-METHOD", method);
                res = client.invoke("POST", IOUtils.toInputStream(content));
            } else {
                res = client.invoke(method, IOUtils.toInputStream(content));
            }
        }

        // When updating to CXF 3.0.1, uncomment the following line, see CXF-5865
        // client.close();
    }

    return res;
}

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private Sequence getMessageListAsXML(Sequence[] args, Sequence contextSequence) throws XPathException {
    Message[] msgList;/*from  www. j  a  va 2s. c  o m*/
    Sequence ret = Sequence.EMPTY_SEQUENCE;

    // was a msgList handle specified?
    if (args[0].isEmpty()) {
        throw (new XPathException(this, "Message List handle not specified"));
    }

    // get the MessageList
    long msgListHandle = ((IntegerValue) args[0].itemAt(0)).getLong();
    msgList = MailModule.retrieveMessageList(context, msgListHandle);
    if (msgList == null) {
        throw (new XPathException(this, "Invalid Message List handle specified"));
    }

    if (msgList.length > 0) {

        boolean includeHeaders = args[1].effectiveBooleanValue();

        MemTreeBuilder builder = context.getDocumentBuilder();

        builder.startDocument();
        builder.startElement(new QName("messages", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
        builder.addAttribute(new QName("count", null, null), String.valueOf(msgList.length));

        try {
            for (int i = 0; i < msgList.length; i++) {
                Message message = msgList[i];

                builder.startElement(new QName("message", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                builder.addAttribute(new QName("number", null, null),
                        String.valueOf(message.getMessageNumber()));

                // Sent Date
                if (message.getSentDate() != null) {
                    builder.startElement(new QName("sent", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(formatDate(message.getSentDate()));
                    builder.endElement();
                }

                // Received Date
                if (message.getReceivedDate() != null) {
                    builder.startElement(new QName("received", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                            null);
                    builder.characters(formatDate(message.getReceivedDate()));
                    builder.endElement();
                }

                // From
                if (message.getFrom() != null) {
                    builder.startElement(new QName("from", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                    builder.characters(message.getFrom()[0].toString());
                    builder.endElement();
                }

                // Recipients
                builder.startElement(new QName("recipients", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                        null);
                // To Recipients
                Address[] toAddresses = message.getRecipients(Message.RecipientType.TO);
                if (toAddresses != null) {
                    for (Address to : toAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "to");
                        builder.characters(to.toString());
                        builder.endElement();
                    }
                }

                // cc Recipients
                Address[] ccAddresses = message.getRecipients(Message.RecipientType.CC);
                if (ccAddresses != null) {
                    for (Address ccAddress : ccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "cc");
                        builder.characters(ccAddress.toString());
                        builder.endElement();
                    }
                }

                // bcc Recipients
                Address[] bccAddresses = message.getRecipients(Message.RecipientType.BCC);
                if (bccAddresses != null) {
                    for (Address bccAddress : bccAddresses) {
                        builder.startElement(
                                new QName("recipient", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                        builder.addAttribute(new QName("type", null, null), "bcc");
                        builder.characters(bccAddress.toString());
                        builder.endElement();
                    }
                }
                builder.endElement();

                // Flags

                Flags flags = message.getFlags();
                Flags.Flag[] systemFlags = flags.getSystemFlags();
                String[] userFlags = flags.getUserFlags();

                if (systemFlags.length > 0 || userFlags.length > 0) {
                    builder.startElement(new QName("flags", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);

                    for (Flags.Flag systemFlag : systemFlags) {
                        if (systemFlag == Flags.Flag.ANSWERED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "answered");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DELETED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "deleted");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.DRAFT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "draft");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.FLAGGED) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "flagged");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.RECENT) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "recent");
                            builder.endElement();
                        } else if (systemFlag == Flags.Flag.SEEN) {
                            builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                    null);
                            builder.addAttribute(new QName("type", null, null), "seen");
                            builder.endElement();
                        }
                    }

                    for (String userFlag : userFlags) {
                        builder.startElement(new QName("flag", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);
                        builder.addAttribute(new QName("type", null, null), "user");
                        builder.addAttribute(new QName("value", null, null), userFlag);
                        builder.endElement();
                    }

                    builder.endElement();
                }

                // Headers

                if (includeHeaders) {
                    Enumeration headers = message.getAllHeaders();

                    if (headers.hasMoreElements()) {
                        builder.startElement(new QName("headers", MailModule.NAMESPACE_URI, MailModule.PREFIX),
                                null);

                        while (headers.hasMoreElements()) {
                            Header header = (Header) headers.nextElement();

                            builder.startElement(
                                    new QName("header", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                            builder.addAttribute(new QName("name", null, null), header.getName());
                            builder.addAttribute(new QName("value", null, null), header.getValue());
                            builder.endElement();
                        }

                        builder.endElement();
                    }
                }

                // Subject
                builder.startElement(new QName("subject", MailModule.NAMESPACE_URI, MailModule.PREFIX), null);
                builder.characters(message.getSubject());
                builder.endElement();

                builder.endElement();
            }
        } catch (MessagingException me) {
            throw (new XPathException(this, "Failed to retrieve messages from list", me));
        }

        builder.endElement();

        ret = (NodeValue) builder.getDocument().getDocumentElement();
    }

    return (ret);
}

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

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;//from w w w.j a va  2 s . c o m
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION_PART_HEADER);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }
            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:org.mule.service.http.impl.service.server.grizzly.HttpParser.java

public static Collection<HttpPart> parseMultipartContent(InputStream content, String contentType)
        throws IOException {
    MimeMultipart mimeMultipart = null;//from ww w  . j  a  va2  s.  c  om
    List<HttpPart> parts = Lists.newArrayList();

    try {
        mimeMultipart = new MimeMultipart(new ByteArrayDataSource(content, contentType));
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    try {
        int partCount = mimeMultipart.getCount();

        for (int i = 0; i < partCount; i++) {
            BodyPart part = mimeMultipart.getBodyPart(i);

            String filename = part.getFileName();
            String partName = filename;
            String[] contentDispositions = part.getHeader(CONTENT_DISPOSITION);
            if (contentDispositions != null) {
                String contentDisposition = contentDispositions[0];
                if (contentDisposition.contains(NAME_ATTRIBUTE)) {
                    partName = contentDisposition.substring(
                            contentDisposition.indexOf(NAME_ATTRIBUTE) + NAME_ATTRIBUTE.length() + 2);
                    partName = partName.substring(0, partName.indexOf("\""));
                }
            }

            if (partName == null && mimeMultipart.getContentType().contains(MULTIPART_RELATED.toString())) {
                String[] contentIdHeader = part.getHeader(CONTENT_ID);
                if (contentIdHeader != null && contentIdHeader.length > 0) {
                    partName = contentIdHeader[0];
                }
            }

            HttpPart httpPart = new HttpPart(partName, filename, IOUtils.toByteArray(part.getInputStream()),
                    part.getContentType(), part.getSize());

            Enumeration<Header> headers = part.getAllHeaders();

            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                httpPart.addHeader(header.getName(), header.getValue());
            }
            parts.add(httpPart);
        }
    } catch (MessagingException e) {
        throw new IOException(e);
    }

    return parts;
}

From source file:org.mule.transport.email.MailMuleMessageFactory.java

@SuppressWarnings({ "unchecked", "rawtypes" })
protected void addMailHeadersToMessageProperties(Message mailMessage, DefaultMuleMessage muleMessage)
        throws MessagingException {
    for (Enumeration<?> e = mailMessage.getAllHeaders(); e.hasMoreElements();) {
        Header header = (Header) e.nextElement();

        String name = header.getName();
        String listName = MailUtils.toListHeader(name);
        String value = header.getValue();

        if (null == muleMessage.getOutboundProperty(name)) {
            muleMessage.setInboundProperty(name, value);
        }/*from www  .jav a 2  s  .  co  m*/

        Object listPropertyValue = muleMessage.getOutboundProperty(listName);
        if (null == listPropertyValue) {
            listPropertyValue = new LinkedList<Object>();
            muleMessage.setInboundProperty(listName, listPropertyValue);
        }
        if (listPropertyValue instanceof List<?>) {
            ((List) listPropertyValue).add(header.getValue());
        }
    }
}