Example usage for javax.mail.internet MimeMessage getSize

List of usage examples for javax.mail.internet MimeMessage getSize

Introduction

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

Prototype

@Override
public int getSize() throws MessagingException 

Source Link

Document

Return the size of the content of this message in bytes.

Usage

From source file:mitm.application.djigzo.james.mailets.BlackberrySMIMEAdapter.java

private void replaceSMIMEAttachment(MimeMessage containerMessage, MimeMessage sourceMessage)
        throws MessagingException, IOException, PartException {
    Part smimePart = findAttachment(containerMessage);

    if (sourceMessage.getSize() > directSizeLimit) {
        /*/*from  ww w  . j  a  va  2 s  .c  om*/
         * The message is too large to be sent to the BB directly so we should 
         * sent it as an attachment that can be downloaded and handled using
         * a content handler on the BB
         */
        String filename = downloadAttachmentName + DOWNLOAD_ATTACHMENT_EXTENSION;

        smimePart.setFileName(filename);
    }

    smimePart.setDataHandler(new DataHandler(
            new ByteArrayDataSource(sourceMessage.getInputStream(), "application/octet-stream")));
}

From source file:org.zilverline.core.IMAPCollection.java

/**
 * Index a MIME message, which seems to be all of them.
 *///from   w  w w.  j  av a2  s . c  o  m
private void indexMimeMessage(final Document doc, final MimeMessage mm) throws MessagingException, IOException {
    // o.println( "\n\n[index mm]: " + mm.getSubject());

    long size = mm.getSize();
    int lines = mm.getLineCount();
    doc.add(Field.Keyword("hash", mm.getMessageID()));

    if (size > 0) {
        doc.add(Field.UnIndexed(F_SIZE, "" + size));
    } else {
        doc.add(Field.UnIndexed(F_SIZE, "" + 0));
    }
    indexPart(doc, mm);
}

From source file:org.apache.james.transport.mailets.HeadersToHTTP.java

private HashSet<NameValuePair> getNameValuePairs(MimeMessage message)
        throws UnsupportedEncodingException, MessagingException {

    // to_address
    // from//  w ww . j a va 2s.c  o  m
    // reply to
    // subject

    HashSet<NameValuePair> pairs = new HashSet<NameValuePair>();

    if (message != null) {
        if (message.getSender() != null) {
            pairs.add(new BasicNameValuePair("from", message.getSender().toString()));
        }
        if (message.getReplyTo() != null) {
            pairs.add(new BasicNameValuePair("reply_to", Arrays.toString(message.getReplyTo())));
        }
        if (message.getMessageID() != null) {
            pairs.add(new BasicNameValuePair("message_id", message.getMessageID()));
        }
        if (message.getSubject() != null) {
            pairs.add(new BasicNameValuePair("subject", message.getSubject()));
        }
        pairs.add(new BasicNameValuePair("size", Integer.toString(message.getSize())));
    }

    pairs.add(new BasicNameValuePair(parameterKey, parameterValue));

    return pairs;
}

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

/**Analyzes and creates passed message data
 *//*from   w  w w  .jav  a2s  .  c  o m*/
public AS2Message createMessageFromRequest(byte[] rawMessageData, Properties header, String contentType)
        throws AS2Exception {
    AS2Message message = new AS2Message(new AS2MessageInfo());
    if (this.configConnection == null) {
        throw new AS2Exception(AS2Exception.PROCESSING_ERROR,
                "AS2MessageParser: Pass a DB connection before calling createMessageFromRequest()", message);
    }
    try {
        //decode the content transfer encoding if set
        rawMessageData = this.processContentTransferEncoding(rawMessageData, header);
        //check if this is a MDN
        MDNParser mdnParser = new MDNParser();
        AS2MDNInfo mdnInfo = mdnParser.parseMDNData(rawMessageData, contentType);
        //its a MDN
        if (mdnInfo != null) {
            message.setAS2Info(mdnInfo);
            mdnInfo.initializeByRequestHeader(header);
            return (this.createFromMDNRequest(rawMessageData, header, contentType, mdnInfo, mdnParser));
        } else {
            AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info();
            messageInfo.initializeByRequestHeader(header);
            //inbound AS2 message, no MDN
            //no futher processing if the message does not contain a message id
            if (messageInfo.getMessageId() == null) {
                return (message);
            }
            //figure out if the MDN should be signed NOW. If an error occurs beyond this point
            //the info has to know if the returned MDN should be signed
            messageInfo.getDispositionNotificationOptions()
                    .setHeaderValue(header.getProperty("disposition-notification-options"));
            //check for existing partners
            PartnerAccessDB partnerAccess = new PartnerAccessDB(this.configConnection, this.runtimeConnection);
            Partner sender = partnerAccess.getPartner(messageInfo.getSenderId());
            Partner receiver = partnerAccess.getPartner(messageInfo.getReceiverId());
            if (sender == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Sender AS2 id " + messageInfo.getSenderId() + " is unknown.", message);
            }
            if (receiver == null) {
                throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR,
                        "Receiver AS2 id " + messageInfo.getReceiverId() + " is unknown.", message);
            }
            if (!receiver.isLocalStation()) {
                throw new AS2Exception(
                        AS2Exception.PROCESSING_ERROR, "The receiver of the message ("
                                + receiver.getAS2Identification() + ") is not defined as a local station.",
                        message);
            }
            MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection);
            //check if the message already exists
            AS2MessageInfo alreadyExistingInfo = this.messageAlreadyExists(messageAccess,
                    messageInfo.getMessageId());
            if (alreadyExistingInfo != null) {
                //perform notification: Resend detected, manual interaction might be required
                Notification notification = new Notification(this.configConnection, this.runtimeConnection);
                notification.sendResendDetected(messageInfo, alreadyExistingInfo, sender, receiver);
                throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "An AS2 message with the message id "
                        + messageInfo.getMessageId()
                        + " has been already processed successfully by the system or is pending ("
                        + alreadyExistingInfo.getInitDate() + "). Please "
                        + " resubmit the message with a new message id instead or resending it if it should be processed again.",
                        new AS2Message(messageInfo));
            }
            messageAccess.initializeOrUpdateMessage(messageInfo);
            if (this.logger != null) {
                //do not log before because the logging process is related to an already created message in the transaction log
                this.logger.log(
                        Level.FINE, this.rb
                                .getResourceString("msg.incoming",
                                        new Object[] { messageInfo.getMessageId(),
                                                AS2Tools.getDataSizeDisplay(rawMessageData.length) }),
                        messageInfo);
            }
            //indicates if a sync or async mdn is requested
            messageInfo.setAsyncMDNURL(header.getProperty("receipt-delivery-option"));
            messageInfo.setRequestsSyncMDN(header.getProperty("receipt-delivery-option") == null
                    || header.getProperty("receipt-delivery-option").trim().length() == 0);
            message.setRawData(rawMessageData);
            byte[] decryptedData = this.decryptMessage(message, rawMessageData, contentType, sender, receiver);
            //may be already compressed here. Decompress first before going further
            if (this.contentTypeIndicatesCompression(contentType)) {
                byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(), decryptedData,
                        contentType);
                message.setDecryptedRawData(decompressed);
                //content type has changed now, get it from the decompressed data
                ByteArrayInputStream memIn = new ByteArrayInputStream(decompressed);
                MimeBodyPart tempPart = new MimeBodyPart(memIn);
                memIn.close();
                contentType = tempPart.getContentType();
            } else {
                //check the MIME structure that is embedded in decryptedData for its content type
                ByteArrayInputStream memIn = new ByteArrayInputStream(decryptedData);
                MimeMessage possibleCompressedPart = new MimeMessage(
                        Session.getInstance(System.getProperties()), memIn);
                memIn.close();
                if (this.contentTypeIndicatesCompression(possibleCompressedPart.getContentType())) {
                    long compressedSize = possibleCompressedPart.getSize();
                    byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(),
                            new SMIMECompressed(possibleCompressedPart), compressedSize);
                    message.setDecryptedRawData(decompressed);
                } else {
                    message.setDecryptedRawData(decryptedData);
                }
            }
            decryptedData = null;
            Part payloadPart = this.verifySignature(message, sender, contentType);
            //decompress the data if it has been sent compressed, only possible for signed data
            if (message.getAS2Info().getSignType() != AS2Message.SIGNATURE_NONE) {
                //signed message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.1 MIC Calculation For Signed Message
                //For any signed message, the MIC to be returned is calculated over
                //the same data that was signed in the original message as per [AS1].
                //The signed content will be a mime bodypart that contains either
                //compressed or uncompressed data.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
                payloadPart = this.decompressData(payloadPart, message);
                this.writePayloadsToMessage(payloadPart, message, header);
            } else {
                //this is an unsigned message
                this.writePayloadsToMessage(message.getDecryptedRawData(), message, header);
                //unsigned message:
                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.2 MIC Calculation For Encrypted, Unsigned Message
                //For encrypted, unsigned messages, the MIC to be returned is
                //calculated over the uncompressed data content including all
                //MIME header fields and any applied Content-Transfer-Encoding.

                //http://tools.ietf.org/html/draft-ietf-ediint-compression-12
                //4.3 MIC Calculation For Unencrypted, Unsigned Message
                //For unsigned, unencrypted messages, the MIC is calculated
                //over the uncompressed data content including all MIME header
                //fields and any applied Content-Transfer-Encoding.                    
                this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType);
            }
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("found.attachments",
                        new Object[] { messageInfo.getMessageId(), String.valueOf(message.getPayloadCount()) }),
                        messageInfo);
            }
            return (message);
        }
    } catch (Exception e) {
        if (e instanceof AS2Exception) {
            throw (AS2Exception) e;
        } else {
            throw new AS2Exception(AS2Exception.PROCESSING_ERROR, e.getMessage(), message);
        }
    }
}

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

/**Writes a passed payload data to the passed message object. Could be called from either the MDN
 * processing or the message processing//w w w . j av a 2s.  c om
 */
public void writePayloadsToMessage(byte[] data, AS2Message message, Properties header) throws Exception {
    ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
    MimeMessage testMessage = new MimeMessage(Session.getInstance(System.getProperties()),
            new ByteArrayInputStream(data));
    //multiple attachments?
    if (testMessage.isMimeType("multipart/*")) {
        this.writePayloadsToMessage(testMessage, message, header);
        return;
    }
    InputStream payloadIn = null;
    AS2Info info = message.getAS2Info();
    if (info instanceof AS2MessageInfo && info.getSignType() == AS2Message.SIGNATURE_NONE
            && ((AS2MessageInfo) info).getCompressionType() == AS2Message.COMPRESSION_NONE) {
        payloadIn = new ByteArrayInputStream(data);
    } else if (testMessage.getSize() > 0) {
        payloadIn = testMessage.getInputStream();
    } else {
        payloadIn = new ByteArrayInputStream(data);
    }
    this.copyStreams(payloadIn, payloadOut);
    payloadOut.flush();
    payloadOut.close();
    byte[] payloadData = payloadOut.toByteArray();
    AS2Payload as2Payload = new AS2Payload();
    as2Payload.setData(payloadData);
    String contentIdHeader = header.getProperty("content-id");
    if (contentIdHeader != null) {
        as2Payload.setContentId(contentIdHeader);
    }
    String contentTypeHeader = header.getProperty("content-type");
    if (contentTypeHeader != null) {
        as2Payload.setContentType(contentTypeHeader);
    }
    try {
        as2Payload.setOriginalFilename(testMessage.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);
}

From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java

/**
 * A method that executes the reading of data from the email account to the
 * RBNB server after all configuration of settings, connections to hosts,
 * and thread initiatizing occurs. This method contains the detailed code
 * for reading the data and interpreting the data files.
 *//*ww  w .  j a v a2  s.  c o m*/
protected boolean execute() {
    logger.debug("StorXDispatcher.execute() called.");
    boolean failed = true; // indicates overall success of execute()
    boolean messageProcessed = false; // indicates per message success

    // declare the account properties that will be pulled from the
    // email.account.properties.xml file
    String accountName = "";
    String server = "";
    String username = "";
    String password = "";
    String protocol = "";
    String dataMailbox = "";
    String processedMailbox = "";
    String prefetch = "";

    // fetch data from each sensor in the account list
    List accountList = this.xmlConfiguration.getList("account.accountName");

    for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) {

        int aIndex = accountList.indexOf(aIterator.next());

        // populate the email connection variables from the xml properties
        // file
        accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName");
        server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server");
        username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username");
        password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password");
        protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol");
        dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox");
        processedMailbox = (String) this.xmlConfiguration
                .getProperty("account(" + aIndex + ").processedMailbox");
        prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch");

        logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName     : " + accountName + "\n"
                + "server          : " + server + "\n" + "username        : " + username + "\n"
                + "password        : " + password + "\n" + "protocol        : " + protocol + "\n"
                + "dataMailbox     : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n"
                + "prefetch        : " + prefetch + "\n");

        // get a connection to the mail server
        Properties props = System.getProperties();
        props.setProperty("mail.store.protocol", protocol);
        props.setProperty("mail.imaps.partialfetch", prefetch);

        try {

            // create the imaps mail session
            this.mailSession = Session.getDefaultInstance(props, null);
            this.mailStore = mailSession.getStore(protocol);

        } catch (NoSuchProviderException nspe) {

            try {
                // pause for 10 seconds
                logger.debug(
                        "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry.");
                Thread.sleep(10000L);
                this.mailStore = mailSession.getStore(protocol);

            } catch (NoSuchProviderException nspe2) {

                logger.debug("There was an error connecting to the mail server. The " + "message was: "
                        + nspe2.getMessage());
                nspe2.printStackTrace();
                failed = true;
                return !failed;

            } catch (InterruptedException ie) {

                logger.debug("The thread was interrupted: " + ie.getMessage());
                failed = true;
                return !failed;

            }

        }

        try {

            this.mailStore.connect(server, username, password);

            // get folder references for the inbox and processed data box
            Folder inbox = mailStore.getFolder(dataMailbox);
            inbox.open(Folder.READ_WRITE);

            Folder processed = this.mailStore.getFolder(processedMailbox);
            processed.open(Folder.READ_WRITE);

            Message[] msgs;
            while (!inbox.isOpen()) {
                inbox.open(Folder.READ_WRITE);

            }
            msgs = inbox.getMessages();

            List<Message> messages = new ArrayList<Message>();
            Collections.addAll(messages, msgs);

            // sort the messages found in the inbox by date sent
            Collections.sort(messages, new Comparator<Message>() {

                public int compare(Message message1, Message message2) {
                    int value = 0;
                    try {
                        value = message1.getSentDate().compareTo(message2.getSentDate());
                    } catch (MessagingException e) {
                        e.printStackTrace();
                    }
                    return value;

                }

            });

            logger.debug("Number of messages: " + messages.size());
            for (Message message : messages) {

                // Copy the message to ensure we have the full attachment
                MimeMessage mimeMessage = (MimeMessage) message;
                MimeMessage copiedMessage = new MimeMessage(mimeMessage);

                // determine the sensor serial number for this message
                String messageSubject = copiedMessage.getSubject();
                Date sentDate = copiedMessage.getSentDate();
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");

                // The subfolder of the processed mail folder (e.g. 2016-12);
                String destinationFolder = formatter.format(sentDate);
                logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber());
                String[] subjectParts = messageSubject.split("\\s");
                String loggerSerialNumber = "SerialNumber";
                if (subjectParts.length > 1) {
                    loggerSerialNumber = subjectParts[2];

                }

                // Do we have a data attachment? If not, there's no data to
                // process
                if (copiedMessage.isMimeType("multipart/mixed")) {

                    logger.debug("Message size: " + copiedMessage.getSize());

                    MimeMessageParser parser = new MimeMessageParser(copiedMessage);
                    try {
                        parser.parse();

                    } catch (Exception e) {
                        logger.error("Failed to parse the MIME message: " + e.getMessage());
                        continue;
                    }
                    ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only

                    logger.debug("Has attachments: " + parser.hasAttachments());
                    for (DataSource dataSource : parser.getAttachmentList()) {
                        if (StringUtils.isNotBlank(dataSource.getName())) {
                            logger.debug(
                                    "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType());

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            IOUtils.copy(dataSource.getInputStream(), outputStream);
                            messageAttachment = ByteBuffer.wrap(outputStream.toByteArray());

                        }
                    }

                    // We now have the attachment and serial number. Parse the attachment 
                    // for the data components, look up the storXSource based on the serial 
                    // number, and push the data to the DataTurbine

                    // parse the binary attachment
                    StorXParser storXParser = new StorXParser(messageAttachment);

                    // iterate through the parsed framesMap and handle each
                    // frame
                    // based on its instrument type
                    BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap();

                    Collection frameCollection = framesMap.getAll("/frames/frame");
                    Iterator framesIterator = frameCollection.iterator();

                    while (framesIterator.hasNext()) {

                        BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next();

                        // logger.debug(frameMap.toXMLString(1000));

                        String frameType = (String) frameMap.get("type");
                        String sensorSerialNumber = (String) frameMap.get("serialNumber");

                        // handle each instrument type
                        if (frameType.equals("HDR")) {
                            logger.debug("This is a header frame. Skipping it.");

                        } else if (frameType.equals("STX")) {

                            try {

                                // handle StorXSource
                                StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the StorXSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("SBE")) {

                            try {

                                // handle CTDSource
                                CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber);

                                // process the data using the CTDSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NLB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else if (frameType.equals("NDB")) {

                            try {

                                // handle ISUSSource
                                ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber);
                                // process the data using the ISUSSource
                                // driver
                                messageProcessed = source.process(this.xmlConfiguration, frameMap);

                            } catch (ClassCastException cce) {

                            }

                        } else {

                            logger.debug("The frame type " + frameType + " is not recognized. Skipping it.");
                        }

                    } // end while()

                    if (this.sourceMap.get(loggerSerialNumber) != null) {

                        // Note: Use message (not copiedMessage) when setting flags 

                        if (!messageProcessed) {
                            logger.info("Failed to process message: " + "Message Number: "
                                    + message.getMessageNumber() + "  " + "Logger Serial:"
                                    + loggerSerialNumber);
                            // leave it in the inbox, flagged as seen (read)
                            message.setFlag(Flags.Flag.SEEN, true);
                            logger.debug("Saw message " + message.getMessageNumber());

                        } else {

                            // message processed successfully. Create a by-month sub folder if it doesn't exist
                            // Copy the message and flag it deleted
                            Folder destination = processed.getFolder(destinationFolder);
                            boolean created = destination.create(Folder.HOLDS_MESSAGES);
                            inbox.copyMessages(new Message[] { message }, destination);
                            message.setFlag(Flags.Flag.DELETED, true);
                            logger.debug("Deleted message " + message.getMessageNumber());
                        } // end if()

                    } else {
                        logger.debug("There is no configuration information for " + "the logger serial number "
                                + loggerSerialNumber + ". Please add the configuration to the "
                                + "email.account.properties.xml configuration file.");

                    } // end if()

                } else {
                    logger.debug("This is not a data email since there is no "
                            + "attachment. Skipping it. Subject: " + messageSubject);

                } // end if()

            } // end for()

            // expunge messages and close the mail server store once we're
            // done
            inbox.expunge();
            this.mailStore.close();

        } catch (MessagingException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                failed = true;
                return !failed;

            }
            logger.info(
                    "There was an error reading the mail message. The " + "message was: " + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IOException me) {
            try {
                this.mailStore.close();

            } catch (MessagingException me3) {
                failed = true;
                return !failed;

            }
            logger.info("There was an I/O error reading the message part. The " + "message was: "
                    + me.getMessage());
            me.printStackTrace();
            failed = true;
            return !failed;

        } catch (IllegalStateException ese) {
            try {
                this.mailStore.close();

            } catch (MessagingException me4) {
                failed = true;
                return !failed;

            }
            logger.info("There was an error reading messages from the folder. The " + "message was: "
                    + ese.getMessage());
            failed = true;
            return !failed;

        } finally {

            try {
                this.mailStore.close();

            } catch (MessagingException me2) {
                logger.debug("Couldn't close the mail store: " + me2.getMessage());

            }

        }

    }

    return !failed;
}

From source file:com.zimbra.cs.service.mail.ToXML.java

/** Encodes an Invite stored within a calendar item object into <m> element
 *  with <mp> elements.//from   w w w.  java  2s .c  om
 * @param parent  The Element to add the new <tt>&lt;m></tt> to.
 * @param ifmt    The SOAP request's context.
 * @param calItem The calendar item to serialize.
 * @param iid     The requested item; the contained subpart will be used to
 *                pick the Invite out of the calendar item's blob & metadata.
 * @param part    If non-null, we'll serialuize this message/rfc822 subpart
 *                of the specified Message instead of the Message itself.
 * @param maxSize The maximum amount of content to inline (<=0 is unlimited).
 * @param wantHTML  <tt>true</tt> to prefer HTML parts as the "body",
 *                  <tt>false</tt> to prefer text/plain parts.
 * @param neuter  Whether to rename "src" attributes on HTML <img> tags.
 * @param headers Extra message headers to include in the returned element.
 * @param serializeType If <tt>false</tt>, always serializes as an
 *                      <tt>&lt;m></tt> element.
 * @return The newly-created <tt>&lt;m></tt> Element, which has already
 *         been added as a child to the passed-in <tt>parent</tt>.
 * @throws ServiceException */
public static Element encodeInviteAsMP(Element parent, ItemIdFormatter ifmt, OperationContext octxt,
        CalendarItem calItem, String recurIdZ, ItemId iid, String part, int maxSize, boolean wantHTML,
        boolean neuter, Set<String> headers, boolean serializeType, boolean wantExpandGroupInfo)
        throws ServiceException {
    int invId = iid.getSubpartId();
    Invite[] invites = calItem.getInvites(invId);
    boolean isPublic = calItem.isPublic();
    boolean showAll = isPublic || allowPrivateAccess(octxt, calItem);

    boolean wholeMessage = (part == null || part.trim().isEmpty());

    Element m;
    if (wholeMessage) {
        // We want to return the MODIFIED_CONFLICT fields to enable conflict detection on modify.
        int fields = NOTIFY_FIELDS | Change.CONFLICT;
        m = encodeMessageCommon(parent, ifmt, octxt, calItem, fields, serializeType);
        m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(calItem, invId));
    } else {
        m = parent.addElement(MailConstants.E_MSG);
        m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(calItem, invId));
        m.addAttribute(MailConstants.A_PART, part);
    }

    try {
        MimeMessage mm = calItem.getSubpartMessage(invId);
        if (mm != null) {
            if (!wholeMessage) {
                MimePart mp = Mime.getMimePart(mm, part);
                if (mp == null) {
                    throw MailServiceException.NO_SUCH_PART(part);
                }
                Object content = Mime.getMessageContent(mp);
                if (!(content instanceof MimeMessage)) {
                    throw MailServiceException.NO_SUCH_PART(part);
                }
                mm = (MimeMessage) content;
            } else {
                part = "";
            }
            if (showAll) {
                addEmails(m, Mime.parseAddressHeader(mm, "From"), EmailType.FROM);
                addEmails(m, Mime.parseAddressHeader(mm, "Sender"), EmailType.SENDER);
                addEmails(m, Mime.parseAddressHeader(mm, "Reply-To"), EmailType.REPLY_TO);
                addEmails(m, Mime.parseAddressHeader(mm, "To"), EmailType.TO);
                addEmails(m, Mime.parseAddressHeader(mm, "Cc"), EmailType.CC);
                addEmails(m, Mime.parseAddressHeader(mm, "Bcc"), EmailType.BCC);

                String subject = Mime.getSubject(mm);
                if (subject != null) {
                    m.addAttribute(MailConstants.E_SUBJECT, StringUtil.stripControlCharacters(subject),
                            Element.Disposition.CONTENT);
                }
                String messageID = mm.getMessageID();
                if (messageID != null && !messageID.trim().isEmpty()) {
                    m.addAttribute(MailConstants.E_MSG_ID_HDR, StringUtil.stripControlCharacters(messageID),
                            Element.Disposition.CONTENT);
                }
                if (!wholeMessage) {
                    m.addAttribute(MailConstants.A_SIZE, mm.getSize());
                }
                java.util.Date sent = mm.getSentDate();
                if (sent != null) {
                    m.addAttribute(MailConstants.A_SENT_DATE, sent.getTime());
                }
            }
        }

        Element invElt = m.addElement(MailConstants.E_INVITE);
        setCalendarItemType(invElt, calItem.getType());
        encodeTimeZoneMap(invElt, calItem.getTimeZoneMap());
        if (invites.length > 0) {
            if (showAll) {
                encodeCalendarReplies(invElt, calItem, invites[0], recurIdZ);
            }
            for (Invite inv : invites) {
                encodeInviteComponent(invElt, ifmt, octxt, calItem, (ItemId) null, inv, NOTIFY_FIELDS, neuter);
            }
        }

        //encodeAlarmTimes(invElt, calItem);

        if (mm != null && showAll) {
            if (headers != null) {
                for (String name : headers) {
                    String[] values = mm.getHeader(name);
                    if (values == null) {
                        continue;
                    }
                    for (int i = 0; i < values.length; i++) {
                        m.addKeyValuePair(name, values[i], MailConstants.A_HEADER,
                                MailConstants.A_ATTRIBUTE_NAME);
                    }
                }
            }

            List<MPartInfo> parts = Mime.getParts(mm, getDefaultCharset(calItem));
            if (parts != null && !parts.isEmpty()) {
                Set<MPartInfo> bodies = Mime.getBody(parts, wantHTML);
                addParts(m, parts.get(0), bodies, part, maxSize, neuter, true, getDefaultCharset(calItem),
                        true);
            }
        }

        if (wantExpandGroupInfo) {
            Account authedAcct = octxt.getAuthenticatedUser();
            Account requestedAcct = calItem.getMailbox().getAccount();
            encodeAddrsWithGroupInfo(m, requestedAcct, authedAcct);
        }
    } catch (IOException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } catch (MessagingException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    }
    return m;
}

From source file:com.zimbra.cs.service.mail.ToXML.java

/** Encodes a Message object into <m> element with <mp> elements for
 *  message body.//from  w w w  .j  a  va2 s  . c  om
 * @param parent  The Element to add the new <tt>&lt;m></tt> to.
 * @param ifmt    The formatter to sue when serializing item ids.
 * @param msg     The Message to serialize.
 * @param part    If non-null, serialize this message/rfc822 subpart of
 *                the Message instead of the Message itself.
 * @param maxSize TODO
 * @param wantHTML  <tt>true</tt> to prefer HTML parts as the "body",
 *                  <tt>false</tt> to prefer text/plain parts.
 * @param neuter  Whether to rename "src" attributes on HTML <img> tags.
 * @param headers Extra message headers to include in the returned element.
 * @param serializeType If <tt>false</tt>, always serializes as an
 *                      <tt>&lt;m></tt> element.
 * @param bestEffort  If <tt>true</tt>, errors serializing part content
 *                    are swallowed.
 * @return The newly-created <tt>&lt;m></tt> Element, which has already
 *         been added as a child to the passed-in <tt>parent</tt>.
 * @throws ServiceException */
private static Element encodeMessageAsMP(Element parent, ItemIdFormatter ifmt, OperationContext octxt,
        Message msg, String part, int maxSize, boolean wantHTML, boolean neuter, Set<String> headers,
        boolean serializeType, boolean wantExpandGroupInfo, boolean bestEffort, boolean encodeMissingBlobs,
        MsgContent wantContent) throws ServiceException {
    Element m = null;
    boolean success = false;
    try {
        boolean wholeMessage = part == null || part.trim().isEmpty();
        if (wholeMessage) {
            m = encodeMessageCommon(parent, ifmt, octxt, msg, NOTIFY_FIELDS, serializeType);
            m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg));
        } else {
            m = parent.addElement(MailConstants.E_MSG);
            m.addAttribute(MailConstants.A_ID, ifmt.formatItemId(msg));
            m.addAttribute(MailConstants.A_PART, part);
        }

        MimeMessage mm = null;
        try {
            String requestedAccountId = octxt.getmRequestedAccountId();
            String authtokenAccountId = octxt.getmAuthTokenAccountId();
            boolean isDecryptionNotAllowed = StringUtils.isNotEmpty(authtokenAccountId)
                    && !authtokenAccountId.equalsIgnoreCase(requestedAccountId);
            if (isDecryptionNotAllowed && Mime.isEncrypted(msg.getMimeMessage(false).getContentType())) {
                mm = msg.getMimeMessage(false);
            } else {
                mm = msg.getMimeMessage();
            }
        } catch (MailServiceException e) {
            if (encodeMissingBlobs && MailServiceException.NO_SUCH_BLOB.equals(e.getCode())) {
                ZimbraLog.mailbox.error("Unable to get blob while encoding message", e);
                encodeEmail(m, msg.getSender(), EmailType.FROM);
                encodeEmail(m, msg.getSender(), EmailType.SENDER);
                if (msg.getRecipients() != null) {
                    addEmails(m, Mime.parseAddressHeader(msg.getRecipients()), EmailType.TO);
                }
                m.addAttribute(MailConstants.A_SUBJECT, msg.getSubject());
                Element mimePart = m.addElement(MailConstants.E_MIMEPART);
                mimePart.addAttribute(MailConstants.A_PART, 1);
                mimePart.addAttribute(MailConstants.A_BODY, true);
                mimePart.addAttribute(MailConstants.A_CONTENT_TYPE, MimeConstants.CT_TEXT_PLAIN);

                String errMsg = L10nUtil.getMessage(L10nUtil.MsgKey.errMissingBlob,
                        msg.getAccount().getLocale(), ifmt.formatItemId(msg));
                m.addAttribute(MailConstants.E_FRAG, errMsg, Element.Disposition.CONTENT);
                mimePart.addAttribute(MailConstants.E_CONTENT, errMsg, Element.Disposition.CONTENT);
                success = true; //not really success, but mark as such so the element is appended correctly
                return m;
            }
            throw e;
        }
        if (!wholeMessage) {
            MimePart mp = Mime.getMimePart(mm, part);
            if (mp == null) {
                throw MailServiceException.NO_SUCH_PART(part);
            }
            Object content = Mime.getMessageContent(mp);
            if (!(content instanceof MimeMessage)) {
                throw MailServiceException.NO_SUCH_PART(part);
            }
            mm = (MimeMessage) content;
        } else {
            part = "";
        }

        // Add fragment before emails to maintain consistent ordering
        // of elements with encodeConversation - need to do this to
        // overcome JAXB issues.

        String fragment = msg.getFragment();
        if (fragment != null && !fragment.isEmpty()) {
            m.addAttribute(MailConstants.E_FRAG, fragment, Element.Disposition.CONTENT);
        }

        addEmails(m, Mime.parseAddressHeader(mm, "From"), EmailType.FROM);
        addEmails(m, Mime.parseAddressHeader(mm, "Sender"), EmailType.SENDER);
        addEmails(m, Mime.parseAddressHeader(mm, "Reply-To"), EmailType.REPLY_TO);
        addEmails(m, Mime.parseAddressHeader(mm, "To"), EmailType.TO);
        addEmails(m, Mime.parseAddressHeader(mm, "Cc"), EmailType.CC);
        addEmails(m, Mime.parseAddressHeader(mm, "Bcc"), EmailType.BCC);
        addEmails(m, Mime.parseAddressHeader(mm.getHeader("Resent-From", null), false), EmailType.RESENT_FROM);
        // read-receipts only get sent by the mailbox's owner
        if (!(octxt.isDelegatedRequest(msg.getMailbox()) && octxt.isOnBehalfOfRequest(msg.getMailbox()))) {
            addEmails(m, Mime.parseAddressHeader(mm, "Disposition-Notification-To"), EmailType.READ_RECEIPT);
        }

        String calIntendedFor = msg.getCalendarIntendedFor();
        m.addAttribute(MailConstants.A_CAL_INTENDED_FOR, calIntendedFor);

        String subject = Mime.getSubject(mm);
        if (subject != null) {
            m.addAttribute(MailConstants.E_SUBJECT, StringUtil.stripControlCharacters(subject),
                    Element.Disposition.CONTENT);
        }

        String messageID = mm.getMessageID();
        if (messageID != null && !messageID.trim().isEmpty()) {
            m.addAttribute(MailConstants.E_MSG_ID_HDR, StringUtil.stripControlCharacters(messageID),
                    Element.Disposition.CONTENT);
        }

        if (wholeMessage && msg.isDraft()) {
            if (!msg.getDraftOrigId().isEmpty()) {
                ItemId origId = new ItemId(msg.getDraftOrigId(), msg.getMailbox().getAccountId());
                m.addAttribute(MailConstants.A_ORIG_ID, ifmt.formatItemId(origId));
            }
            if (!msg.getDraftReplyType().isEmpty()) {
                m.addAttribute(MailConstants.A_REPLY_TYPE, msg.getDraftReplyType());
            }
            if (!msg.getDraftIdentityId().isEmpty()) {
                m.addAttribute(MailConstants.A_IDENTITY_ID, msg.getDraftIdentityId());
            }
            if (!msg.getDraftAccountId().isEmpty()) {
                m.addAttribute(MailConstants.A_FOR_ACCOUNT, msg.getDraftAccountId());
            }
            String inReplyTo = mm.getHeader("In-Reply-To", null);
            if (inReplyTo != null && !inReplyTo.isEmpty()) {
                m.addAttribute(MailConstants.E_IN_REPLY_TO, StringUtil.stripControlCharacters(inReplyTo),
                        Element.Disposition.CONTENT);
            }
            if (msg.getDraftAutoSendTime() != 0) {
                m.addAttribute(MailConstants.A_AUTO_SEND_TIME, msg.getDraftAutoSendTime());
            }
        }

        if (!wholeMessage) {
            m.addAttribute(MailConstants.A_SIZE, mm.getSize());
        }

        Date sent = mm.getSentDate();
        if (sent != null) {
            m.addAttribute(MailConstants.A_SENT_DATE, sent.getTime());
        }

        Calendar resent = DateUtil.parseRFC2822DateAsCalendar(mm.getHeader("Resent-Date", null));
        if (resent != null) {
            m.addAttribute(MailConstants.A_RESENT_DATE, resent.getTimeInMillis());
        }

        if (msg.isInvite() && msg.hasCalendarItemInfos()) {
            encodeInvitesForMessage(m, ifmt, octxt, msg, NOTIFY_FIELDS, neuter);
        }

        if (headers != null) {
            for (String name : headers) {
                String[] values = mm.getHeader(name);
                if (values != null) {
                    for (int i = 0; i < values.length; i++) {
                        m.addKeyValuePair(name, values[i], MailConstants.A_HEADER,
                                MailConstants.A_ATTRIBUTE_NAME);
                    }
                }
            }
        }

        List<MPartInfo> parts = Mime.getParts(mm, getDefaultCharset(msg));
        if (parts != null && !parts.isEmpty()) {
            Set<MPartInfo> bodies = Mime.getBody(parts, wantHTML);
            addParts(m, parts.get(0), bodies, part, maxSize, neuter, false, getDefaultCharset(msg), bestEffort,
                    wantContent);
        }

        if (wantExpandGroupInfo) {
            ZimbraLog.gal.trace("want expand group info");
            Account authedAcct = octxt.getAuthenticatedUser();
            Account requestedAcct = msg.getMailbox().getAccount();
            encodeAddrsWithGroupInfo(m, requestedAcct, authedAcct);
        } else {
            ZimbraLog.gal.trace("do not want expand group info");
        }

        success = true;
        // update crypto flags - isSigned/isEncrypted
        if (SmimeHandler.getHandler() != null) {
            if (!wholeMessage) {
                // check content type of attachment message for encryption flag
                SmimeHandler.getHandler().updateCryptoFlags(msg, m, mm, mm);
            } else {
                MimeMessage originalMimeMessage = msg.getMimeMessage(false);
                SmimeHandler.getHandler().updateCryptoFlags(msg, m, originalMimeMessage, mm);
            }
        }

        // if the mime it is signed
        if (Mime.isMultipartSigned(mm.getContentType()) || Mime.isPKCS7Signed(mm.getContentType())) {
            ZimbraLog.mailbox
                    .debug("The message is signed. Forwarding it to SmimeHandler for signature verification.");
            if (SmimeHandler.getHandler() != null) {
                SmimeHandler.getHandler().verifyMessageSignature(msg.getMailbox().getAccount(), m, mm,
                        octxt.getmResponseProtocol());
            }
        } else {
            // if the original mime message was PKCS7-signed and it was
            // decoded and stored in cache as plain mime
            if ((mm instanceof Mime.FixedMimeMessage) && ((Mime.FixedMimeMessage) mm).isPKCS7Signed()) {
                if (SmimeHandler.getHandler() != null) {
                    SmimeHandler.getHandler().addPKCS7SignedMessageSignatureDetails(
                            msg.getMailbox().getAccount(), m, mm, octxt.getmResponseProtocol());
                }
            }
        }
        return m;
    } catch (IOException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } catch (MessagingException ex) {
        throw ServiceException.FAILURE(ex.getMessage(), ex);
    } finally {
        // don't leave turds around if we're going to retry
        if (!success && !bestEffort && m != null) {
            m.detach();
        }
    }
}

From source file:fr.gouv.culture.vitam.eml.EmlExtract.java

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {//from  w  ww .jav  a2  s  .  c o m
    File oldDir = argument.currentOutputDir;
    if (argument.currentOutputDir == null) {
        if (config.outputDir != null) {
            argument.currentOutputDir = new File(config.outputDir);
        }
    }
    Element keywords = XmlDom.factory.createElement(EMAIL_FIELDS.keywords.name);
    Element metadata = XmlDom.factory.createElement(EMAIL_FIELDS.metadata.name);
    String skey = "";
    String id = config.addRankId(root);
    Address[] from = null;
    Element sub2 = null;
    try {
        from = message.getFrom();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("From");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);
            }
        } catch (MessagingException e) {
        }
    }
    Address sender = null;
    try {
        sender = message.getSender();
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Sender");
            if (partialResult != null && partialResult.length > 0) {
                if (sub2 == null) {
                    sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.from.name);
                    Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                    add.setText(partialResult[0]);
                    sub2.add(add);
                }
            }
        } catch (MessagingException e) {
        }
    }
    if (from != null && from.length > 0) {
        String value0 = null;
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        if (sender != null) {
            value0 = addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        }
        for (Address address : from) {
            addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, value0);
        }
        metadata.add(sub);
    } else if (sender != null) {
        Element sub = (sub2 != null ? sub2 : XmlDom.factory.createElement(EMAIL_FIELDS.from.name));
        addAddress(sub, EMAIL_FIELDS.fromUnit.name, sender, null);
        metadata.add(sub);
    } else {
        if (sub2 != null) {
            metadata.add(sub2);
        }
    }
    Address[] replyTo = null;
    try {
        replyTo = message.getReplyTo();
        if (replyTo != null && replyTo.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
            for (Address address : replyTo) {
                addAddress(sub, EMAIL_FIELDS.fromUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("ReplyTo");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.replyTo.name);
                addAddress(sub2, EMAIL_FIELDS.fromUnit.name, partialResult, null);
                /*Element add = XmlDom.factory.createElement(EMAIL_FIELDS.fromUnit.name);
                add.setText(partialResult[0]);
                sub2.add(add);*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] toRecipients = null;
    try {
        toRecipients = message.getRecipients(Message.RecipientType.TO);
        if (toRecipients != null && toRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
            for (Address address : toRecipients) {
                addAddress(sub, EMAIL_FIELDS.toUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("To");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.toRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.toUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.toUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] ccRecipients;
    try {
        ccRecipients = message.getRecipients(Message.RecipientType.CC);
        if (ccRecipients != null && ccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
            for (Address address : ccRecipients) {
                addAddress(sub, EMAIL_FIELDS.ccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.ccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.ccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.ccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    Address[] bccRecipients;
    try {
        bccRecipients = message.getRecipients(Message.RecipientType.BCC);
        if (bccRecipients != null && bccRecipients.length > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
            for (Address address : bccRecipients) {
                addAddress(sub, EMAIL_FIELDS.bccUnit.name, address, null);
            }
            metadata.add(sub);
        }
    } catch (MessagingException e1) {
        String[] partialResult;
        try {
            partialResult = message.getHeader("Cc");
            if (partialResult != null && partialResult.length > 0) {
                sub2 = XmlDom.factory.createElement(EMAIL_FIELDS.bccRecipients.name);
                addAddress(sub2, EMAIL_FIELDS.bccUnit.name, partialResult, null);
                /*for (String string : partialResult) {
                   Element add = XmlDom.factory.createElement(EMAIL_FIELDS.bccUnit.name);
                   add.setText(string);
                   sub2.add(add);
                }*/
                metadata.add(sub2);
            }
        } catch (MessagingException e) {
        }
    }
    try {
        String subject = message.getSubject();
        if (subject != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.subject.name);
            sub.setText(StringUtils.unescapeHTML(subject, true, false));
            metadata.add(sub);
        }
        Date sentDate = message.getSentDate();
        if (sentDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.sentDate.name);
            sub.setText(sentDate.toString());
            metadata.add(sub);
        }
        Date receivedDate = message.getReceivedDate();
        if (receivedDate != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
            sub.setText(receivedDate.toString());
            metadata.add(sub);
        }
        String[] headers = message.getHeader("Received");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.receptionTrace.name);
            MailDateFormat mailDateFormat = null;
            long maxTime = 0;
            if (receivedDate == null) {
                mailDateFormat = new MailDateFormat();
            }
            for (String string : headers) {
                Element sub3 = XmlDom.factory.createElement(EMAIL_FIELDS.trace.name);
                sub3.setText(StringUtils.unescapeHTML(string, true, false));
                sub.add(sub3);
                if (receivedDate == null) {
                    int pos = string.lastIndexOf(';');
                    if (pos > 0) {
                        String recvdate = string.substring(pos + 2).replaceAll("\t\n\r\f", "").trim();
                        try {
                            Date date = mailDateFormat.parse(recvdate);
                            if (date.getTime() > maxTime) {
                                maxTime = date.getTime();
                            }
                        } catch (ParseException e) {
                        }
                    }
                }
            }
            if (receivedDate == null) {
                Element subdate = XmlDom.factory.createElement(EMAIL_FIELDS.receivedDate.name);
                Date date = new Date(maxTime);
                subdate.setText(date.toString());
                metadata.add(subdate);
            }
            metadata.add(sub);
        }
        int internalSize = message.getSize();
        if (internalSize > 0) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.emailSize.name);
            sub.setText(Integer.toString(internalSize));
            metadata.add(sub);
        }
        String encoding = message.getEncoding();
        if (encoding != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.encoding.name);
            sub.setText(StringUtils.unescapeHTML(encoding, true, false));
            metadata.add(sub);
        }
        String description = message.getDescription();
        if (description != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.description.name);
            sub.setText(StringUtils.unescapeHTML(description, true, false));
            metadata.add(sub);
        }
        String contentType = message.getContentType();
        if (contentType != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentType.name);
            sub.setText(StringUtils.unescapeHTML(contentType, true, false));
            metadata.add(sub);
        }
        headers = message.getHeader("Content-Transfer-Encoding");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentTransferEncoding.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String[] contentLanguage = message.getContentLanguage();
        if (contentLanguage != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentLanguage.name);
            StringBuilder builder = new StringBuilder();
            for (String string : contentLanguage) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String contentId = message.getContentID();
        if (contentId != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.contentId.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(contentId, true, false)));
            metadata.add(sub);
        }
        String disposition = message.getDisposition();
        if (disposition != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.disposition.name);
            sub.setText(StringUtils.removeChevron(StringUtils.unescapeHTML(disposition, true, false)));
            metadata.add(sub);
        }
        headers = message.getHeader("Keywords");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.msgKeywords.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.unescapeHTML(string, true, false));
                builder.append(' ');
            }
            sub.setText(builder.toString());
            metadata.add(sub);
        }
        String messageId = message.getMessageID();
        if (messageId != null) {
            messageId = StringUtils.removeChevron(StringUtils.unescapeHTML(messageId, true, false)).trim();
            if (messageId.length() > 1) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.messageId.name);
                sub.setText(messageId);
                metadata.add(sub);
            }
        }
        headers = message.getHeader("In-Reply-To");
        String inreplyto = null;
        if (headers != null) {
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            inreplyto = builder.toString().trim();
            if (inreplyto.length() > 0) {
                Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.inReplyTo.name);
                sub.setText(inreplyto);
                if (messageId != null && messageId.length() > 1) {
                    String old = filEmls.get(inreplyto);
                    if (old == null) {
                        old = messageId;
                    } else {
                        old += "," + messageId;
                    }
                    filEmls.put(inreplyto, old);
                }
                metadata.add(sub);
            }
        }
        headers = message.getHeader("References");
        if (headers != null) {
            Element sub = XmlDom.factory.createElement(EMAIL_FIELDS.references.name);
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(StringUtils.removeChevron(StringUtils.unescapeHTML(string, true, false)));
                builder.append(' ');
            }
            String[] refs = builder.toString().trim().split(" ");
            for (String string : refs) {
                if (string.length() > 0) {
                    Element ref = XmlDom.factory.createElement(EMAIL_FIELDS.reference.name);
                    ref.setText(string);
                    sub.add(ref);
                }
            }
            metadata.add(sub);
        }
        Element prop = XmlDom.factory.createElement(EMAIL_FIELDS.properties.name);
        headers = message.getHeader("X-Priority");
        if (headers == null) {
            headers = message.getHeader("Priority");
            if (headers != null && headers.length > 0) {
                prop.addAttribute(EMAIL_FIELDS.priority.name, headers[0]);
            }
        } else if (headers != null && headers.length > 0) {
            String imp = headers[0];
            try {
                int Priority = Integer.parseInt(imp);
                switch (Priority) {
                case 5:
                    imp = "LOWEST";
                    break;
                case 4:
                    imp = "LOW";
                    break;
                case 3:
                    imp = "NORMAL";
                    break;
                case 2:
                    imp = "HIGH";
                    break;
                case 1:
                    imp = "HIGHEST";
                    break;
                default:
                    imp = "LEV" + Priority;
                }
            } catch (NumberFormatException e) {
                // ignore since imp will be used as returned
            }
            prop.addAttribute(EMAIL_FIELDS.priority.name, imp);
        }
        headers = message.getHeader("Sensitivity");
        if (headers != null && headers.length > 0) {
            prop.addAttribute(EMAIL_FIELDS.sensitivity.name, headers[0]);
        }
        headers = message.getHeader("X-RDF");
        if (headers != null && headers.length > 0) {
            System.err.println("Found X-RDF");
            StringBuilder builder = new StringBuilder();
            for (String string : headers) {
                builder.append(string);
                builder.append("\n");
            }
            try {
                byte[] decoded = org.apache.commons.codec.binary.Base64.decodeBase64(builder.toString());
                String rdf = new String(decoded);
                Document tempDocument = DocumentHelper.parseText(rdf);
                Element xrdf = prop.addElement("x-rdf");
                xrdf.add(tempDocument.getRootElement());
            } catch (Exception e) {
                System.err.println("Cannot decode X-RDF: " + e.getMessage());
            }
        }
        try {
            File old = argument.currentOutputDir;
            if (config.extractFile) {
                File newOutDir = new File(argument.currentOutputDir, id);
                newOutDir.mkdirs();
                argument.currentOutputDir = newOutDir;
            }
            if (argument.extractKeyword) {
                skey = handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
                ExtractInfo.exportMetadata(keywords, skey, "", config, null);
                if (keywords.hasContent()) {
                    root.add(keywords);
                }
            } else {
                handleMessage(message, metadata, prop, id, argument, config);
                // should have hasAttachment
                if (prop.hasContent()) {
                    metadata.add(prop);
                }
                if (metadata.hasContent()) {
                    root.add(metadata);
                }
            }
            argument.currentOutputDir = old;
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        try {
            message.getInputStream().close();
        } catch (IOException e) {
            System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        }
        root.addAttribute(EMAIL_FIELDS.status.name, "ok");
    } catch (MessagingException e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    } catch (Exception e) {
        System.err.println(StaticValues.LBL.error_error.get() + e.toString());
        e.printStackTrace();
        String status = "Error during identification";
        root.addAttribute(EMAIL_FIELDS.status.name, status);
    }
    argument.currentOutputDir = oldDir;
    return skey;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder./*from w  w w.  j  a v a  2s  .c  om*/
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}