Example usage for javax.mail.internet InternetAddress getAddress

List of usage examples for javax.mail.internet InternetAddress getAddress

Introduction

In this page you can find the example usage for javax.mail.internet InternetAddress getAddress.

Prototype

public String getAddress() 

Source Link

Document

Get the email address.

Usage

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());
    }/*from   w  ww.  j  av a  2  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: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. ja  v  a2 s . c o  m*/
    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:com.sonicle.webtop.mail.Service.java

public void processPortletMail(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    ArrayList<JsPreviewMessage> items = new ArrayList<>();

    try {/*  w w  w .j av a 2 s .co  m*/
        MailAccount account = getAccount(request);
        String query = ServletUtils.getStringParameter(request, "query", null);
        int visibleRows = 0;
        int maxVisibleRows = 20;

        if (query == null) {
            String folderId = account.getInboxFolderFullName();
            FolderCache fc = account.getFolderCache(folderId);
            Message msgs[] = fc.getMessages(FolderCache.SORT_BY_DATE, false, true, -1, true, false, null,
                    false);
            if (msgs != null)
                fc.fetch(msgs, getMessageFetchProfile(), 0, 50);
            else
                msgs = new Message[0];

            for (Message msg : msgs) {
                SonicleIMAPMessage simsg = (SonicleIMAPMessage) msg;

                InternetAddress iafrom = null;
                Address vfrom[] = msg.getFrom();
                if (vfrom != null && vfrom.length > 0) {
                    Address afrom = vfrom[0];
                    if (afrom instanceof InternetAddress) {
                        iafrom = (InternetAddress) afrom;
                    }
                }

                Address[] rcpts = msg.getRecipients(Message.RecipientType.TO);
                ArrayList<InternetAddress> tos = new ArrayList<>();
                if (rcpts != null)
                    for (Address ato : rcpts) {
                        if (ato instanceof InternetAddress) {
                            InternetAddress iato = (InternetAddress) ato;
                            tos.add(iato);
                        }
                    }

                String msgtext = "";
                if (visibleRows < maxVisibleRows) {
                    msgtext = MailUtils.peekText(simsg);
                    if (msgtext == null)
                        msgtext = "";
                    else {
                        msgtext = msgtext.trim();
                        if (msgtext.length() > 100)
                            msgtext = msgtext.substring(0, 100);
                    }
                    ++visibleRows;
                }

                String from = iafrom != null
                        ? (iafrom.getPersonal() != null ? iafrom.getPersonal() : iafrom.getAddress())
                        : "";
                String to = "";
                if (tos.size() > 0) {
                    boolean first = true;
                    for (InternetAddress iato : tos) {
                        if (!first)
                            to += "; ";
                        to += (iato.getPersonal() != null ? iato.getPersonal() : iato.getAddress());
                        first = false;
                    }
                }

                JsPreviewMessage jsmsg = new JsPreviewMessage(simsg.getUID(), folderId,
                        getInternationalFolderName(account.getFolderCache(folderId)), simsg.getSubject(), from,
                        to, msg.getReceivedDate(), msgtext);
                items.add(jsmsg);
            }
        } else {
        }

        new JsonResult(items).printTo(out);

    } catch (Exception ex) {
        logger.error("Error in PortletMail", ex);
        new JsonResult(false, "Error").printTo(out);
    }
}