Example usage for javax.mail.internet MimeMessage getReceivedDate

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

Introduction

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

Prototype

@Override
public Date getReceivedDate() throws MessagingException 

Source Link

Document

Returns the Date on this message was received.

Usage

From source file:javamailclient.GmailAPI.java

public static Map getMessageDetails(String messageId) throws IOException, MessagingException {
    Map<String, String> mapDetails = new HashMap<String, String>();
    Message message = service.users().messages().get("me", messageId).setFormat("raw").execute();
    byte[] bytes = Base64.decodeBase64(message.getRaw());

    Properties prop = new Properties();
    Session session = Session.getDefaultInstance(prop, null);

    MimeMessage email = new MimeMessage(session, new ByteArrayInputStream(bytes));
    mapDetails.put("subject", email.getSubject());
    String from = "None";
    if (email.getSender() != null) {
        from = email.getSender().toString();
    }/* w ww .j  av  a2s.co  m*/
    mapDetails.put("from", from);
    String date = "Unknown";
    if (email.getReceivedDate() != null) {
        date = email.getReceivedDate().toString();
    }
    mapDetails.put("receiveddate", date);
    date = "Unknown";
    if (email.getSentDate() != null) {
        date = email.getSentDate().toString();
    }
    mapDetails.put("senddate", date);
    mapDetails.put("body", getMessageBody(email));
    return mapDetails;
}

From source file:io.lavagna.service.MailTicketService.java

public void checkNew() {
    List<ProjectMailTicketConfig> entries = mailTicketRepository.findAll();

    for (ProjectMailTicketConfig entry : entries) {
        if (entry.getEntries().size() == 0 || !entry.getEnabled()) {
            continue;
        }//from w w  w  .ja va  2  s.com

        MailReceiver receiver = entry.getConfig().getInboundProtocol().startsWith("pop3")
                ? getPop3MailReceiver(entry.getConfig())
                : getImapMailReceiver(entry.getConfig());

        try {
            Date updateLastChecked = entry.getLastChecked();

            Object[] messages = receiver.receive();
            LOG.debug("found {} messages", messages.length);

            for (int i = 0; i < messages.length; i++) {
                MimeMessage message = (MimeMessage) messages[i];
                if (!message.getReceivedDate().after(entry.getLastChecked())) {
                    continue;
                } else {
                    updateLastChecked = message.getReceivedDate().after(updateLastChecked)
                            ? message.getReceivedDate()
                            : updateLastChecked;
                }

                String deliveredTo = getDeliveredTo(message);

                for (ProjectMailTicket ticketConfig : entry.getEntries()) {
                    if (ticketConfig.getEnabled() && ticketConfig.getAlias().equals(deliveredTo)) {
                        String from = getFrom(message);
                        String name = getName(message);
                        Matcher m = CARD_SHORT_NAME.matcher(message.getSubject());

                        if (!m.find() || (m.find() && !cardService.existCardWith(m.group("shortname"),
                                Integer.parseInt(m.group("sequence"))))) {
                            try {
                                ImmutablePair<Card, User> cardAndUser = createCard(message.getSubject(),
                                        getTextFromMessage(message), from, ticketConfig.getColumnId());

                                notify(cardAndUser.getLeft(), entry, ticketConfig, cardAndUser.getRight(), from,
                                        name);
                            } catch (IOException | MessagingException e) {
                                LOG.error("failed to parse message body", e);
                            }
                        }
                    }
                }
            }

            mailTicketRepository.updateLastChecked(entry.getId(), updateLastChecked);
        } catch (MessagingException e) {
            LOG.error("could not retrieve messages for ticket mail config id: {}", entry.getId());
        }
    }
}

From source file:org.ofbiz.common.CommonServices.java

public static Map<String, Object> mcaTest(DispatchContext dctx, Map<String, ?> context) {
    MimeMessageWrapper wrapper = (MimeMessageWrapper) context.get("messageWrapper");
    MimeMessage message = wrapper.getMessage();
    try {/* w  ww.j  a  v a 2s  .c  o  m*/
        if (message.getAllRecipients() != null) {
            Debug.log("To: " + UtilMisc.toListArray(message.getAllRecipients()), module);
        }
        if (message.getFrom() != null) {
            Debug.log("From: " + UtilMisc.toListArray(message.getFrom()), module);
        }
        Debug.log("Subject: " + message.getSubject(), module);
        if (message.getSentDate() != null) {
            Debug.log("Sent: " + message.getSentDate().toString(), module);
        }
        if (message.getReceivedDate() != null) {
            Debug.log("Received: " + message.getReceivedDate().toString(), module);
        }
    } catch (Exception e) {
        Debug.logError(e, module);
    }
    return ServiceUtil.returnSuccess();
}

From source file:com.opensearchserver.extractor.parser.Eml.java

@Override
protected void parseContent(InputStream inputStream, String extension, String mimeType) throws Exception {
    Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);

    MimeMessage mimeMessage = new MimeMessage(session, inputStream);
    MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();

    ParserDocument document = getNewParserDocument();
    String from = mimeMessageParser.getFrom();
    if (from != null)
        document.add(FROM, from.toString());
    for (Address address : mimeMessageParser.getTo())
        document.add(RECIPIENT_TO, address.toString());
    for (Address address : mimeMessageParser.getCc())
        document.add(RECIPIENT_CC, address.toString());
    for (Address address : mimeMessageParser.getBcc())
        document.add(RECIPIENT_BCC, address.toString());
    document.add(SUBJECT, mimeMessageParser.getSubject());
    document.add(HTML_CONTENT, mimeMessageParser.getHtmlContent());
    document.add(PLAIN_CONTENT, mimeMessageParser.getPlainContent());
    document.add(SENT_DATE, mimeMessage.getSentDate());
    document.add(RECEIVED_DATE, mimeMessage.getReceivedDate());

    for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
        document.add(ATTACHMENT_NAME, dataSource.getName());
        document.add(ATTACHMENT_TYPE, dataSource.getContentType());
        // TODO Extract content from attachmend
        // if (parserSelector != null) {
        // Parser attachParser = parserSelector.parseStream(
        // getSourceDocument(), dataSource.getName(),
        // dataSource.getContentType(), null,
        // dataSource.getInputStream(), null, null, null);
        // if (attachParser != null) {
        // List<ParserResultItem> parserResults = attachParser
        // .getParserResults();
        // if (parserResults != null)
        // for (ParserResultItem parserResult : parserResults)
        // result.addField(
        // ParserFieldEnum.email_attachment_content,
        // parserResult);
        // }//from  w w  w.j ava2 s  . c  o  m
        // }
    }
    if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
        document.add(LANG_DETECTION, languageDetection(document, PLAIN_CONTENT, 10000));
    else
        document.add(LANG_DETECTION, languageDetection(document, HTML_CONTENT, 10000));
}

From source file:com.qwazr.library.email.EmlParser.java

@Override
public void parseContent(final MultivaluedMap<String, String> parameters, final InputStream inputStream,
        final String extension, final String mimeType, final ParserResultBuilder resultBuilder)
        throws Exception {
    final Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);

    resultBuilder.metas().set(MIME_TYPE, findMimeType(extension, mimeType, this::findMimeTypeUsingDefault));

    final MimeMessage mimeMessage = new MimeMessage(session, inputStream);
    final MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();

    ParserFieldsBuilder document = resultBuilder.newDocument();
    final String from = mimeMessageParser.getFrom();
    if (from != null)
        document.add(FROM, from);//from  ww w .j  a  va2s . c  o m
    for (Address address : mimeMessageParser.getTo())
        document.add(RECIPIENT_TO, address.toString());
    for (Address address : mimeMessageParser.getCc())
        document.add(RECIPIENT_CC, address.toString());
    for (Address address : mimeMessageParser.getBcc())
        document.add(RECIPIENT_BCC, address.toString());
    document.add(SUBJECT, mimeMessageParser.getSubject());
    document.add(HTML_CONTENT, mimeMessageParser.getHtmlContent());
    document.add(PLAIN_CONTENT, mimeMessageParser.getPlainContent());
    document.add(SENT_DATE, mimeMessage.getSentDate());
    document.add(RECEIVED_DATE, mimeMessage.getReceivedDate());

    for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
        document.add(ATTACHMENT_NAME, dataSource.getName());
        document.add(ATTACHMENT_TYPE, dataSource.getContentType());
        // TODO Extract content from attachmend
        // if (parserSelector != null) {
        // Parser attachParser = parserSelector.parseStream(
        // getSourceDocument(), dataSource.getName(),
        // dataSource.getContentType(), null,
        // dataSource.getInputStream(), null, null, null);
        // if (attachParser != null) {
        // List<ParserResultItem> parserResults = attachParser
        // .getParserResults();
        // if (parserResults != null)
        // for (ParserResultItem parserResult : parserResults)
        // result.addField(
        // ParserFieldEnum.email_attachment_content,
        // parserResult);
        // }
        // }
    }
    if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
        document.add(LANG_DETECTION, languageDetection(document, PLAIN_CONTENT, 10000));
    else
        document.add(LANG_DETECTION, languageDetection(document, HTML_CONTENT, 10000));
}

From source file:com.jaeksoft.searchlib.parser.EmlParser.java

@Override
protected void parseContent(StreamLimiter streamLimiter, LanguageEnum lang)
        throws IOException, SearchLibException {
    Session session = Session.getDefaultInstance(JAVAMAIL_PROPS);
    try {//w  ww .j a v a2s.c  o  m

        MimeMessage mimeMessage = new MimeMessage(session, streamLimiter.getNewInputStream());
        MimeMessageParser mimeMessageParser = new MimeMessageParser(mimeMessage).parse();

        ParserResultItem result = getNewParserResultItem();
        String from = mimeMessageParser.getFrom();
        if (from != null)
            result.addField(ParserFieldEnum.email_display_from, from.toString());
        for (Address address : mimeMessageParser.getTo())
            result.addField(ParserFieldEnum.email_display_to, address.toString());
        for (Address address : mimeMessageParser.getCc())
            result.addField(ParserFieldEnum.email_display_cc, address.toString());
        for (Address address : mimeMessageParser.getBcc())
            result.addField(ParserFieldEnum.email_display_bcc, address.toString());
        result.addField(ParserFieldEnum.subject, mimeMessageParser.getSubject());
        result.addField(ParserFieldEnum.htmlSource, mimeMessageParser.getHtmlContent());
        result.addField(ParserFieldEnum.content, mimeMessageParser.getPlainContent());
        result.addField(ParserFieldEnum.email_sent_date, mimeMessage.getSentDate());
        result.addField(ParserFieldEnum.email_received_date, mimeMessage.getReceivedDate());

        for (DataSource dataSource : mimeMessageParser.getAttachmentList()) {
            result.addField(ParserFieldEnum.email_attachment_name, dataSource.getName());
            result.addField(ParserFieldEnum.email_attachment_type, dataSource.getContentType());
            if (parserSelector == null)
                continue;
            Parser attachParser = parserSelector.parseStream(getSourceDocument(), dataSource.getName(),
                    dataSource.getContentType(), null, dataSource.getInputStream(), null, null, null);
            if (attachParser == null)
                continue;
            List<ParserResultItem> parserResults = attachParser.getParserResults();
            if (parserResults != null)
                for (ParserResultItem parserResult : parserResults)
                    result.addField(ParserFieldEnum.email_attachment_content, parserResult);
        }
        if (StringUtils.isEmpty(mimeMessageParser.getHtmlContent()))
            result.langDetection(10000, ParserFieldEnum.content);
        else
            result.langDetection(10000, ParserFieldEnum.htmlSource);
    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:com.duroty.service.Mailet.java

/**
 * DOCUMENT ME!//ww  w  .  jav a 2s  . c  om
 *
 * @param hfactory DOCUMENT ME!
 * @param username DOCUMENT ME!
 * @param mime DOCUMENT ME!
 */
private void parseContacts(Session hsession, Users user, MimeMessage mime, String box) {
    try {
        Address[] addresses = null;

        Date sentDate = null;
        Date receivedDate = null;

        if (box.equals("SENT")) {
            addresses = mime.getAllRecipients();
            sentDate = mime.getSentDate();

            if (sentDate == null) {
                sentDate = new Date();
            }
        } else {
            addresses = mime.getFrom();
            receivedDate = mime.getReceivedDate();

            if (receivedDate == null) {
                receivedDate = new Date();
            }
        }

        if ((addresses != null) && (addresses.length > 0)) {
            String name = null;
            String email = null;

            for (int i = 0; i < addresses.length; i++) {
                if (addresses[i] instanceof InternetAddress) {
                    InternetAddress xinet = (InternetAddress) addresses[i];

                    name = xinet.getPersonal();

                    if ((name != null) && (name.length() > 49)) {
                        name = name.substring(0, 49);
                    }

                    email = xinet.getAddress();
                } else {
                    email = addresses[i].toString();
                }

                Criteria crit1 = hsession.createCriteria(Contact.class);
                crit1.add(Restrictions.eq("users", user));
                crit1.add(Restrictions.eq("conEmail", email));

                Contact contact = (Contact) crit1.uniqueResult();

                if (contact != null) {
                    if (receivedDate != null) {
                        contact.setConReceivedDate(receivedDate);
                    }

                    if (sentDate != null) {
                        contact.setConSentDate(sentDate);
                    }

                    int freq = contact.getConCount();

                    contact.setConCount(freq + 1);

                    if (!StringUtils.isBlank(name)) {
                        name = name.replaceAll(",", " ");
                        name = name.replaceAll(";", " ");
                        contact.setConName(name);
                    }

                    hsession.update(contact);
                } else {
                    contact = new Contact();
                    contact.setConEmail(email);
                    contact.setConName(name);
                    contact.setConReceivedDate(receivedDate);
                    contact.setConSentDate(sentDate);
                    contact.setConCount(new Integer(1));
                    contact.setUsers(user);

                    hsession.save(contact);
                }

                hsession.flush();

                try {
                    if ((contact.getConSentDate() != null) && (contact.getConReceivedDate() != null)) {
                        Criteria crit2 = hsession.createCriteria(Identity.class);
                        crit2.add(Restrictions.eq("ideEmail", email));
                        crit2.add(Restrictions.eq("ideActive", new Boolean(true)));

                        List list = crit2.list();

                        if (list != null) {
                            Iterator scroll = list.iterator();

                            while (scroll.hasNext()) {
                                Identity identity = (Identity) scroll.next();
                                Users buddy = identity.getUsers();

                                if ((buddy != null) && (user.getUseIdint() != buddy.getUseIdint())) {
                                    Criteria auxCrit = hsession.createCriteria(BuddyList.class);
                                    auxCrit.add(Restrictions.eq("usersByBuliOwnerIdint", user));
                                    auxCrit.add(Restrictions.eq("usersByBuliBuddyIdint", buddy));

                                    BuddyList buddyList = (BuddyList) auxCrit.uniqueResult();

                                    if (buddyList != null) {
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        hsession.update(buddyList);
                                    } else {
                                        buddyList = new BuddyList();
                                        buddyList.setBuliActive(true);
                                        buddyList.setBuliLastDate(new Date());
                                        buddyList.setUsersByBuliBuddyIdint(buddy);
                                        buddyList.setUsersByBuliOwnerIdint(user);
                                        hsession.save(buddyList);
                                    }
                                }
                            }
                        }

                        hsession.flush();
                    }
                } catch (Exception e) {
                }
            }
        }
    } catch (Exception e) {
    } finally {
    }
}

From source file:edu.stanford.muse.email.EmailFetcherStats.java

/**
 * Key method for importing email: converts a javamail obj. to our own data structure (EmailDocument)
 *//*from ww  w .ja  v  a  2 s .  c  om*/
//public EmailDocument convertToEmailDocument(MimeMessage m, int num, String url) throws MessagingException, IOException
private EmailDocument convertToEmailDocument(MimeMessage m, String id) throws MessagingException, IOException {
    // get the date.
    // prevDate is a hack for the cases where the message is lacking an explicit Date: header. e.g.
    //      From hangal Sun Jun 10 13:46:46 2001
    //      To: ewatkins@stanford.edu
    //      Subject: Re: return value bugs
    // though the date is on the From separator line, the mbox provider fails to parse it and provide it to us.
    // so as a hack, we will assign such messages the same date as the previous one this fetcher has seen! ;-)
    // update: having the exact same date causes the message to be considered a duplicate, so just increment
    // the timestamp it by 1 millisecond!
    // a better fix would be to improve the parsing in the provider

    boolean hackyDate = false;
    Date d = m.getSentDate();
    if (d == null)
        d = m.getReceivedDate();
    if (d == null) {
        if (prevDate != null) {
            long newTime = prevDate.getTime() + 1L; // added +1 so that this email is not considered the same object as the prev. one if they are in the same thread
            d = new Date(newTime);
            dataErrors.add("No date for message id:" + id + ": " + EmailUtils.formatMessageHeader(m)
                    + " assigned approximate date");
        } else {
            d = INVALID_DATE; // wrong, but what can we do... :-(
            dataErrors.add("No date for message id:" + id + ": " + EmailUtils.formatMessageHeader(m)
                    + " assigned deliberately invalid date");
        }
        hackyDate = true;
    } else {
        Calendar c = new GregorianCalendar();
        c.setTime(d);
        int yy = c.get(Calendar.YEAR);
        if (yy < 1960 || yy > 2020) {
            dataErrors.add("Probably bad date: " + Util.formatDate(c) + " message: "
                    + EmailUtils.formatMessageHeader(m));
            hackyDate = true;
        }
    }

    if (hackyDate && prevDate != null) {
        long newTime = prevDate.getTime() + 1L; // added +1 so that this email is not considered the same object as the prev. one if they are in the same thread
        d = new Date(newTime);
        Util.ASSERT(!d.equals(prevDate));
    }

    Calendar c = new GregorianCalendar();
    c.setTime(d != null ? d : new Date());

    prevDate = d;

    Address to[] = null, cc[] = null, bcc[] = null;
    Address[] from = null;
    try {
        //          allrecip = m.getAllRecipients(); // turns out to be too expensive because it looks for newsgroup headers for imap
        // assemble to, cc, bcc into a list and copy it into allrecip
        List<Address> list = new ArrayList<Address>();
        from = m.getFrom();
        to = m.getRecipients(Message.RecipientType.TO);
        if (to != null)
            list.addAll(Arrays.asList(to));
        cc = m.getRecipients(Message.RecipientType.CC);
        if (cc != null)
            list.addAll(Arrays.asList(cc));
        bcc = m.getRecipients(Message.RecipientType.BCC);
        if (bcc != null)
            list.addAll(Arrays.asList(bcc));

        // intern the strings in these addresses to save memory cos they are repeated often in a large archive
        internAddressList(from);
        internAddressList(to);
        internAddressList(cc);
        internAddressList(bcc);
    } catch (AddressException ae) {
        String s = "Bad address in folder " + folder_name() + " message id" + id + " " + ae;
        dataErrors.add(s);
    }

    // take a deep breath. This object is going to live longer than most of us.
    EmailDocument ed = new EmailDocument(id, email_source(), folder_name(), to, cc, bcc, from, m.getSubject(),
            m.getMessageID(), c.getTime());

    String[] headers = m.getHeader("List-Post");
    if (headers != null && headers.length > 0) {
        // trim the headers because they usually look like: "<mailto:prpl-devel@lists.stanford.edu>"
        ed.sentToMailingLists = new String[headers.length];
        int i = 0;
        for (String header : headers) {
            header = header.trim();
            header = header.toLowerCase();

            if (header.startsWith("<") && header.endsWith(">"))
                header = header.substring(1, header.length() - 1);
            if (header.startsWith("mailto:") && !"mailto:".equals(header)) // defensive check in case header == "mailto:"
                header = header.substring(("mailto:").length());
            ed.sentToMailingLists[i++] = header;
        }
    }
    if (hackyDate) {
        String s = "Guessed date " + Util.formatDate(c) + " for message id: " + id + ": " + ed.getHeader();
        dataErrors.add(s);
        ed.hackyDate = true;
    }

    // check if the message has attachments.
    // if it does and we're not downloading attachments, then we mark the ed as such.
    // otherwise we had a problem where a message header (and maybe text) was downloaded but without attachments in one run
    // but in a subsequent run where attachments were needed, we thought the message was already cached and there was no
    // need to recompute it, leaving the attachments field in this ed incorrect.
    List<String> attachmentNames = getAttachmentNames(m, m);
    if (!Util.nullOrEmpty(attachmentNames)) {
        ed.attachmentsYetToBeDownloaded = true; // will set it to false later if attachments really were downloaded (not sure why)
        //         log.info ("added " + attachmentNames.size() + " attachments to message: " + ed);
    }
    return ed;
}

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

public static String extractInfoMessage(MimeMessage message, Element root, VitamArgument argument,
        ConfigLoader config) {//from w  w w .j a  v  a  2 s.co  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:org.alfresco.repo.invitation.AbstractInvitationServiceImplTest.java

/**
 * Test nominated user - new user/*from w w  w . j a  va 2 s . c  o  m*/
 * 
 * @throws Exception
 */
public void testNominatedInvitationNewUser() throws Exception {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.SECOND, -1);
    Date startDate = calendar.getTime();

    String inviteeFirstName = PERSON_FIRSTNAME;
    String inviteeLastName = PERSON_LASTNAME;
    String inviteeEmail = "123@alfrescotesting.com";
    String inviteeUserName = null;
    Invitation.ResourceType resourceType = Invitation.ResourceType.WEB_SITE;
    String resourceName = SITE_SHORT_NAME_INVITE;
    String inviteeRole = SiteModel.SITE_COLLABORATOR;
    String serverPath = "wibble";
    String acceptUrl = "froob";
    String rejectUrl = "marshmallow";

    this.authenticationComponent.setCurrentUser(USER_MANAGER);

    NominatedInvitation nominatedInvitation = invitationService.inviteNominated(inviteeFirstName,
            inviteeLastName, inviteeEmail, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
            rejectUrl);

    assertNotNull("nominated invitation is null", nominatedInvitation);
    String inviteId = nominatedInvitation.getInviteId();
    assertEquals("first name wrong", inviteeFirstName, nominatedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, nominatedInvitation.getInviteeLastName());
    assertEquals("email name wrong", inviteeEmail, nominatedInvitation.getInviteeEmail());

    // Generated User Name should be returned
    inviteeUserName = nominatedInvitation.getInviteeUserName();
    assertNotNull("generated user name is null", inviteeUserName);
    // sentInviteDate should be set to today
    {
        Date sentDate = nominatedInvitation.getSentInviteDate();
        assertTrue("sentDate wrong - too early. Start Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.after(startDate));
        assertTrue("sentDate wrong - too lateStart Date: " + startDate + "\nSent Date: " + sentDate,
                sentDate.before(new Date(new Date().getTime() + 1)));
    }

    assertEquals("resource type name wrong", resourceType, nominatedInvitation.getResourceType());
    assertEquals("resource name wrong", resourceName, nominatedInvitation.getResourceName());
    assertEquals("role  name wrong", inviteeRole, nominatedInvitation.getRoleName());
    assertEquals("server path wrong", serverPath, nominatedInvitation.getServerPath());
    assertEquals("accept URL wrong", acceptUrl, nominatedInvitation.getAcceptUrl());
    assertEquals("reject URL wrong", rejectUrl, nominatedInvitation.getRejectUrl());

    /**
     * Now we have an invitation get it and check the details have been
     * returned correctly.
     */
    {
        NominatedInvitation invitation = (NominatedInvitation) invitationService.getInvitation(inviteId);

        assertNotNull("invitation is null", invitation);
        assertEquals("invite id wrong", inviteId, invitation.getInviteId());
        assertEquals("first name wrong", inviteeFirstName, invitation.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, invitation.getInviteeLastName());
        assertEquals("user name wrong", inviteeUserName, invitation.getInviteeUserName());
        assertEquals("resource type name wrong", resourceType, invitation.getResourceType());
        assertEquals("resource name wrong", resourceName, invitation.getResourceName());
        assertEquals("role  name wrong", inviteeRole, invitation.getRoleName());
        assertEquals("server path wrong", serverPath, invitation.getServerPath());
        assertEquals("accept URL wrong", acceptUrl, invitation.getAcceptUrl());
        assertEquals("reject URL wrong", rejectUrl, invitation.getRejectUrl());

        Date sentDate = invitation.getSentInviteDate();
        // sentInviteDate should be set to today
        assertTrue("sentDate wrong too early", sentDate.after(startDate));
        assertTrue("sentDate wrong - too late", sentDate.before(new Date(new Date().getTime() + 1)));
    }

    /**
     * Check the email itself, and check it
     *  is as we would expect it to be
     */
    {
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(inviteeEmail, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(USER_MANAGER + "@alfrescotesting.com", msg.getFrom()[0].toString());

        // Hasn't been sent, so no sent or received date
        assertNull("Not been sent yet", msg.getSentDate());
        assertNull("Not been sent yet", msg.getReceivedDate());

        // TODO - check some more details of the email
        assertTrue((msg.getSubject().indexOf("You have been invited to join the") != -1));
    }

    /**
     * Search for the new invitation
     */
    List<Invitation> invitations = invitationService.listPendingInvitationsForResource(resourceType,
            resourceName);
    assertTrue("invitations is empty", !invitations.isEmpty());

    NominatedInvitation firstInvite = (NominatedInvitation) invitations.get(0);
    assertEquals("invite id wrong", inviteId, firstInvite.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, firstInvite.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, firstInvite.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, firstInvite.getInviteeUserName());

    /**
     * Now accept the invitation
     */
    NominatedInvitation acceptedInvitation = (NominatedInvitation) invitationService
            .accept(firstInvite.getInviteId(), firstInvite.getTicket());
    assertEquals("invite id wrong", firstInvite.getInviteId(), acceptedInvitation.getInviteId());
    assertEquals("first name wrong", inviteeFirstName, acceptedInvitation.getInviteeFirstName());
    assertEquals("last name wrong", inviteeLastName, acceptedInvitation.getInviteeLastName());
    assertEquals("user name wrong", inviteeUserName, acceptedInvitation.getInviteeUserName());

    List<Invitation> it4 = invitationService.listPendingInvitationsForResource(resourceType, resourceName);
    assertTrue("invitations is not empty", it4.isEmpty());

    /**
     * Now get the invitation that we accepted
     */
    NominatedInvitation acceptedInvitation2 = (NominatedInvitation) invitationService
            .getInvitation(firstInvite.getInviteId());
    assertNotNull("get after accept does not return", acceptedInvitation2);

    /**
     * Now verify access control list
     */
    String roleName = siteService.getMembersRole(resourceName, inviteeUserName);
    assertEquals("role name wrong", roleName, inviteeRole);
    siteService.removeMembership(resourceName, inviteeUserName);

    /**
     * Check that system generated invitations can work as well
     */
    {
        Field faf = mailService.getClass().getDeclaredField("fromAddress");
        faf.setAccessible(true);
        String defaultFromAddress = (String) ReflectionUtils.getField(faf, mailService);

        AuthenticationUtil.setFullyAuthenticatedUser(USER_NOEMAIL);

        // Check invitiation
        NominatedInvitation nominatedInvitation2 = invitationService.inviteNominated(inviteeFirstName,
                inviteeLastName, USER_TWO_EMAIL, resourceType, resourceName, inviteeRole, serverPath, acceptUrl,
                rejectUrl);

        assertNotNull("nominated invitation is null", nominatedInvitation2);
        inviteId = nominatedInvitation.getInviteId();
        assertEquals("first name wrong", inviteeFirstName, nominatedInvitation2.getInviteeFirstName());
        assertEquals("last name wrong", inviteeLastName, nominatedInvitation2.getInviteeLastName());
        assertEquals("email name wrong", USER_TWO_EMAIL, nominatedInvitation2.getInviteeEmail());

        // Check the email
        MimeMessage msg = mailService.retrieveLastTestMessage();

        assertEquals(1, msg.getAllRecipients().length);
        assertEquals(USER_TWO_EMAIL, msg.getAllRecipients()[0].toString());

        assertEquals(1, msg.getFrom().length);
        assertEquals(defaultFromAddress, msg.getFrom()[0].toString());
    }
}