Example usage for javax.mail.internet InternetAddress getPersonal

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

Introduction

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

Prototype

public String getPersonal() 

Source Link

Document

Get the personal name.

Usage

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

public String getDecodedAddress(Address a) {
    String ret = "";
    try {//from w ww  .  j a  v  a 2 s  . c o  m
        InternetAddress ia = (InternetAddress) a;
        String personal = ia.getPersonal();
        String email = ia.getAddress();
        if (personal == null || personal.equals(email)) {
            ret = email;
        } else {
            ret = personal + " <" + email + ">";
        }
    } catch (RuntimeException exc) {
        ret = a.toString();
    }
    return ret;
}

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

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

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

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

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

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

                boolean hasNote = flags.contains(sflagNote);

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

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

public void processSendMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    JsonResult json = null;//from  w w  w.  j  a v a  2s . c om
    CoreManager coreMgr = WT.getCoreManager();
    IContactsManager contactsManager = (IContactsManager) WT.getServiceManager("com.sonicle.webtop.contacts",
            true, environment.getProfileId());

    // TODO: Cloud integration!!!
    /*        VFSService vfs=(VFSService)wts.getServiceByName("vfs");
           ArrayList<String> hashlinks=null;
           if (vfs!=null) {
           //look for links to cloud in the html
           String html=request.getParameter("content");
           hashlinks=new ArrayList<String>();
           int hlx=-1;
           String puburl=wtd.getSetting("vfs.pub.url");
           char chars[]=new char[] { '\'', '"'};
           for(char c: chars) {
           String pattern="<a href="+c+puburl+"/public/vfs/";
           Service.logger.debug("Looking for pattern "+pattern);
           while((hlx=html.indexOf(pattern,hlx+1))>=0) {
           int xhash1=hlx+pattern.length();
           int xhash2=html.indexOf(c,xhash1);
           if (xhash2>xhash1) {
           String hash=html.substring(xhash1,xhash2);
           Service.logger.debug("Found hash "+hash);
           hashlinks.add(hash);
           }
           }
           }
           }*/
    try {
        MailAccount account = getAccount(request);
        //String emails[]=request.getParameterValues("recipients");
        Payload<MapItem, JsMessage> pl = ServletUtils.getPayload(request, JsMessage.class);
        JsMessage jsmsg = pl.data;
        long msgId = ServletUtils.getLongParameter(request, "msgId", true);
        boolean isFax = ServletUtils.getBooleanParameter(request, "isFax", false);
        boolean save = ServletUtils.getBooleanParameter(request, "save", false);

        if (isFax) {
            int faxmaxtos = getEnv().getCoreServiceSettings().getFaxMaxRecipients();

            //check for valid fax recipients
            String faxpattern = getEnv().getCoreServiceSettings().getFaxPattern();
            String regex = "^" + faxpattern.replace("{number}", "(\\d+)").replace("{username}", "(\\w+)") + "$";
            Pattern pattern = Pattern.compile(regex);
            int nemails = 0;
            for (JsRecipient jsr : jsmsg.recipients) {
                if (StringUtils.isEmpty(jsr.email))
                    continue;
                ++nemails;
                if (StringUtils.isNumeric(jsr.email))
                    continue;
                boolean matches = false;
                try {
                    InternetAddress ia = new InternetAddress(jsr.email);
                    String email = ia.getAddress();
                    matches = pattern.matcher(email).matches();
                } catch (Exception exc) {

                }
                if (!matches) {
                    throw new Exception(lookupResource(MailLocaleKey.FAX_ADDRESS_ERROR));
                }
            }
            if (faxmaxtos > 0 && nemails > faxmaxtos) {
                throw new WTException(lookupResource(MailLocaleKey.FAX_MAXADDRESS_ERROR), faxmaxtos);
            }

        }

        account.checkStoreConnected();
        //String attachments[] = request.getParameterValues("attachments");
        //if (attachments == null) {
        //   attachments = new String[0];
        //}
        SimpleMessage msg = prepareMessage(jsmsg, msgId, save, isFax);
        Identity ifrom = msg.getFrom();
        String from = environment.getProfile().getEmailAddress();
        if (ifrom != null) {
            from = ifrom.getEmail();
        }
        account.checkStoreConnected();
        Exception exc = sendMessage(msg, jsmsg.attachments);
        if (exc == null) {
            //if is draft, check for deletion
            if (jsmsg.draftuid > 0 && jsmsg.draftfolder != null && ss.isDefaultFolderDraftsDeleteMsgOnSend()) {
                FolderCache fc = account.getFolderCache(jsmsg.draftfolder);
                fc.deleteMessages(new long[] { jsmsg.draftuid }, false);
            }

            //Save used recipients
            for (JsRecipient rcpt : pl.data.recipients) {
                String email = rcpt.email;
                if (email != null && email.trim().length() > 0)
                    coreMgr.autoLearnInternetRecipient(email);
            }

            //Save subject for suggestions
            if (jsmsg.subject != null && jsmsg.subject.trim().length() > 0)
                WT.getCoreManager().addServiceStoreEntry(SERVICE_ID, "subject", jsmsg.subject.toUpperCase(),
                        jsmsg.subject);

            coreMgr.deleteMyAutosaveData(getEnv().getClientTrackingID(), SERVICE_ID, "newmail", "" + msgId);

            deleteAutosavedDraft(account, msgId);
            // TODO: Cloud integration!!! Destination emails added to share
            /*                if (vfs!=null && hashlinks!=null && hashlinks.size()>0) {
                         for(String hash: hashlinks) {
                         Service.logger.debug("Adding emails to hash "+hash);
                         vfs.setAuthEmails(hash, from, emails);
                         }
                    
                         }*/
            FolderCache fc = account.getFolderCache(account.getFolderSent());
            fc.setForceRefresh();
            //check for in-reply-to and set the answered flags
            //String inreplyto = request.getParameter("inreplyto");
            //String replyfolder = request.getParameter("replyfolder");
            //String forwardedfrom = request.getParameter("forwardedfrom");
            //String forwardedfolder = request.getParameter("forwardedfolder");
            //String soriguid=request.getParameter("origuid");
            //long origuid=0;
            //try { origuid=Long.parseLong(soriguid); } catch(RuntimeException rexc) {}
            String foundfolder = null;
            if (jsmsg.forwardedfrom != null && jsmsg.forwardedfrom.trim().length() > 0) {
                try {
                    foundfolder = foundfolder = flagForwardedMessage(account, jsmsg.forwardedfolder,
                            jsmsg.forwardedfrom, jsmsg.origuid);
                } catch (Exception xexc) {
                    Service.logger.error("Exception", xexc);
                }
            } else if ((jsmsg.inreplyto != null && jsmsg.inreplyto.trim().length() > 0)
                    || (jsmsg.replyfolder != null && jsmsg.replyfolder.trim().length() > 0
                            && jsmsg.origuid > 0)) {
                try {

                    String[] toRecipients = SimpleMessage.breakAddr(msg.getTo());

                    for (String toRecipient : toRecipients) {
                        InternetAddress internetAddress = getInternetAddress(toRecipient);
                        String contactEmail = internetAddress.getAddress();
                        String contactPersonal = internetAddress.getPersonal();

                        Condition<ContactQuery> predicate = new ContactQuery().email().eq(contactEmail);

                        List<Integer> myCategories = contactsManager.listCategoryIds();
                        List<Integer> sharedCategories = contactsManager.listIncomingCategoryIds();
                        myCategories.addAll(sharedCategories);

                        boolean existsContact = contactsManager.existContact(myCategories, predicate);

                        if (!existsContact) {
                            sendAddContactMessage(contactEmail, contactPersonal);
                            break;
                        }
                    }

                    foundfolder = flagAnsweredMessage(account, jsmsg.replyfolder, jsmsg.inreplyto,
                            jsmsg.origuid);
                } catch (Exception xexc) {
                    Service.logger.error("Exception", xexc);
                }
            }

            json = new JsonResult().set("foundfolder", foundfolder).set("saved", Boolean.FALSE);
        } else {
            Throwable cause = exc.getCause();
            String msgstr = cause != null ? cause.getMessage() : exc.getMessage();
            json = new JsonResult(false, msgstr);
        }
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        Throwable cause = exc.getCause();
        String msg = cause != null ? cause.getMessage() : exc.getMessage();
        json = new JsonResult(false, msg);
    }
    json.printTo(out);
}

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

public void processGetEditMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pnewmsgid = request.getParameter("newmsgid");
    long newmsgid = Long.parseLong(pnewmsgid);
    String sout = null;/*from ww w  .  java  2  s. c  om*/
    try {
        MailEditFormat editFormat = ServletUtils.getEnumParameter(request, "format", null,
                MailEditFormat.class);
        if (editFormat == null)
            editFormat = EnumUtils.forSerializedName(us.getFormat(), MailEditFormat.HTML, MailEditFormat.class);
        boolean isPlainEdit = MailEditFormat.PLAIN_TEXT.equals(editFormat);

        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        IMAPMessage m = (IMAPMessage) mcache.getMessage(Long.parseLong(puidmessage));
        m.setPeek(us.isManualSeen());
        //boolean wasseen = m.isSet(Flags.Flag.SEEN);
        String vheader[] = m.getHeader("Disposition-Notification-To");
        boolean receipt = false;
        int priority = 3;
        boolean recipients = false;
        boolean toDelete = false;
        if (account.isDraftsFolder(pfoldername)) {
            if (vheader != null && vheader[0] != null) {
                receipt = true;
            }
            priority = getPriority(m);
            recipients = true;

            //if autosaved drafts, delete
            String values[] = m.getHeader(HEADER_X_WEBTOP_MSGID);
            if (values != null && values.length > 0) {
                try {
                    long msgId = Long.parseLong(values[0]);
                    if (msgId > 0) {
                        toDelete = true;
                    }
                } catch (NumberFormatException exc) {

                }
            }
        }

        sout = "{\n result: true,";
        String subject = m.getSubject();
        if (subject == null) {
            subject = "";
        }
        sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n";

        String inreplyto = null;
        String references[] = null;
        String vs[] = m.getHeader("In-Reply-To");
        if (vs != null && vs[0] != null) {
            inreplyto = vs[0];
        }
        references = m.getHeader("References");
        if (inreplyto != null) {
            vs = m.getHeader("Sonicle-reply-folder");
            String replyfolder = null;
            if (vs != null && vs[0] != null) {
                replyfolder = vs[0];
            }
            if (replyfolder != null) {
                sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(replyfolder) + "',";
            }
            sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',";
        }
        if (references != null) {
            String refs = "";
            for (String s : references) {
                refs += StringEscapeUtils.escapeEcmaScript(s) + " ";
            }
            sout += " references: '" + refs.trim() + "',";
        }

        String forwardedfrom = null;
        vs = m.getHeader("Forwarded-From");
        if (vs != null && vs[0] != null) {
            forwardedfrom = vs[0];
        }
        if (forwardedfrom != null) {
            vs = m.getHeader("Sonicle-forwarded-folder");
            String forwardedfolder = null;
            if (vs != null && vs[0] != null) {
                forwardedfolder = vs[0];
            }
            if (forwardedfolder != null) {
                sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(forwardedfolder) + "',";
            }
            sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',";
        }

        sout += " receipt: " + receipt + ",\n";
        sout += " priority: " + (priority >= 3 ? false : true) + ",\n";

        Identity ident = null;
        Address from[] = m.getFrom();
        InternetAddress iafrom = null;
        if (from != null && from.length > 0) {
            iafrom = (InternetAddress) from[0];
            String email = iafrom.getAddress();
            String displayname = iafrom.getPersonal();
            if (displayname == null)
                displayname = email;
            //sout+=" from: { email: '"+StringEscapeUtils.escapeEcmaScript(email)+"', displayname: '"+StringEscapeUtils.escapeEcmaScript(displayname)+"' },\n";
            ident = mprofile.getIdentity(displayname, email);
        }

        sout += " recipients: [\n";
        if (recipients) {
            Address tos[] = m.getRecipients(RecipientType.TO);
            String srec = "";
            if (tos != null) {
                for (Address to : tos) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'to', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(to)) + "'" + " }";
                }
            }
            Address ccs[] = m.getRecipients(RecipientType.CC);
            if (ccs != null) {
                for (Address cc : ccs) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'cc', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(cc)) + "'" + " }";
                }
            }
            Address bccs[] = m.getRecipients(RecipientType.BCC);
            if (bccs != null) {
                for (Address bcc : bccs) {
                    if (srec.length() > 0) {
                        srec += ",\n";
                    }
                    srec += "   { " + "rtype: 'bcc', " + "email: '"
                            + StringEscapeUtils.escapeEcmaScript(getDecodedAddress(bcc)) + "'" + " }";
                }
            }

            sout += srec;
        } else {
            sout += "   { " + "rtype: 'to', " + "email: ''" + " }";

        }
        sout += " ],\n";

        String html = "";
        boolean balanceTags = isPreviewBalanceTags(iafrom);
        ArrayList<String> htmlparts = mcache.getHTMLParts((MimeMessage) m, newmsgid, true, balanceTags);
        for (String xhtml : htmlparts) {
            html += xhtml + "<BR><BR>";
        }
        HTMLMailData maildata = mcache.getMailData((MimeMessage) m);
        //if(!wasseen){
        //   if (us.isManualSeen()) {
        //      m.setFlag(Flags.Flag.SEEN, false);
        //   }
        //}

        boolean first = true;
        sout += " attachments: [\n";
        for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) {
            Part part = maildata.getAttachmentPart(i);
            String filename = getPartName(part);

            String cids[] = part.getHeader("Content-ID");
            String cid = null;
            //String cid=filename;
            if (cids != null && cids[0] != null) {
                cid = cids[0];
                if (cid.startsWith("<"))
                    cid = cid.substring(1);
                if (cid.endsWith(">"))
                    cid = cid.substring(0, cid.length() - 1);
            }

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

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

        if (ident != null)
            sout += " identityId: " + ident.getIdentityId() + ",\n";
        sout += " origuid:" + puidmessage + ",\n";
        sout += " deleted:" + toDelete + ",\n";
        sout += " folder:'" + pfoldername + "',\n";
        sout += " content:'" + (isPlainEdit
                ? StringEscapeUtils.escapeEcmaScript(MailUtils.htmlToText(MailUtils.htmlunescapesource(html)))
                : StringEscapeUtils.escapeEcmaScript(html)) + "',\n";
        sout += " format:'" + EnumUtils.toSerializedName(editFormat) + "'\n";
        sout += "\n}";

        m.setPeek(false);

        if (toDelete) {
            m.setFlag(Flags.Flag.DELETED, true);
            m.getFolder().expunge();
        }

        out.println(sout);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
}

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  w  w  . ja  va  2 s  .  co  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  ww  .  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:com.sonicle.webtop.mail.Service.java

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

    try {//from  w w w . jav a 2 s  .c  o 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);
    }
}