Example usage for javax.mail Message isExpunged

List of usage examples for javax.mail Message isExpunged

Introduction

In this page you can find the example usage for javax.mail Message isExpunged.

Prototype

public boolean isExpunged() 

Source Link

Document

Checks whether this message is expunged.

Usage

From source file:com.cubusmail.server.mail.util.MessageComparator.java

public int compare(Message msg1, Message msg2) {

    int result = 0;

    if (msg1.isExpunged() || msg2.isExpunged()) {
        return result;
    }/*from   ww  w .ja  va 2s.  c o  m*/

    try {
        if (MessageListFields.SUBJECT == this.field) {
            if (msg1.getSubject() != null && msg2.getSubject() != null) {
                result = msg1.getSubject().compareToIgnoreCase(msg2.getSubject());
            } else {
                result = -1;
            }
        } else if (MessageListFields.FROM == this.field) {
            String fromString1 = MessageUtils.getMailAdressString(msg1.getFrom(), AddressStringType.PERSONAL);
            String fromString2 = MessageUtils.getMailAdressString(msg2.getFrom(), AddressStringType.PERSONAL);
            if (fromString1 != null && fromString2 != null) {
                result = fromString1.compareToIgnoreCase(fromString2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SEND_DATE == this.field) {
            Date date1 = msg1.getSentDate();
            Date date2 = msg2.getSentDate();
            if (date1 != null && date2 != null) {
                result = date1.compareTo(date2);
            } else {
                result = -1;
            }
        } else if (MessageListFields.SIZE == this.field) {
            int size1 = msg1.getSize();
            int size2 = msg2.getSize();
            result = Integer.valueOf(size1).compareTo(Integer.valueOf(size2));

        }
    } catch (MessagingException e) {
        log.warn(e.getMessage(), e);
    }

    if (!this.ascending) {
        result = result * (-1);
    }

    return result;
}

From source file:com.funambol.email.items.manager.ImapEntityManager.java

/**
 * deletes an email//from w w w  .j a v a  2  s.co  m
 *
 * @param parentId String
 * @param mailId String
 * @param GUID String
 * @param serverItems map with all in the Mail Server CrcSyncItemsInfo
 * @param source_uri  String
 * @param principalId long
 * @throws EntityException
 */
public void removeEmail(String parentId, String mailId, String GUID, Map serverItems, String username,
        String source_uri, long principalId) throws EntityException {

    String fullpath = null;

    try {
        fullpath = this.ied.getFullPathFromFID(parentId, source_uri, principalId, username);
    } catch (EntityException e) {
        throw new EntityException(e);
    }

    if (log.isTraceEnabled()) {
        log.trace("remove item in FID: " + fullpath + " with FMID: " + mailId);
    }

    if (fullpath != null) {
        if (parentId.equalsIgnoreCase(Def.FOLDER_INBOX_ID)) {
            try {

                // INBOX

                timeStart = System.currentTimeMillis();

                IMAPFolder inbox = this.imsw.folderInboxOpened;
                long uid = Long.parseLong(mailId);

                if (!inbox.isOpen()) {
                    inbox.open(javax.mail.Folder.READ_WRITE);
                }

                Message message = inbox.getMessageByUID(uid);
                IMAPFolder trashFolder = this.imsw.getTrashFolder();

                //
                // If the trash folder does not exists, then create it.
                //
                if (!trashFolder.exists()) {

                    if (log.isTraceEnabled()) {
                        log.trace("Trash folder does not exist. Creating Trash folder with path "
                                + trashFolder.getFullName());
                    }

                    if (trashFolder.create(Folder.HOLDS_MESSAGES)) {
                        trashFolder.open(Folder.READ_WRITE);
                    }
                }

                if (message != null) {
                    if (message.isExpunged()) {
                        //
                        // GMail mail server sometimes says an email is expunged
                        // even if it has not been previously deleted.
                        //
                        // Workaround:
                        //
                        // - such behaviour seems to appear after the first time
                        //   IMAPFolder.copyMessage method is executed on an open 
                        //   folder.
                        //
                        //   More precisely: the first time method is executed,
                        //   the given message is moved correctly; each of 
                        //   the subsequent execution could work correctly
                        //   or not.
                        // 
                        // - So: reopen the inbox folder (as: "nothing has
                        //   happened"), extract the message, call copyMessage
                        //   with that message.
                        //

                        if (inbox.isOpen()) {
                            //
                            // close folder expunging all emails to be expunged 
                            // in order to reset state of each email
                            //
                            inbox.close(true);
                            inbox.open(Folder.READ_WRITE);
                        }

                        message = ((IMAPFolder) inbox).getMessageByUID(uid);
                    }

                    //
                    // Following check: message != null is needed in the case
                    // message was expunged (see above).
                    //
                    if (message != null) {

                        // if TRASH folder exists, then copy email to TRASH folder
                        if (trashFolder.exists()) {
                            this.ied.copyEmail(inbox, trashFolder, uid);
                        }

                        //
                        // - With some mail servers the copyEmail method
                        //   copies the original message in the destination
                        //   folder and leaves the original one in the source
                        //   one.
                        // - Other mail servers move the message from the
                        //   source folder to the destination folder; thus
                        //   the original message cannot be deleted from the
                        //   source folder, since it has been already deleted. 
                        //
                        // For example: consider the Gmail mail server; when
                        // moving an email from the INBOX folder to the default
                        // trash folder, the copy operation will automatically 
                        // delete and expunge the original message from the
                        // source folder; note also that this behavior does
                        // not happen when destination folder is not the default
                        // trash folder).
                        //
                        if (!message.isExpunged()) {
                            // remove email from inbox folder
                            this.ied.removeEmail(inbox, uid);
                        }
                    }
                }

                // remove from Cache Inbox Table
                this.ied.removeEmailInDB(username, Def.PROTOCOL_IMAP, GUID);

                // remove serverItemsList
                this.ied.removeItemInServerItems(GUID, serverItems);

                timeStop = System.currentTimeMillis();
                if (log.isTraceEnabled()) {
                    log.trace("removeItem Execution Time: " + (timeStop - timeStart) + " ms");
                }
            } catch (MessagingException e) {
                throw new EntityException(e);
            } catch (EntityException e) {
                throw new EntityException(e);
            } catch (EmailAccessException e) {
                throw new EntityException(e);
            }
        } else {

            // SENT - OUTBOX - DRAFTS - TRASH

            IMAPFolder f = null;

            EntityException finalExc = null;

            try {

                timeStart = System.currentTimeMillis();
                // rest of the folders
                f = (IMAPFolder) this.imsw.getMailDefaultFolder().getFolder(fullpath);

                if (f.exists()) {

                    if (!f.isOpen()) {
                        f.open(Folder.READ_WRITE);
                    }

                    // remove email from mail server
                    this.ied.removeEmail(f, Long.parseLong(mailId));

                    // remove serverItemsList
                    this.ied.removeItemInServerItems(GUID, serverItems);

                }

            } catch (MessagingException me) {
                throw new EntityException(me);
            } catch (EntityException e) {
                throw new EntityException(e);
            } finally {
                if (f != null) {
                    try {
                        if (f.isOpen()) {
                            f.close(true);
                            timeStop = System.currentTimeMillis();
                            if (log.isTraceEnabled()) {
                                log.trace("removeItem Execution Time: " + (timeStop - timeStart) + " ms");
                            }
                        }
                    } catch (MessagingException me) {
                        throw new EntityException(me);
                    }
                }
            }
        }
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processGetForwardMessage(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {//from  ww w  . ja v a2 s .co  m
    MailAccount account = getAccount(request);
    UserProfile profile = environment.getProfile();
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pnewmsgid = request.getParameter("newmsgid");
    String pattached = request.getParameter("attached");
    boolean attached = (pattached != null && pattached.equals("1"));
    long newmsgid = Long.parseLong(pnewmsgid);
    String sout = null;
    try {
        String format = us.getFormat();
        boolean isHtml = format.equals("html");
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        Message m = mcache.getMessage(Long.parseLong(puidmessage));
        if (m.isExpunged()) {
            throw new MessagingException("Message " + puidmessage + " expunged");
        }
        SimpleMessage smsg = getForwardMsg(newmsgid, m, isHtml, lookupResource(MailLocaleKey.MSG_FROMTITLE),
                lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE),
                lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE),
                attached);

        sout = "{\n result: true,";
        Identity ident = mprofile.getIdentity(pfoldername);
        String forwardedfrom = smsg.getForwardedFrom();
        sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',";
        if (forwardedfrom != null) {
            sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',";
        }
        String subject = smsg.getSubject();
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";

        String html = smsg.getContent();
        String text = smsg.getTextContent();
        if (!attached) {
            HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
            boolean first = true;
            sout += " attachments: [\n";

            for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
                try {
                    Part part = maildata.getAttachmentPart(i);
                    String filename = getPartName(part);
                    if (!part.isMimeType("message/*")) {
                        String cids[] = part.getHeader("Content-ID");
                        String cid = null;
                        //String cid=filename;
                        if (cids != null && cids[0] != null) {
                            cid = cids[0];
                            if (cid.startsWith("<"))
                                cid = cid.substring(1);
                            if (cid.endsWith(">"))
                                cid = cid.substring(0, cid.length() - 1);
                        }

                        if (filename == null)
                            filename = cid;
                        String mime = MailUtils.getMediaTypeFromHeader(part.getContentType());
                        UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime,
                                part.getInputStream());
                        boolean inline = false;
                        if (part.getDisposition() != null) {
                            inline = part.getDisposition().equalsIgnoreCase(Part.INLINE);
                        }
                        if (!first) {
                            sout += ",\n";
                        }
                        sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId())
                                + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', "
                                + " cid: "
                                + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'")
                                + ", " + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + ", "
                                + " editable: " + isFileEditableInDocEditor(filename) + " " + " }";
                        first = false;
                        //TODO: change this weird matching of cids2urls!
                        html = StringUtils.replace(html, "cid:" + cid,
                                "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID
                                        + "&action=PreviewAttachment&nowriter=true&uploadId="
                                        + upfile.getUploadId() + "&cid=" + cid);
                    }
                } catch (Exception exc) {
                    Service.logger.error("Exception", exc);
                }
            }

            sout += "\n ],\n";
            //String surl = "service-request?service="+SERVICE_ID+"&action=PreviewAttachment&nowriter=true&newmsgid=" + newmsgid + "&cid=";
            //html = replaceCidUrls(html, maildata, surl);
        } else {
            String filename = m.getSubject() + ".eml";
            UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, "message/rfc822",
                    ((IMAPMessage) m).getMimeStream());
            sout += " attachments: [\n";
            sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', "
                    + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: null, "
                    + " inline: false, " + " fileSize: " + upfile.getSize() + ", " + " editable: "
                    + isFileEditableInDocEditor(filename) + " " + " }";
            sout += "\n ],\n";
        }
        sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        if (isHtml) {
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n";
        } else {
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n";
        }
        sout += " format:'" + format + "'\n";
        sout += "\n}";
        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
        out.println(sout);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processGetReplyMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    UserProfile profile = environment.getProfile();
    //WebTopApp webtopapp=environment.getWebTopApp();
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String preplyall = request.getParameter("replyall");
    boolean replyAll = false;
    if (preplyall != null && preplyall.equals("1")) {
        replyAll = true;//from   w  w  w.  j  a v a  2 s  . c o m
    }
    String sout = null;
    try {
        String format = us.getFormat();
        boolean isHtml = format.equals("html");
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        Message m = mcache.getMessage(Long.parseLong(puidmessage));
        if (m.isExpunged()) {
            throw new MessagingException("Message " + puidmessage + " expunged");
        }
        int newmsgid = getNewMessageID();
        SimpleMessage smsg = getReplyMsg(getNewMessageID(), account, m, replyAll,
                account.isSentFolder(pfoldername), isHtml, profile.getEmailAddress(),
                mprofile.isIncludeMessageInReply(), lookupResource(MailLocaleKey.MSG_FROMTITLE),
                lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE),
                lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE));
        sout = "{\n result: true,";
        Identity ident = mprofile.getIdentity(pfoldername);
        String inreplyto = smsg.getInReplyTo();
        String references[] = smsg.getReferences();
        sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',";
        if (inreplyto != null) {
            sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',";
        }
        if (references != null) {
            String refs = "";
            for (String s : references) {
                refs += StringEscapeUtils.escapeEcmaScript(s) + " ";
            }
            sout += " references: '" + refs.trim() + "',";
        }
        String subject = smsg.getSubject();
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";
        sout += " recipients: [\n";
        String tos[] = smsg.getTo().split(";");
        boolean first = true;
        for (String to : tos) {
            if (!first) {
                sout += ",\n";
            }
            sout += "   {rtype:'to',email:'" + StringEscapeUtils.escapeEcmaScript(to) + "'}";
            first = false;
        }
        String ccs[] = smsg.getCc().split(";");
        for (String cc : ccs) {
            if (!first) {
                sout += ",\n";
            }
            sout += "   {rtype:'cc',email:'" + StringEscapeUtils.escapeEcmaScript(cc) + "'}";
            first = false;
        }
        sout += "\n ],\n";
        sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        if (isHtml) {
            String html = smsg.getContent();

            //cid inline attachments and relative html href substitution
            HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
            first = true;
            sout += " attachments: [\n";

            for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
                try {
                    Part part = maildata.getAttachmentPart(i);
                    String filename = getPartName(part);
                    String cids[] = part.getHeader("Content-ID");
                    if (cids != null && cids[0] != null) {
                        String cid = cids[0];
                        if (cid.startsWith("<"))
                            cid = cid.substring(1);
                        if (cid.endsWith(">"))
                            cid = cid.substring(0, cid.length() - 1);
                        String mime = MailUtils.getMediaTypeFromHeader(part.getContentType());
                        UploadedFile upfile = addAsUploadedFile("" + newmsgid, filename, mime,
                                part.getInputStream());
                        if (!first) {
                            sout += ",\n";
                        }
                        sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId())
                                + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', "
                                + " cid: '" + StringEscapeUtils.escapeEcmaScript(cid) + "', "
                                + " inline: true, " + " fileSize: " + upfile.getSize() + ", " + " editable: "
                                + isFileEditableInDocEditor(filename) + " " + " }";
                        first = false;
                        //TODO: change this weird matching of cids2urls!
                        html = StringUtils.replace(html, "cid:" + cid,
                                "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID
                                        + "&action=PreviewAttachment&nowriter=true&uploadId="
                                        + upfile.getUploadId() + "&cid=" + cid);
                    }
                } catch (Exception exc) {
                    Service.logger.error("Exception", exc);
                }
            }

            sout += "\n ],\n";

            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n";
        } else {
            String text = smsg.getTextContent();
            sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n";
        }
        sout += " format:'" + format + "'\n";
        sout += "\n}";
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
    if (sout != null) {
        out.println(sout);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processPollAdvancedSearch(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {//from w  w  w. j  a  v a2  s  .  c  o m
    CoreManager core = WT.getCoreManager();

    try {
        MailAccount account = getAccount(request);
        String sstart = request.getParameter("start");
        int start = 0;
        if (sstart != null) {
            start = Integer.parseInt(sstart);
        }
        String sout = "{\n";
        if (ast != null) {
            UserProfile profile = environment.getProfile();
            Locale locale = profile.getLocale();
            java.util.Calendar cal = java.util.Calendar.getInstance(locale);
            ArrayList<Message> msgs = ast.getResult();
            int totalrows = msgs.size();
            int newrows = totalrows - start;
            sout += "total:" + totalrows + ",\nstart:" + start + ",\nlimit:" + newrows + ",\nmessages: [\n";
            boolean first = true;
            for (int i = start; i < msgs.size(); ++i) {
                Message xm = msgs.get(i);
                if (xm.isExpunged()) {
                    continue;
                }
                IMAPFolder xmfolder = (IMAPFolder) xm.getFolder();
                boolean wasopen = xmfolder.isOpen();
                if (!wasopen)
                    xmfolder.open(Folder.READ_ONLY);
                long nuid = xmfolder.getUID(xm);
                if (!wasopen)
                    xmfolder.close(false);
                IMAPMessage m = (IMAPMessage) xm;
                //Date
                java.util.Date d = m.getSentDate();
                if (d == null) {
                    d = m.getReceivedDate();
                }
                if (d == null) {
                    d = new java.util.Date(0);
                }
                cal.setTime(d);
                int yyyy = cal.get(java.util.Calendar.YEAR);
                int mm = cal.get(java.util.Calendar.MONTH);
                int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
                int hhh = cal.get(java.util.Calendar.HOUR_OF_DAY);
                int mmm = cal.get(java.util.Calendar.MINUTE);
                int sss = cal.get(java.util.Calendar.SECOND);
                String xfolder = xm.getFolder().getFullName();
                FolderCache fc = account.getFolderCache(xfolder);
                String folder = StringEscapeUtils.escapeEcmaScript(xfolder);
                String foldername = StringEscapeUtils
                        .escapeEcmaScript(MailUtils.htmlescape(getInternationalFolderName(fc)));
                //From
                String from = "";
                Address ia[] = m.getFrom();
                if (ia != null) {
                    InternetAddress iafrom = (InternetAddress) ia[0];
                    from = iafrom.getPersonal();
                    if (from == null) {
                        from = iafrom.getAddress();
                    }
                }
                from = (from == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(from)));
                //To
                String to = "";
                ia = m.getRecipients(Message.RecipientType.TO);
                if (ia != null) {
                    InternetAddress iato = (InternetAddress) ia[0];
                    to = iato.getPersonal();
                    if (to == null) {
                        to = iato.getAddress();
                    }
                }
                to = (to == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(to)));
                //Subject
                String subject = m.getSubject();
                if (subject != null) {
                    try {
                        subject = MailUtils.decodeQString(subject);
                    } catch (Exception exc) {

                    }
                }
                subject = (subject == null ? ""
                        : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject)));
                //Unread
                boolean unread = !m.isSet(Flags.Flag.SEEN);
                //if (ppattern==null && unread) ++funread;
                //Priority
                int priority = getPriority(m);
                //Status
                java.util.Date today = new java.util.Date();
                java.util.Calendar cal1 = java.util.Calendar.getInstance(locale);
                java.util.Calendar cal2 = java.util.Calendar.getInstance(locale);
                boolean isToday = false;
                if (d != null) {
                    cal1.setTime(today);
                    cal2.setTime(d);
                    if (cal1.get(java.util.Calendar.DAY_OF_MONTH) == cal2.get(java.util.Calendar.DAY_OF_MONTH)
                            && cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH)
                            && cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)) {
                        isToday = true;
                    }
                }

                Flags flags = m.getFlags();
                String status = "read";
                if (flags != null) {
                    if (flags.contains(Flags.Flag.ANSWERED)) {
                        if (flags.contains("$Forwarded")) {
                            status = "repfwd";
                        } else {
                            status = "replied";
                        }
                    } else if (flags.contains("$Forwarded")) {
                        status = "forwarded";
                    } else if (flags.contains(Flags.Flag.SEEN)) {
                        status = "read";
                    } else if (isToday) {
                        status = "new";
                    } else {
                        status = "unread";
                    }
                    //                    if (flags.contains(Flags.Flag.USER)) flagImage=webtopapp.getUri()+"/images/themes/"+profile.getTheme()+"/mail/flag.gif";
                }
                //Size
                int msgsize = 0;
                msgsize = (m.getSize() * 3) / 4;// /1024 + 1;
                //User flags
                String cflag = "";
                for (WebtopFlag webtopFlag : webtopFlags) {
                    String flagstring = webtopFlag.label;
                    //String tbflagstring=webtopFlag.tbLabel;
                    if (!flagstring.equals("complete")) {
                        String oldflagstring = "flag" + flagstring;
                        if (flags.contains(flagstring) || flags.contains(oldflagstring)
                        /*|| (tbflagstring!=null && flags.contains(tbflagstring))*/
                        ) {
                            cflag = flagstring;
                        }
                    }
                }
                boolean flagComplete = flags.contains("complete");
                if (flagComplete) {
                    cflag += "-complete";
                }

                //idmessage=idmessage.replaceAll("\\\\", "\\\\");
                //idmessage=OldUtils.jsEscape(idmessage);
                if (!first) {
                    sout += ",\n";
                }
                boolean archived = false;
                if (hasDmsDocumentArchiving()) {
                    archived = m.getHeader("X-WT-Archived") != null;
                    if (!archived) {
                        archived = flags.contains(sflagDmsArchived);
                    }
                }

                boolean hasNote = flags.contains(sflagNote);

                sout += "{folder:'" + folder + "', folderdesc:'" + foldername + "',idmandfolder:'" + folder
                        + "|" + nuid + "',idmessage:'" + nuid + "',priority:" + priority + ",status:'" + status
                        + "',to:'" + to + "',from:'" + from + "',subject:'" + subject + "',date: new Date("
                        + yyyy + "," + mm + "," + dd + "," + hhh + "," + mmm + "," + sss + "),unread: " + unread
                        + ",size:" + msgsize + ",flag:'" + cflag + "'" + (archived ? ",arch:true" : "")
                        + (isToday ? ",istoday:true" : "") + (hasNote ? ",note:true" : "") + "}";
                first = false;
            }
            sout += "\n]\n, progress: " + ast.getProgress() + ", curfoldername: '"
                    + StringEscapeUtils.escapeEcmaScript(getInternationalFolderName(ast.getCurrentFolder()))
                    + "', " + "max: " + ast.isMoreThanMax() + ", finished: "
                    + (ast.isFinished() || ast.isCanceled() || !ast.isRunning()) + " }\n";
        } else {
            sout += "total:0,\nstart:0,\nlimit:0,\nmessages: [\n";
            sout += "\n] }\n";
        }
        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:com.sonicle.webtop.mail.Service.java

public void processGetMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pidattach = request.getParameter("idattach");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");
    String nopec = request.getParameter("nopec");
    int idattach = 0;
    boolean isEditor = request.getParameter("editor") != null;
    boolean setSeen = ServletUtils.getBooleanParameter(request, "setseen", true);

    if (df == null) {
        df = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.MEDIUM,
                environment.getProfile().getLocale());
    }// ww  w.ja  v a2 s .  c  o  m
    try {
        FolderCache mcache = null;
        Message m = null;
        IMAPMessage im = null;
        int recs = 0;
        long msguid = -1;
        String vheader[] = null;
        boolean wasseen = false;
        boolean isPECView = false;
        String sout = "{\nmessage: [\n";
        if (providername == null) {
            account.checkStoreConnected();
            mcache = account.getFolderCache(pfoldername);
            msguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(msguid);
            im = (IMAPMessage) m;
            im.setPeek(us.isManualSeen());
            if (m.isExpunged())
                throw new MessagingException("Message " + puidmessage + " expunged");
            vheader = m.getHeader("Disposition-Notification-To");
            wasseen = m.isSet(Flags.Flag.SEEN);
            if (pidattach != null) {

                HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
                m = (Message) part.getContent();
                idattach = Integer.parseInt(pidattach) + 1;
            } else if (nopec == null && mcache.isPEC()) {
                String hdrs[] = m.getHeader(HDR_PEC_TRASPORTO);
                if (hdrs != null && hdrs.length > 0 && hdrs[0].equals("posta-certificata")) {
                    HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
                    int parts = mailData.getAttachmentPartCount();
                    for (int i = 0; i < parts; ++i) {
                        Part p = mailData.getAttachmentPart(i);
                        if (p.isMimeType("message/rfc822")) {
                            m = (Message) p.getContent();
                            idattach = i + 1;
                            isPECView = true;
                            break;
                        }
                    }
                }
            }
        } else {
            // TODO: provider get message!!!!
            /*                WebTopService provider=wts.getServiceByName(providername);
                         MessageContentProvider mcp=provider.getMessageContentProvider(providerid);
                         m=new MimeMessage(session,mcp.getSource());
                         mcache=fcProvided;
                         mcache.addProvidedMessage(providername, providerid, m);*/
        }
        String messageid = getMessageID(m);
        String subject = m.getSubject();
        if (subject == null) {
            subject = "";
        } else {
            try {
                subject = MailUtils.decodeQString(subject);
            } catch (Exception exc) {

            }
        }
        java.util.Date d = m.getSentDate();
        if (d == null) {
            d = m.getReceivedDate();
        }
        if (d == null) {
            d = new java.util.Date(0);
        }
        String date = df.format(d).replaceAll("\\.", ":");
        String fromName = "";
        String fromEmail = "";
        Address as[] = m.getFrom();
        InternetAddress iafrom = null;
        if (as != null && as.length > 0) {
            iafrom = (InternetAddress) as[0];
            fromName = iafrom.getPersonal();
            fromEmail = adjustEmail(iafrom.getAddress());
            if (fromName == null) {
                fromName = fromEmail;
            }
        }
        sout += "{iddata:'from',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromName))
                + "',value2:'" + StringEscapeUtils.escapeEcmaScript(fromEmail) + "',value3:0},\n";
        recs += 2;
        Address tos[] = m.getRecipients(RecipientType.TO);
        if (tos != null) {
            for (Address to : tos) {
                InternetAddress ia = (InternetAddress) to;
                String toName = ia.getPersonal();
                String toEmail = adjustEmail(ia.getAddress());
                if (toName == null) {
                    toName = toEmail;
                }
                sout += "{iddata:'to',value1:'"
                        + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toName)) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(toEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address ccs[] = m.getRecipients(RecipientType.CC);
        if (ccs != null) {
            for (Address cc : ccs) {
                InternetAddress ia = (InternetAddress) cc;
                String ccName = ia.getPersonal();
                String ccEmail = adjustEmail(ia.getAddress());
                if (ccName == null) {
                    ccName = ccEmail;
                }
                sout += "{iddata:'cc',value1:'" + StringEscapeUtils.escapeEcmaScript(ccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(ccEmail) + "',value3:0},\n";
                ++recs;
            }
        }
        Address bccs[] = m.getRecipients(RecipientType.BCC);
        if (bccs != null)
            for (Address bcc : bccs) {
                InternetAddress ia = (InternetAddress) bcc;
                String bccName = ia.getPersonal();
                String bccEmail = adjustEmail(ia.getAddress());
                if (bccName == null) {
                    bccName = bccEmail;
                }
                sout += "{iddata:'bcc',value1:'" + StringEscapeUtils.escapeEcmaScript(bccName) + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(bccEmail) + "',value3:0},\n";
                ++recs;
            }
        ArrayList<String> htmlparts = null;
        boolean balanceTags = isPreviewBalanceTags(iafrom);
        if (providername == null) {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, msguid, false, balanceTags);
        } else {
            htmlparts = mcache.getHTMLParts((MimeMessage) m, providername, providerid, balanceTags);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        ICalendarRequest ir = mailData.getICalRequest();
        if (ir != null) {
            if (htmlparts.size() > 0)
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(htmlparts.get(0))
                        + "',value2:'',value3:0},\n";
        } else {
            for (String html : htmlparts) {
                //sout += "{iddata:'html',value1:'" + OldUtils.jsEscape(html) + "',value2:'',value3:0},\n";
                sout += "{iddata:'html',value1:'" + StringEscapeUtils.escapeEcmaScript(html)
                        + "',value2:'',value3:0},\n";
                ++recs;
            }
        }

        /*if (!wasseen) {
           //if (us.isManualSeen()) {
           if (!setSeen) {
              m.setFlag(Flags.Flag.SEEN, false);
           } else {
              //if no html part, flag seen is not set
              if (htmlparts.size()==0) m.setFlag(Flags.Flag.SEEN, true);
           }
        }*/
        if (!us.isManualSeen()) {
            if (htmlparts.size() == 0)
                m.setFlag(Flags.Flag.SEEN, true);
        } else {
            if (setSeen)
                m.setFlag(Flags.Flag.SEEN, true);
        }

        int acount = mailData.getAttachmentPartCount();
        for (int i = 0; i < acount; ++i) {
            Part p = mailData.getAttachmentPart(i);
            String ctype = p.getContentType();
            Service.logger.debug("attachment " + i + " is " + ctype);
            int ix = ctype.indexOf(';');
            if (ix > 0) {
                ctype = ctype.substring(0, ix);
            }
            String cidnames[] = p.getHeader("Content-ID");
            String cidname = null;
            if (cidnames != null && cidnames.length > 0)
                cidname = mcache.normalizeCidFileName(cidnames[0]);
            boolean isInlineable = isInlineableMime(ctype);
            boolean inline = ((p.getHeader("Content-Location") != null) || (cidname != null)) && isInlineable;
            if (inline && cidname != null)
                inline = mailData.isReferencedCid(cidname);
            if (p.getDisposition() != null && p.getDisposition().equalsIgnoreCase(Part.INLINE) && inline) {
                continue;
            }

            String imgname = null;
            boolean isCalendar = ctype.equalsIgnoreCase("text/calendar")
                    || ctype.equalsIgnoreCase("text/icalendar");
            if (isCalendar) {
                imgname = "resources/" + getManifest().getId() + "/laf/" + cus.getLookAndFeel()
                        + "/ical_16.png";
            }

            String pname = getPartName(p);
            try {
                pname = MailUtils.decodeQString(pname);
            } catch (Exception exc) {
            }
            if (pname == null) {
                ix = ctype.indexOf("/");
                String fname = ctype;
                if (ix > 0) {
                    fname = ctype.substring(ix + 1);
                }
                //String ext = WT.getMediaTypeExtension(ctype);
                //if (ext == null) {
                pname = fname;
                //} else {
                //   pname = fname + "." + ext;
                //}
                if (isCalendar)
                    pname += ".ics";
            } else {
                if (isCalendar && !StringUtils.endsWithIgnoreCase(pname, ".ics"))
                    pname += ".ics";
            }
            int size = p.getSize();
            int lines = (size / 76);
            int rsize = size - (lines * 2);//(p.getSize()/4)*3;
            String iddata = ctype.equalsIgnoreCase("message/rfc822") ? "eml"
                    : (inline ? "inlineattach" : "attach");
            boolean editable = isFileEditableInDocEditor(pname);

            sout += "{iddata:'" + iddata + "',value1:'" + (i + idattach) + "',value2:'"
                    + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(pname)) + "',value3:" + rsize
                    + ",value4:"
                    + (imgname == null ? "null" : "'" + StringEscapeUtils.escapeEcmaScript(imgname) + "'")
                    + ", editable: " + editable + " },\n";
        }
        if (!mcache.isDrafts() && !mcache.isSent() && !mcache.isSpam() && !mcache.isTrash()
                && !mcache.isArchive()) {
            if (vheader != null && vheader[0] != null && !wasseen) {
                sout += "{iddata:'receipt',value1:'" + us.getReadReceiptConfirmation() + "',value2:'"
                        + StringEscapeUtils.escapeEcmaScript(vheader[0]) + "',value3:0},\n";
            }
        }

        String h = getSingleHeaderValue(m, "Sonicle-send-scheduled");
        if (h != null && h.equals("true")) {
            java.util.Calendar scal = parseScheduleHeader(getSingleHeaderValue(m, "Sonicle-send-date"),
                    getSingleHeaderValue(m, "Sonicle-send-time"));
            if (scal != null) {
                java.util.Date sd = scal.getTime();
                String sdate = df.format(sd).replaceAll("\\.", ":");
                sout += "{iddata:'scheddate',value1:'" + StringEscapeUtils.escapeEcmaScript(sdate)
                        + "',value2:'',value3:0},\n";
            }
        }

        if (ir != null) {

            /*
            ICalendarManager calMgr = (ICalendarManager)WT.getServiceManager("com.sonicle.webtop.calendar",environment.getProfileId());
            if (calMgr != null) {
               if (ir.getMethod().equals("REPLY")) {
                  calMgr.updateEventFromICalReply(ir.getCalendar());
                  //TODO: gestire lato client una notifica di avvenuto aggiornamento
               } else {
                  Event evt = calMgr..getEvent(GetEventScope.PERSONAL_AND_INCOMING, false, ir.getUID())
                  if (evt != null) {
             UserProfileId pid = getEnv().getProfileId();
             UserProfile.Data ud = WT.getUserData(pid);
             boolean iAmOrganizer = StringUtils.equalsIgnoreCase(evt.getOrganizerAddress(), ud.getEmailAddress());
             boolean iAmOwner = pid.equals(calMgr.getCalendarOwner(evt.getCalendarId()));
                     
             if (!iAmOrganizer && !iAmOwner) {
                //TODO: gestire lato client l'aggiornamento: Accetta/Rifiuta, Aggiorna e20 dopo update/request
             }
                  }
               }
            }
            */

            ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true,
                    environment.getProfileId());
            if (cm != null) {
                int eid = -1;
                //Event ev=cm.getEventByScope(EventScope.PERSONAL_AND_INCOMING, ir.getUID());
                Event ev = null;
                if (ir.getMethod().equals("REPLY")) {
                    // Previous impl. forced (forceOriginal == true)
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                } else {
                    ev = cm.getEvent(GetEventScope.PERSONAL_AND_INCOMING, ir.getUID());
                }

                UserProfileId pid = getEnv().getProfileId();
                UserProfile.Data ud = WT.getUserData(pid);

                if (ev != null) {
                    InternetAddress organizer = InternetAddressUtils.toInternetAddress(ev.getOrganizer());
                    boolean iAmOwner = pid.equals(cm.getCalendarOwner(ev.getCalendarId()));
                    boolean iAmOrganizer = (organizer != null)
                            && StringUtils.equalsIgnoreCase(organizer.getAddress(), ud.getEmailAddress());

                    //TODO: in reply controllo se mail combacia con quella dell'attendee che risponde...
                    //TODO: rimuovere controllo su data? dovrebbe sempre aggiornare?

                    if (iAmOwner || iAmOrganizer) {
                        eid = 0;
                        //TODO: troviamo un modo per capire se la risposta si riverisce all'ultima versione dell'evento? Nuovo campo timestamp?
                        /*
                        DateTime dtEvt = ev.getRevisionTimestamp().withMillisOfSecond(0).withZone(DateTimeZone.UTC);
                        DateTime dtICal = ICal4jUtils.fromICal4jDate(ir.getLastModified(), ICal4jUtils.getTimeZone(DateTimeZone.UTC));
                        if (dtICal.isAfter(dtEvt)) {
                           eid = 0;
                        } else {
                           eid = ev.getEventId();
                        }
                        */
                    }
                }
                sout += "{iddata:'ical',value1:'" + ir.getMethod() + "',value2:'" + ir.getUID() + "',value3:'"
                        + eid + "'},\n";
            }
        }

        sout += "{iddata:'date',value1:'" + StringEscapeUtils.escapeEcmaScript(date)
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'subject',value1:'" + StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject))
                + "',value2:'',value3:0},\n";
        sout += "{iddata:'messageid',value1:'" + StringEscapeUtils.escapeEcmaScript(messageid)
                + "',value2:'',value3:0}\n";

        if (providername == null && !mcache.isSpecial()) {
            mcache.refreshUnreads();
        }
        long millis = System.currentTimeMillis();
        sout += "\n],\n";

        String svtags = getJSTagsArray(m.getFlags());
        if (svtags != null)
            sout += "tags: " + svtags + ",\n";

        if (isPECView) {
            sout += "pec: true,\n";
        }

        sout += "total:" + recs + ",\nmillis:" + millis + "\n}\n";
        out.println(sout);

        if (im != null)
            im.setPeek(false);

        //            if (!wasopen) folder.close(false);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * @return the body from the supplied message or null if there was a problem
 *
 * @throws MessagingException if there was a problem reading the message status
 * @throws IOException if the body content could not be retrieved
 *//*from w ww.j a  v a  2  s. c o  m*/
public Object getBody(Message msg) throws MessagingException, IOException {
    if (msg != null && !msg.isExpunged() && !msg.isSet(Flags.Flag.DELETED))
        return msg.getContent();

    return null;
}

From source file:org.openadaptor.auxil.connector.mail.MailReadConnector.java

/**
 * @return true if the supplied message is to be processed - ie. if it has
 * not been expunged, marked for deletion or is null. Also takes into account
 * the [ProcessReadMessages] property which, if set to false, means that read
 * messages should not be processed.//w  w  w  . jav a2s  . c om
 *
 * @throws MessagingException if there was a comms error
 */
protected boolean isToBeProcessed(Message msg) throws MessagingException {
    // Note: isExpunged() is the only allowable call on an expunged message
    // or we get an exception so we need to check this first before checking
    // if it has been read.
    if (msg == null || msg.isExpunged() || msg.isSet(Flags.Flag.DELETED))
        return false;

    if (!processReadMessages && msg.isSet(Flags.Flag.SEEN))
        return false;

    return true;
}

From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java

/**
 * This method read verification e-mail from Gmail inbox and returns the verification URL.
 *
 * @return  verification redirection URL.
 * @throws  Exception/*  w  w  w  . j  a  v  a2s.c o  m*/
 */
public static String readGmailInboxForVerification() throws Exception {
    boolean isEmailVerified = false;
    long waitTime = 10000;
    String pointBrowserURL = "";
    Properties props = new Properties();
    props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG")
            + File.separator + "axis2" + File.separator + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);
    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isEmailVerified) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());
                    if (message.getSubject().contains("EmailVerification")) {
                        pointBrowserURL = getBodyFromMessage(message);
                        isEmailVerified = true;
                    }

                    // Optional : deleting the mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }
        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count * waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return pointBrowserURL;
}

From source file:org.wso2.carbon.registry.es.utils.EmailUtil.java

/**
 * This method read e-mails from Gmail inbox and find whether the notification of particular type is found.
 *
 * @param   notificationType    Notification types supported by publisher and store.
 * @return  whether email is found for particular type.
 * @throws  Exception//ww w  .  j  a  va  2s  . c o m
 */
public static boolean readGmailInboxForNotification(String notificationType) throws Exception {
    boolean isNotificationMailAvailable = false;
    long waitTime = 10000;
    Properties props = new Properties();
    props.load(new FileInputStream(new File(TestConfigurationProvider.getResourceLocation("GREG")
            + File.separator + "axis2" + File.separator + "smtp.properties")));
    Session session = Session.getDefaultInstance(props, null);
    Store store = session.getStore("imaps");
    store.connect("smtp.gmail.com", emailAddress, java.nio.CharBuffer.wrap(emailPassword).toString());

    Folder inbox = store.getFolder("inbox");
    inbox.open(Folder.READ_WRITE);
    Thread.sleep(waitTime);

    long startTime = System.currentTimeMillis();
    long endTime = 0;
    int count = 1;
    while (endTime - startTime < 180000 && !isNotificationMailAvailable) {
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            if (!message.isExpunged()) {
                try {
                    log.info("Mail Subject:- " + message.getSubject());

                    if (message.getSubject().contains(notificationType)) {
                        isNotificationMailAvailable = true;

                    }
                    // Optional : deleting the  mail
                    message.setFlag(Flags.Flag.DELETED, true);
                } catch (MessageRemovedException e) {
                    log.error("Could not read the message subject. Message is removed from inbox");
                }
            }

        }
        endTime = System.currentTimeMillis();
        Thread.sleep(waitTime);
        endTime += count * waitTime;
        count++;
    }
    inbox.close(true);
    store.close();
    return isNotificationMailAvailable;
}