Example usage for javax.mail Flags contains

List of usage examples for javax.mail Flags contains

Introduction

In this page you can find the example usage for javax.mail Flags contains.

Prototype

public boolean contains(Flags f) 

Source Link

Document

Check whether all the flags in the specified Flags object are present in this Flags object.

Usage

From source file:com.hs.mail.imap.dao.FlagUtils.java

static String getParam(Flags flags, Flags.Flag flag) {
    return flags.contains(flag) ? "Y" : "N";
}

From source file:com.hs.mail.imap.message.responder.AbstractImapResponder.java

protected void flags(Flags flags) {
    if (flags.contains(Flags.Flag.ANSWERED)) {
        message("\\Answered");
    }//from  w w w  .  ja  v  a2 s .  co  m
    if (flags.contains(Flags.Flag.DELETED)) {
        message("\\Deleted");
    }
    if (flags.contains(Flags.Flag.DRAFT)) {
        message("\\Draft");
    }
    if (flags.contains(Flags.Flag.FLAGGED)) {
        message("\\Flagged");
    }
    if (flags.contains(Flags.Flag.RECENT)) {
        message("\\Recent");
    }
    if (flags.contains(Flags.Flag.SEEN)) {
        message("\\Seen");
    }
    String[] ufs = flags.getUserFlags();
    if (!ArrayUtils.isEmpty(ufs)) {
        for (String uf : ufs) {
            message(uf);
        }
    }
    skipNextSpace = false;
}

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

private String getJSTagsArray(Flags flags) {
    ArrayList<Tag> tags = null;
    String svtags = null;/*  w ww.  j  av a2  s .  c  o  m*/
    if (flags != null) {
        for (Tag tag : atags) {
            if (flags.contains(tag.getTagId())) {
                if (tags == null)
                    tags = new ArrayList<>();
                tags.add(tag);
            }
        }
        if (tags != null) {
            for (Tag tag : tags) {
                if (svtags == null)
                    svtags = "[ ";
                else
                    svtags += ",";
                svtags += "'" + StringEscapeUtils.escapeEcmaScript(tag.getTagId()) + "'";
            }
            if (svtags != null)
                svtags += " ]";
        }
    }
    return svtags;
}

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

public void processPollAdvancedSearch(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {/*from   ww w.ja v a  2 s  .  c  om*/
    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 processListMessages(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    CoreManager core = WT.getCoreManager();
    UserProfile profile = environment.getProfile();
    Locale locale = profile.getLocale();
    java.util.Calendar cal = java.util.Calendar.getInstance(locale);
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    //String psortfield = request.getParameter("sort");
    //String psortdir = request.getParameter("dir");
    String pstart = request.getParameter("start");
    String plimit = request.getParameter("limit");
    String ppage = request.getParameter("page");
    String prefresh = request.getParameter("refresh");
    String ptimestamp = request.getParameter("timestamp");
    String pthreaded = request.getParameter("threaded");
    String pthreadaction = request.getParameter("threadaction");
    String pthreadactionuid = request.getParameter("threadactionuid");

    QueryObj queryObj = null;//from  w  w  w .  j a va 2  s . c  om
    SearchTerm searchTerm = null;
    try {
        queryObj = ServletUtils.getObjectParameter(request, "query", new QueryObj(), QueryObj.class);
    }

    catch (ParameterException parameterException) {
        logger.error("Exception getting query obejct parameter", parameterException);
    }

    boolean refresh = (prefresh != null && prefresh.equals("true"));
    //boolean threaded=(pthreaded!=null && pthreaded.equals("1"));

    //String threadedSetting="list-threaded-"+pfoldername;
    //if (pthreaded==null || pthreaded.equals("2")) {
    //   threaded=us.isMessageListThreaded(pfoldername);
    //} else {
    //   us.setMessageListThreaded(pfoldername, threaded);
    //}
    //System.out.println("timestamp="+ptimestamp);
    long timestamp = Long.parseLong(ptimestamp);

    if (account.isSpecialFolder(pfoldername) || account.isSharedFolder(pfoldername)) {
        logger.debug("folder is special or shared, refresh forced");
        refresh = true;
    }

    String group = us.getMessageListGroup(pfoldername);
    if (group == null) {
        group = "";
    }

    String psortfield = "date";
    String psortdir = "DESC";
    try {
        boolean nogroup = group.equals("");
        JsSort.List sortList = ServletUtils.getObjectParameter(request, "sort", null, JsSort.List.class);
        if (sortList == null) {
            if (nogroup) {
                String s = us.getMessageListSort(pfoldername);
                int ix = s.indexOf("|");
                psortfield = s.substring(0, ix);
                psortdir = s.substring(ix + 1);
            } else {
                psortfield = "date";
                psortdir = "DESC";
            }
        } else {
            JsSort jsSort = sortList.get(0);
            psortfield = jsSort.property;
            psortdir = jsSort.direction;
            if (!nogroup && !psortfield.equals("date")) {
                group = "";
            }
            us.setMessageListGroup(pfoldername, group);
            us.setMessageListSort(pfoldername, psortfield, psortdir);
        }
    } catch (Exception exc) {
        logger.error("Exception", exc);
    }

    SortGroupInfo sgi = getSortGroupInfo(psortfield, psortdir, group);

    //Save search requests

    int start = Integer.parseInt(pstart);
    int limit = Integer.parseInt(plimit);
    int page = 0;
    if (ppage != null) {
        page = Integer.parseInt(ppage);
        start = (page - 1) * limit;
    }
    /*int start = 0;
    int limit = mprofile.getNumMsgList();
    if (ppage==null) {
       if (pstart != null) {
    start = Integer.parseInt(pstart);
       }   
       if (plimit != null) {
    limit = Integer.parseInt(plimit);
       }
    } else {
       int page=Integer.parseInt(ppage);
       int nxpage=mprofile.getNumMsgList();
       start=(page-1)*nxpage;
       limit=nxpage;
    }*/

    String sout = "{\n";
    Folder folder = null;
    boolean connected = false;
    try {
        connected = account.checkStoreConnected();
        if (!connected)
            throw new Exception("Mail account authentication error");

        int funread = 0;
        if (pfoldername == null) {
            folder = account.getDefaultFolder();
        } else {
            folder = account.getFolder(pfoldername);
        }
        boolean issent = account.isSentFolder(folder.getFullName());
        boolean isundersent = account.isUnderSentFolder(folder.getFullName());
        boolean isdrafts = account.isDraftsFolder(folder.getFullName());
        boolean isundershared = account.isUnderSharedFolder(pfoldername);
        if (!issent) {
            String names[] = folder.getFullName().split("\\" + account.getFolderSeparator());
            for (String pname : names) {
                if (account.isSentFolder(pname)) {
                    issent = true;
                    break;
                }
            }
        }

        String ctn = Thread.currentThread().getName();
        String key = folder.getFullName();

        if (!pfoldername.equals("/")) {

            FolderCache mcache = account.getFolderCache(key);
            if (mcache.toBeRefreshed())
                refresh = true;
            //Message msgs[]=mcache.getMessages(ppattern,psearchfield,sortby,ascending,refresh);
            if (psortfield != null && psortdir != null) {
                key += "|" + psortdir + "|" + psortfield;
            }

            searchTerm = ImapQuery.toSearchTerm(this.allFlagStrings, this.atags, queryObj,
                    profile.getTimeZone());

            boolean hasAttachment = queryObj.conditions.stream()
                    .anyMatch(condition -> condition.value.equals("attachment"));
            if (queryObj != null)
                refresh = true;
            MessagesInfo messagesInfo = listMessages(mcache, key, refresh, sgi, timestamp, searchTerm,
                    hasAttachment);
            Message xmsgs[] = messagesInfo.messages;

            if (pthreadaction != null && pthreadaction.trim().length() > 0) {
                long actuid = Long.parseLong(pthreadactionuid);
                mcache.setThreadOpen(actuid, pthreadaction.equals("open"));
            }

            //if threaded, look for the start considering roots and opened children
            if (xmsgs != null && sgi.threaded && page > 1) {
                int i = 0, ni = 0, np = 1;
                long tId = 0;
                while (np < page && ni < xmsgs.length) {
                    SonicleIMAPMessage xm = (SonicleIMAPMessage) xmsgs[ni];
                    ++ni;
                    if (xm.isExpunged())
                        continue;

                    long nuid = mcache.getUID(xm);

                    int tIndent = xm.getThreadIndent();
                    if (tIndent == 0)
                        tId = nuid;
                    else {
                        if (!mcache.isThreadOpen(tId))
                            continue;
                    }

                    ++i;
                    if ((i % limit) == 0)
                        ++np;
                }
                if (np == page) {
                    start = ni;
                    //System.out.println("page "+np+" start is "+start);
                }
            }

            int max = start + limit;
            if (xmsgs != null && max > xmsgs.length)
                max = xmsgs.length;
            ArrayList<Long> autoeditList = new ArrayList<Long>();
            if (xmsgs != null) {
                int total = 0;
                int expunged = 0;

                //calculate expunged
                //for(Message xmsg: xmsgs) {
                //   if (xmsg.isExpunged()) ++expunged;
                //}

                sout += "messages: [\n";

                /*               if (ppattern==null && !isSpecialFolder(mcache.getFolderName())) {
                 //mcache.fetch(msgs,FolderCache.flagsFP,0,start);
                 for(int i=0;i<start;++i) {
                 try {
                 if (!msgs[i].isSet(Flags.Flag.SEEN)) funread++;
                 } catch(Exception exc) {
                        
                 }
                 }
                 }*/
                total = sgi.threaded ? mcache.getThreadedCount() : xmsgs.length;
                if (start < max) {

                    Folder fsent = account.getFolder(account.getFolderSent());
                    boolean openedsent = false;
                    //Fetch others for these messages
                    mcache.fetch(xmsgs, (isdrafts ? draftsFP : messagesInfo.isPEC() ? pecFP : FP), start, max);
                    long tId = 0;
                    for (int i = 0, ni = 0; i < limit; ++ni, ++i) {
                        int ix = start + i;
                        int nx = start + ni;
                        if (nx >= xmsgs.length)
                            break;
                        if (ix >= max)
                            break;

                        SonicleIMAPMessage xm = (SonicleIMAPMessage) xmsgs[nx];
                        if (xm.isExpunged()) {
                            --i;
                            continue;
                        }

                        /*if (messagesInfo.checkSkipPEC(xm)) {
                           --i; --total;
                           continue;
                        }*/

                        /*String ids[]=null;
                         try {
                         ids=xm.getHeader("Message-ID");
                         } catch(MessagingException exc) {
                         --i;
                         continue;
                         }
                         if (ids==null || ids.length==0) { --i; continue; }
                         String idmessage=ids[0];*/

                        long nuid = mcache.getUID(xm);

                        int tIndent = xm.getThreadIndent();
                        if (tIndent == 0)
                            tId = nuid;
                        else if (sgi.threaded) {
                            if (!mcache.isThreadOpen(tId)) {
                                --i;
                                continue;
                            }
                        }
                        boolean tChildren = false;
                        int tUnseenChildren = 0;
                        if (sgi.threaded) {
                            int cnx = nx + 1;
                            while (cnx < xmsgs.length) {
                                SonicleIMAPMessage cxm = (SonicleIMAPMessage) xmsgs[cnx];
                                if (cxm.isExpunged()) {
                                    cnx++;
                                    continue;
                                }
                                while (cxm.getThreadIndent() > 0) {
                                    tChildren = true;
                                    if (!cxm.isExpunged() && !cxm.isSet(Flags.Flag.SEEN))
                                        ++tUnseenChildren;
                                    ++cnx;
                                    if (cnx >= xmsgs.length)
                                        break;
                                    cxm = (SonicleIMAPMessage) xmsgs[cnx];
                                }
                                break;
                            }
                        }

                        Flags flags = xm.getFlags();

                        //Date
                        java.util.Date d = xm.getSentDate();
                        if (d == null)
                            d = xm.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);
                        //From
                        String from = "";
                        String fromemail = "";
                        Address ia[] = xm.getFrom();
                        if (ia != null) {
                            InternetAddress iafrom = (InternetAddress) ia[0];
                            from = iafrom.getPersonal();
                            if (from == null)
                                from = iafrom.getAddress();
                            fromemail = iafrom.getAddress();
                        }
                        from = (from == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(from)));
                        fromemail = (fromemail == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromemail)));

                        //To
                        String to = "";
                        String toemail = "";
                        ia = xm.getRecipients(Message.RecipientType.TO);
                        //if not sent and not shared, show me first if in TO
                        if (ia != null) {
                            InternetAddress iato = (InternetAddress) ia[0];
                            if (!issent && !isundershared) {
                                for (Address ax : ia) {
                                    InternetAddress iax = (InternetAddress) ax;
                                    if (iax.getAddress().equals(profile.getEmailAddress())) {
                                        iato = iax;
                                        break;
                                    }
                                }
                            }
                            to = iato.getPersonal();
                            if (to == null)
                                to = iato.getAddress();
                            toemail = iato.getAddress();
                        }
                        to = (to == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(to)));
                        toemail = (toemail == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toemail)));

                        //Subject
                        String subject = xm.getSubject();
                        if (subject != null) {
                            try {
                                subject = MailUtils.decodeQString(subject);
                            } catch (Exception exc) {

                            }
                        } else
                            subject = "";

                        /*                  if (threaded) {
                                          if (tIndent>0) {
                                             StringBuffer sb=new StringBuffer();
                                             for(int w=0;w<tIndent;++w) sb.append("&nbsp;");
                                             subject=sb+subject;
                                          }
                                       }*/

                        boolean hasAttachments = mcache.hasAttachements(xm);

                        subject = StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject));

                        //Unread
                        boolean unread = !xm.isSet(Flags.Flag.SEEN);
                        if (queryObj != null && unread)
                            ++funread;
                        //Priority
                        int priority = getPriority(xm);
                        //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;
                        String gdate = "";
                        String sdate = "";
                        String xdate = "";
                        if (d != null) {
                            java.util.Date gd = sgi.threaded ? xm.getMostRecentThreadDate() : d;

                            cal1.setTime(today);
                            cal2.setTime(gd);

                            gdate = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(gd);
                            sdate = cal2.get(java.util.Calendar.YEAR) + "/"
                                    + String.format("%02d", (cal2.get(java.util.Calendar.MONTH) + 1)) + "/"
                                    + String.format("%02d", cal2.get(java.util.Calendar.DATE));
                            //boolean isGdate=group.equals("gdate");
                            if (cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH)
                                    && cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)) {
                                int dx = cal1.get(java.util.Calendar.DAY_OF_MONTH)
                                        - cal2.get(java.util.Calendar.DAY_OF_MONTH);
                                if (dx == 0) {
                                    isToday = true;
                                    //if (isGdate) {
                                    //   gdate=WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_TODAY)+"  "+gdate;
                                    //}
                                    xdate = WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_TODAY);
                                } else if (dx == 1 /*&& isGdate*/) {
                                    xdate = WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_YESTERDAY);
                                }
                            }
                        }

                        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 = (xm.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) {
                            if (cflag.length() > 0)
                                cflag += "-complete";
                            else
                                cflag = "complete";
                        }

                        if (cflag.length() == 0 && flags.contains(Flags.Flag.FLAGGED))
                            cflag = "special";

                        boolean hasNote = flags.contains(sflagNote);

                        String svtags = getJSTagsArray(flags);

                        boolean autoedit = false;

                        boolean issched = false;
                        int syyyy = 0;
                        int smm = 0;
                        int sdd = 0;
                        int shhh = 0;
                        int smmm = 0;
                        int ssss = 0;
                        if (isdrafts) {
                            String h = getSingleHeaderValue(xm, "Sonicle-send-scheduled");
                            if (h != null && h.equals("true")) {
                                java.util.Calendar scal = parseScheduleHeader(
                                        getSingleHeaderValue(xm, "Sonicle-send-date"),
                                        getSingleHeaderValue(xm, "Sonicle-send-time"));
                                if (scal != null) {
                                    syyyy = scal.get(java.util.Calendar.YEAR);
                                    smm = scal.get(java.util.Calendar.MONTH);
                                    sdd = scal.get(java.util.Calendar.DAY_OF_MONTH);
                                    shhh = scal.get(java.util.Calendar.HOUR_OF_DAY);
                                    smmm = scal.get(java.util.Calendar.MINUTE);
                                    ssss = scal.get(java.util.Calendar.SECOND);
                                    issched = true;
                                    status = "scheduled";
                                }
                            }

                            h = getSingleHeaderValue(xm, HEADER_SONICLE_FROM_DRAFTER);
                            if (h != null && h.equals("true")) {
                                autoedit = true;
                            }
                        }

                        String xmfoldername = xm.getFolder().getFullName();

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

                        String msgtext = null;
                        if (us.getShowMessagePreviewOnRow() && isToday && unread) {
                            try {
                                msgtext = MailUtils.peekText(xm);
                                if (msgtext != null) {
                                    msgtext = msgtext.trim();
                                    if (msgtext.length() > 100)
                                        msgtext = msgtext.substring(0, 100);
                                }
                            } catch (MessagingException | IOException ex1) {
                                msgtext = ex1.getMessage();
                            }
                        }

                        String pecstatus = null;
                        if (messagesInfo.isPEC()) {
                            String hdrs[] = xm.getHeader(HDR_PEC_TRASPORTO);
                            if (hdrs != null && hdrs.length > 0
                                    && (hdrs[0].equals("errore") || hdrs[0].equals("posta-certificata")))
                                pecstatus = hdrs[0];
                            else {
                                hdrs = xm.getHeader(HDR_PEC_RICEVUTA);
                                if (hdrs != null && hdrs.length > 0)
                                    pecstatus = hdrs[0];
                            }
                        }

                        sout += "{idmessage:'" + nuid + "'," + "priority:" + priority + "," + "status:'"
                                + status + "'," + "to:'" + to + "'," + "toemail:'" + toemail + "'," + "from:'"
                                + from + "'," + "fromemail:'" + fromemail + "'," + "subject:'" + subject + "',"
                                + (msgtext != null
                                        ? "msgtext: '" + StringEscapeUtils.escapeEcmaScript(msgtext) + "',"
                                        : "")
                                + (sgi.threaded ? "threadId: " + tId + "," : "")
                                + (sgi.threaded ? "threadIndent:" + tIndent + "," : "") + "date: new Date("
                                + yyyy + "," + mm + "," + dd + "," + hhh + "," + mmm + "," + sss + "),"
                                + "gdate: '" + gdate + "'," + "sdate: '" + sdate + "'," + "xdate: '" + xdate
                                + "'," + "unread: " + unread + "," + "size:" + msgsize + ","
                                + (svtags != null ? "tags: " + svtags + "," : "")
                                + (pecstatus != null ? "pecstatus: '" + pecstatus + "'," : "") + "flag:'"
                                + cflag + "'" + (hasNote ? ",note:true" : "") + (archived ? ",arch:true" : "")
                                + (isToday ? ",istoday:true" : "") + (hasAttachments ? ",atts:true" : "")
                                + (issched
                                        ? ",scheddate: new Date(" + syyyy + "," + smm + "," + sdd + "," + shhh
                                                + "," + smmm + "," + ssss + ")"
                                        : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadOpen: " + mcache.isThreadOpen(nuid)
                                        : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadHasChildren: " + tChildren : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadUnseenChildren: " + tUnseenChildren
                                        : "")
                                + (sgi.threaded && xm.hasThreads() && !xm.isMostRecentInThread() ? ",fmtd: true"
                                        : "")
                                + (sgi.threaded && !xmfoldername.equals(folder.getFullName()) ? ",fromfolder: '"
                                        + StringEscapeUtils.escapeEcmaScript(xmfoldername) + "'" : "")
                                + "}";

                        if (autoedit) {
                            autoeditList.add(nuid);
                        }

                        //                sout+="{messageid:'"+m.getMessageID()+"',from:'"+from+"',subject:'"+subject+"',date: new Date("+yyyy+","+mm+","+dd+"),unread: "+unread+"},\n";
                    }

                    if (openedsent)
                        fsent.close(false);
                }
                /*                if (ppattern==null && !isSpecialFolder(mcache.getFolderName())) {
                 //if (max<msgs.length) mcache.fetch(msgs,FolderCache.flagsFP,max,msgs.length);
                 for(int i=max;i<msgs.length;++i) {
                 try {
                 if (!msgs[i].isSet(Flags.Flag.SEEN)) funread++;
                 } catch(Exception exc) {
                        
                 }
                 }
                 } else {
                 funread=mcache.getUnreadMessagesCount();
                 }*/
                if (mcache.isScanForcedOrEnabled()) {
                    //Send message only if first page
                    if (start == 0)
                        mcache.refreshUnreads();
                    funread = mcache.getUnreadMessagesCount();
                } else
                    funread = 0;

                long qlimit = -1;
                long qusage = -1;
                try {
                    Quota quotas[] = account.getQuota("INBOX");
                    if (quotas != null)
                        for (Quota q : quotas) {
                            if ((q.quotaRoot.equals("INBOX") || q.quotaRoot.equals("Quota"))
                                    && q.resources != null) {
                                for (Quota.Resource r : q.resources) {
                                    if (r.name.equals("STORAGE")) {
                                        qlimit = r.limit;
                                        qusage = r.usage;
                                    }
                                }
                            }
                        }
                } catch (MessagingException exc) {
                    logger.debug("Error on QUOTA", exc);
                }

                sout += "\n],\n";
                sout += "total: " + (total - expunged) + ",\n";
                if (qlimit >= 0 && qusage >= 0)
                    sout += "quotaLimit: " + qlimit + ", quotaUsage: " + qusage + ",\n";
                if (messagesInfo.isPEC())
                    sout += "isPEC: true,\n";
                sout += "realTotal: " + (xmsgs.length - expunged) + ",\n";
                sout += "expunged: " + (expunged) + ",\n";
            } else {
                sout += "messages: [],\n" + "total: 0,\n" + "realTotal: 0,\n" + "expunged:0,\n";
            }
            sout += "metaData: {\n" + "  root: 'messages', total: 'total', idProperty: 'idmessage',\n"
                    + "  fields: ['idmessage','priority','status','to','from','subject','date','gdate','unread','size','flag','note','arch','istoday','atts','scheddate','fmtd','fromfolder'],\n"
                    + "  sortInfo: { field: '" + psortfield + "', direction: '" + psortdir + "' },\n"
                    + "  threaded: " + sgi.threaded + ",\n" + "  groupField: '"
                    + (sgi.threaded ? "threadId" : group) + "',\n";

            /*            ColumnVisibilitySetting cvs = us.getColumnVisibilitySetting(pfoldername);
                        ColumnsOrderSetting cos = us.getColumnsOrderSetting();
                        // Apply grid defaults
                        //ColumnVisibilitySetting.applyDefaults(mcache.isSent(), cvs);
                        ColumnVisibilitySetting.applyDefaults(issent||isundersent, cvs);
                    
                        if (autoeditList.size()>0) {
                           sout+="autoedit: [";
                           for(long muid: autoeditList) {
                              sout+=muid+",";
                           }
                           if(StringUtils.right(sout, 1).equals(",")) sout = StringUtils.left(sout, sout.length()-1);
                           sout+="],\n";
                        }
                                
                        // Fills columnsInfo object for client rendering
                        sout += "colsInfo2: [";
                        for (String dataIndex : cvs.keySet()) {
                           sout += "{dataIndex:'" + dataIndex + "',hidden:" + String.valueOf(!cvs.get(dataIndex)) + ",index:"+cos.indexOf(dataIndex)+"},";
                        }
                        if (StringUtils.right(sout, 1).equals(",")) {
                           sout = StringUtils.left(sout, sout.length() - 1);
                        }
                        sout += "]\n";*/

            sout += "},\n";
            sout += "threaded: " + (sgi.threaded ? "1" : "0") + ",\n";
            sout += "unread: " + funread + ", issent: " + issent + ", millis: " + messagesInfo.millis + " }\n";

        } else {
            sout += "total:0,\nstart:0,\nlimit:0,\nmessages: [\n";
            sout += "\n], unread: 0, issent: false }\n";
        }
        out.println(sout);
    } catch (Exception exc) {
        new JsonResult(exc).printTo(out);
        Service.logger.error("Exception", exc);
    }
}

From source file:org.alfresco.repo.imap.AlfrescoImapFolder.java

/**
 * Returns count of messages with {@link javax.mail.Flags.Flag#RECENT} flag.
 * If {@code reset} parameter is {@code true} - removes {@link javax.mail.Flags.Flag#RECENT} flag from
 * the message for current user./*  w  w  w.ja  v a  2s  .  c o m*/
 * 
 * @param reset - if true the {@link javax.mail.Flags.Flag#RECENT} will be deleted for current user if exists.
 * @return returns count of recent messages.
 */
@Override
public int getRecentCount(boolean reset) {
    int recent = getFolderStatus().recentCount;
    if (reset && recent > 0) {
        CommandCallback<Void> command = new CommandCallback<Void>() {
            public Void command() throws Throwable {
                for (FileInfo fileInfo : folderStatus.search.values()) {
                    Flags flags = imapService.getFlags(fileInfo);
                    if (flags.contains(Flags.Flag.RECENT)) {
                        imapService.setFlag(fileInfo, Flags.Flag.RECENT, false);
                    }
                }
                return null;
            }
        };
        try {
            command.run();
        } catch (AccessDeniedException ade) {
            if (logger.isDebugEnabled()) {
                logger.debug("Access denied to reset RECENT FLAG");
            }
        }
    }
    return recent;
}

From source file:org.alfresco.repo.imap.ImapServiceImpl.java

public void expungeMessage(FileInfo fileInfo) {
    Flags flags = getFlags(fileInfo);
    if (flags.contains(Flags.Flag.DELETED)) {
        // See MNT-12259
        //fileFolderService.delete(fileInfo.getNodeRef());
        hideAndDelete(fileInfo.getNodeRef());
        messageCache.remove(fileInfo.getNodeRef());
    }//from  w  w  w. j  a v a  2 s .c  o  m
}

From source file:org.alfresco.repo.imap.ImapServiceImpl.java

/**
 * Search for emails in specified folder depending on view mode.
 * /*w  w w  . j  a  va 2s  . c  om*/
 * Shallow list of files
 * 
 * @param contextNodeRef context folder for search
 * @param viewMode context folder view mode
 * @return list of emails that context folder contains.
 */
public FolderStatus getFolderStatus(final String userName, final NodeRef contextNodeRef,
        ImapViewMode viewMode) {
    if (logger.isDebugEnabled()) {
        logger.debug("getFolderStatus contextNodeRef=" + contextNodeRef + ", viewMode=" + viewMode);
    }

    // No need to ACL check the change token read
    String changeToken = AuthenticationUtil.runAs(new RunAsWork<String>() {
        @Override
        public String doWork() throws Exception {
            return (String) nodeService.getProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN);
        }
    }, AuthenticationUtil.getSystemUserName());

    Pair<String, String> cacheKey = null;
    if (changeToken != null) {
        cacheKey = new Pair<String, String>(userName, changeToken);
        this.folderCacheLock.readLock().lock();
        try {
            FolderStatus result = this.folderCache.get(cacheKey);
            if (result != null) {
                return result;
            }
        } finally {
            this.folderCacheLock.readLock().unlock();
        }
    }

    List<FileInfo> fileInfos = null;
    FileFilterMode.setClient(Client.imap);
    try {
        fileInfos = fileFolderService.listFiles(contextNodeRef);
    } finally {
        FileFilterMode.clearClient();
    }

    final NavigableMap<Long, FileInfo> currentSearch = new TreeMap<Long, FileInfo>();

    switch (viewMode) {
    case MIXED:
        for (FileInfo fileInfo : fileInfos) {
            currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
        }
        break;
    case ARCHIVE:
        for (FileInfo fileInfo : fileInfos) {
            if (nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) {
                currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
            }
        }
        break;
    case VIRTUAL:
        for (FileInfo fileInfo : fileInfos) {
            if (!nodeService.hasAspect(fileInfo.getNodeRef(), ImapModel.ASPECT_IMAP_CONTENT)) {
                currentSearch.put((Long) fileInfo.getProperties().get(ContentModel.PROP_NODE_DBID), fileInfo);
            }
        }
        break;
    }

    int messageCount = currentSearch.size(), recentCount = 0, unseenCount = 0, firstUnseen = 0;
    int i = 1;
    for (FileInfo fileInfo : currentSearch.values()) {
        Flags flags = getFlags(fileInfo);
        if (flags.contains(Flags.Flag.RECENT)) {
            recentCount++;
        }
        if (!flags.contains(Flags.Flag.SEEN)) {
            if (firstUnseen == 0) {
                firstUnseen = i;
            }
            unseenCount++;
        }
        i++;
    }
    // Add the IMAP folder aspect with appropriate initial values if it is not already there
    if (changeToken == null) {
        changeToken = GUID.generate();
        cacheKey = new Pair<String, String>(userName, changeToken);
        final String finalToken = changeToken;
        doAsSystem(new RunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                nodeService.setProperty(contextNodeRef, ImapModel.PROP_CHANGE_TOKEN, finalToken);
                nodeService.setProperty(contextNodeRef, ImapModel.PROP_MAXUID,
                        currentSearch.isEmpty() ? 0 : currentSearch.lastKey());
                return null;
            }
        });
    }
    Long uidValidity = (Long) nodeService.getProperty(contextNodeRef, ImapModel.PROP_UIDVALIDITY);
    FolderStatus result = new FolderStatus(messageCount, recentCount, firstUnseen, unseenCount,
            uidValidity == null ? 0 : uidValidity, changeToken, currentSearch);
    this.folderCacheLock.writeLock().lock();
    try {
        FolderStatus oldResult = this.folderCache.get(cacheKey);
        if (oldResult != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("At end of getFolderStatus. Found info in cache, changeToken:" + changeToken);
            }

            return oldResult;
        }
        this.folderCache.put(cacheKey, result);

        if (logger.isDebugEnabled()) {
            logger.debug("At end of getFolderStatus. Found files:" + currentSearch.size() + ", changeToken:"
                    + changeToken);
        }
        return result;
    } finally {
        this.folderCacheLock.writeLock().unlock();
    }
}

From source file:org.apache.james.jmap.model.UpdateMessagePatch.java

public Flags applyToState(Flags currentFlags) {
    Flags newStateFlags = new Flags();

    if (isFlagged().orElse(currentFlags.contains(Flags.Flag.FLAGGED))) {
        newStateFlags.add(Flags.Flag.FLAGGED);
    }//  ww  w  .  ja  v a2  s .co  m
    if (isAnswered().orElse(currentFlags.contains(Flags.Flag.ANSWERED))) {
        newStateFlags.add(Flags.Flag.ANSWERED);
    }
    boolean shouldMessageBeMarkSeen = isUnread().map(b -> !b).orElse(currentFlags.contains(Flags.Flag.SEEN));
    if (shouldMessageBeMarkSeen) {
        newStateFlags.add(Flags.Flag.SEEN);
    }
    return newStateFlags;
}

From source file:org.apache.james.mailbox.hbase.mail.HBaseMailboxMessage.java

@Override
public final void setFlags(Flags flags) {
    answered = flags.contains(Flags.Flag.ANSWERED);
    deleted = flags.contains(Flags.Flag.DELETED);
    draft = flags.contains(Flags.Flag.DRAFT);
    flagged = flags.contains(Flags.Flag.FLAGGED);
    recent = flags.contains(Flags.Flag.RECENT);
    seen = flags.contains(Flags.Flag.SEEN);
    String[] userflags = flags.getUserFlags();
    userFlags.clear();/* w  w  w. j a v  a  2  s. co m*/
    userFlags.addAll(Arrays.asList(userflags));
}