List of usage examples for org.apache.commons.lang3 StringEscapeUtils escapeEcmaScript
public static final String escapeEcmaScript(final String input)
Escapes the characters in a String using EcmaScript String rules.
Escapes any values it finds into their EcmaScript String form.
From source file:com.sonicle.webtop.mail.Service.java
public void processMoveFolder(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String folder = request.getParameter("folder"); String to = request.getParameter("to"); String sout = null;/*from w w w . j a va 2s . co m*/ FolderCache mcache = null; try { account.checkStoreConnected(); boolean result = true; sout = "{\n"; mcache = account.getFolderCache(folder); if (account.isSpecialFolder(folder)) { result = false; } else { FolderCache newfc = account.moveFolder(folder, to); Folder newf = newfc.getFolder(); sout += "oldid: '" + StringEscapeUtils.escapeEcmaScript(folder) + "',\n"; sout += "newid: '" + StringEscapeUtils.escapeEcmaScript(newf.getFullName()) + "',\n"; sout += "newname: '" + StringEscapeUtils.escapeEcmaScript(newf.getName()) + "',\n"; if (to != null) { sout += "parent: '" + StringEscapeUtils.escapeEcmaScript(newf.getParent().getFullName()) + "',\n"; } result = true; } sout += "result: " + result + "\n}"; } catch (MessagingException exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, oldid: '" + StringEscapeUtils.escapeEcmaScript(folder) + "', oldname: '" + StringEscapeUtils.escapeEcmaScript(mcache != null ? mcache.getFolder().getName() : "unknown") + "', text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; } out.println(sout); }
From source file:com.sonicle.webtop.mail.Service.java
public void processEmptyFolder(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String folder = request.getParameter("folder"); String sout = null;/*from www . j a v a 2 s . c o m*/ FolderCache mcache = null; try { account.checkStoreConnected(); sout = "{\n"; mcache = account.getFolderCache(folder); account.emptyFolder(folder); sout += "oldid: '" + StringEscapeUtils.escapeEcmaScript(folder) + "',\n"; sout += "result: true\n}"; } catch (MessagingException exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, oldid: '" + StringEscapeUtils.escapeEcmaScript(folder) + "', oldname: '" + StringEscapeUtils.escapeEcmaScript(mcache != null ? mcache.getFolder().getName() : "unknown") + "', text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; } out.println(sout); }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetSource(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); String foldername = request.getParameter("folder"); String uid = request.getParameter("id"); String sheaders = request.getParameter("headers"); boolean headers = sheaders.equals("true"); String sout = null;//from w ww . ja v a2 s .co m try { account.checkStoreConnected(); //StringBuffer sb = new StringBuffer("<pre>"); StringBuffer sb = new StringBuffer(); FolderCache mcache = account.getFolderCache(foldername); Message msg = mcache.getMessage(Long.parseLong(uid)); //Folder folder=msg.getFolder(); for (Enumeration e = msg.getAllHeaders(); e.hasMoreElements();) { Header header = (Header) e.nextElement(); //sb.append(MailUtils.htmlescape(header.getName()) + ": " + MailUtils.htmlescape(header.getValue()) + "\n"); sb.append(header.getName() + ": " + header.getValue() + "\n"); } if (!headers) { BufferedReader br = new BufferedReader(new InputStreamReader(msg.getInputStream())); String line = null; while ((line = br.readLine()) != null) { //sb.append(MailUtils.htmlescape(line) + "\n"); sb.append(line + "\n"); } } //sb.append("</pre>"); sout = "{\nresult: true, source: '" + StringEscapeUtils.escapeEcmaScript(sb.toString()) + "'\n}"; } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; } out.println(sout); }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetReplyMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { MailAccount account = getAccount(request); UserProfile profile = environment.getProfile(); //WebTopApp webtopapp=environment.getWebTopApp(); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String preplyall = request.getParameter("replyall"); boolean replyAll = false; if (preplyall != null && preplyall.equals("1")) { replyAll = true;/* w w w .j a v a 2 s.c om*/ } String sout = null; try { String format = us.getFormat(); boolean isHtml = format.equals("html"); account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); Message m = mcache.getMessage(Long.parseLong(puidmessage)); if (m.isExpunged()) { throw new MessagingException("Message " + puidmessage + " expunged"); } int newmsgid = getNewMessageID(); SimpleMessage smsg = getReplyMsg(getNewMessageID(), account, m, replyAll, account.isSentFolder(pfoldername), isHtml, profile.getEmailAddress(), mprofile.isIncludeMessageInReply(), lookupResource(MailLocaleKey.MSG_FROMTITLE), lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE), lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE)); sout = "{\n result: true,"; Identity ident = mprofile.getIdentity(pfoldername); String inreplyto = smsg.getInReplyTo(); String references[] = smsg.getReferences(); sout += " replyfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',"; if (inreplyto != null) { sout += " inreplyto: '" + StringEscapeUtils.escapeEcmaScript(inreplyto) + "',"; } if (references != null) { String refs = ""; for (String s : references) { refs += StringEscapeUtils.escapeEcmaScript(s) + " "; } sout += " references: '" + refs.trim() + "',"; } String subject = smsg.getSubject(); sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n"; sout += " recipients: [\n"; String tos[] = smsg.getTo().split(";"); boolean first = true; for (String to : tos) { if (!first) { sout += ",\n"; } sout += " {rtype:'to',email:'" + StringEscapeUtils.escapeEcmaScript(to) + "'}"; first = false; } String ccs[] = smsg.getCc().split(";"); for (String cc : ccs) { if (!first) { sout += ",\n"; } sout += " {rtype:'cc',email:'" + StringEscapeUtils.escapeEcmaScript(cc) + "'}"; first = false; } sout += "\n ],\n"; sout += " identityId: " + ident.getIdentityId() + ",\n"; sout += " origuid:" + puidmessage + ",\n"; if (isHtml) { String html = smsg.getContent(); //cid inline attachments and relative html href substitution HTMLMailData maildata = mcache.getMailData((MimeMessage) m); first = true; sout += " attachments: [\n"; for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) { try { Part part = maildata.getAttachmentPart(i); String filename = getPartName(part); String cids[] = part.getHeader("Content-ID"); if (cids != null && cids[0] != null) { String cid = cids[0]; if (cid.startsWith("<")) cid = cid.substring(1); if (cid.endsWith(">")) cid = cid.substring(0, cid.length() - 1); String mime = MailUtils.getMediaTypeFromHeader(part.getContentType()); UploadedFile upfile = addAsUploadedFile("" + newmsgid, filename, mime, part.getInputStream()); if (!first) { sout += ",\n"; } sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: '" + StringEscapeUtils.escapeEcmaScript(cid) + "', " + " inline: true, " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; first = false; //TODO: change this weird matching of cids2urls! html = StringUtils.replace(html, "cid:" + cid, "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId() + "&cid=" + cid); } } catch (Exception exc) { Service.logger.error("Exception", exc); } } sout += "\n ],\n"; sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n"; } else { String text = smsg.getTextContent(); sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n"; } sout += " format:'" + format + "'\n"; sout += "\n}"; } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; } if (sout != null) { out.println(sout); } }
From source file:com.sonicle.webtop.mail.Service.java
public void processGetForwardMessage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {/*from ww w . j a v a 2 s . c o m*/ MailAccount account = getAccount(request); UserProfile profile = environment.getProfile(); String pfoldername = request.getParameter("folder"); String puidmessage = request.getParameter("idmessage"); String pnewmsgid = request.getParameter("newmsgid"); String pattached = request.getParameter("attached"); boolean attached = (pattached != null && pattached.equals("1")); long newmsgid = Long.parseLong(pnewmsgid); String sout = null; try { String format = us.getFormat(); boolean isHtml = format.equals("html"); account.checkStoreConnected(); FolderCache mcache = account.getFolderCache(pfoldername); Message m = mcache.getMessage(Long.parseLong(puidmessage)); if (m.isExpunged()) { throw new MessagingException("Message " + puidmessage + " expunged"); } SimpleMessage smsg = getForwardMsg(newmsgid, m, isHtml, lookupResource(MailLocaleKey.MSG_FROMTITLE), lookupResource(MailLocaleKey.MSG_TOTITLE), lookupResource(MailLocaleKey.MSG_CCTITLE), lookupResource(MailLocaleKey.MSG_DATETITLE), lookupResource(MailLocaleKey.MSG_SUBJECTTITLE), attached); sout = "{\n result: true,"; Identity ident = mprofile.getIdentity(pfoldername); String forwardedfrom = smsg.getForwardedFrom(); sout += " forwardedfolder: '" + StringEscapeUtils.escapeEcmaScript(pfoldername) + "',"; if (forwardedfrom != null) { sout += " forwardedfrom: '" + StringEscapeUtils.escapeEcmaScript(forwardedfrom) + "',"; } String subject = smsg.getSubject(); sout += " subject: '" + StringEscapeUtils.escapeEcmaScript(subject) + "',\n"; String html = smsg.getContent(); String text = smsg.getTextContent(); if (!attached) { HTMLMailData maildata = mcache.getMailData((MimeMessage) m); boolean first = true; sout += " attachments: [\n"; for (int i = 0; i < maildata.getAttachmentPartCount(); ++i) { try { Part part = maildata.getAttachmentPart(i); String filename = getPartName(part); if (!part.isMimeType("message/*")) { String cids[] = part.getHeader("Content-ID"); String cid = null; //String cid=filename; if (cids != null && cids[0] != null) { cid = cids[0]; if (cid.startsWith("<")) cid = cid.substring(1); if (cid.endsWith(">")) cid = cid.substring(0, cid.length() - 1); } if (filename == null) filename = cid; String mime = MailUtils.getMediaTypeFromHeader(part.getContentType()); UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, mime, part.getInputStream()); boolean inline = false; if (part.getDisposition() != null) { inline = part.getDisposition().equalsIgnoreCase(Part.INLINE); } if (!first) { sout += ",\n"; } sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: " + (cid == null ? null : "'" + StringEscapeUtils.escapeEcmaScript(cid) + "'") + ", " + " inline: " + inline + ", " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; first = false; //TODO: change this weird matching of cids2urls! html = StringUtils.replace(html, "cid:" + cid, "service-request?csrf=" + getEnv().getCSRFToken() + "&service=" + SERVICE_ID + "&action=PreviewAttachment&nowriter=true&uploadId=" + upfile.getUploadId() + "&cid=" + cid); } } catch (Exception exc) { Service.logger.error("Exception", exc); } } sout += "\n ],\n"; //String surl = "service-request?service="+SERVICE_ID+"&action=PreviewAttachment&nowriter=true&newmsgid=" + newmsgid + "&cid="; //html = replaceCidUrls(html, maildata, surl); } else { String filename = m.getSubject() + ".eml"; UploadedFile upfile = addAsUploadedFile(pnewmsgid, filename, "message/rfc822", ((IMAPMessage) m).getMimeStream()); sout += " attachments: [\n"; sout += "{ " + " uploadId: '" + StringEscapeUtils.escapeEcmaScript(upfile.getUploadId()) + "', " + " fileName: '" + StringEscapeUtils.escapeEcmaScript(filename) + "', " + " cid: null, " + " inline: false, " + " fileSize: " + upfile.getSize() + ", " + " editable: " + isFileEditableInDocEditor(filename) + " " + " }"; sout += "\n ],\n"; } sout += " identityId: " + ident.getIdentityId() + ",\n"; sout += " origuid:" + puidmessage + ",\n"; if (isHtml) { sout += " content:'" + StringEscapeUtils.escapeEcmaScript(html) + "',\n"; } else { sout += " content:'" + StringEscapeUtils.escapeEcmaScript(text) + "',\n"; } sout += " format:'" + format + "'\n"; sout += "\n}"; out.println(sout); } catch (Exception exc) { Service.logger.error("Exception", exc); sout = "{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"; out.println(sout); } }
From source file:com.sonicle.webtop.mail.Service.java
public void 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;/* w w w .j ava 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 processListMessages(HttpServletRequest request, HttpServletResponse response, PrintWriter out) { CoreManager core = WT.getCoreManager(); UserProfile profile = environment.getProfile(); Locale locale = profile.getLocale(); java.util.Calendar cal = java.util.Calendar.getInstance(locale); MailAccount account = getAccount(request); String pfoldername = request.getParameter("folder"); //String psortfield = request.getParameter("sort"); //String psortdir = request.getParameter("dir"); String pstart = request.getParameter("start"); String plimit = request.getParameter("limit"); String ppage = request.getParameter("page"); String prefresh = request.getParameter("refresh"); String ptimestamp = request.getParameter("timestamp"); String pthreaded = request.getParameter("threaded"); String pthreadaction = request.getParameter("threadaction"); String pthreadactionuid = request.getParameter("threadactionuid"); QueryObj queryObj = null;/*from w w w . j a v a2 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(" "); 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
private String getJSTagsArray(Flags flags) { ArrayList<Tag> tags = null; String svtags = null;/* w ww .ja va2s. co m*/ if (flags != null) { for (Tag tag : atags) { if (flags.contains(tag.getTagId())) { if (tags == null) tags = new ArrayList<>(); tags.add(tag); } } if (tags != null) { for (Tag tag : tags) { if (svtags == null) svtags = "[ "; else svtags += ","; svtags += "'" + StringEscapeUtils.escapeEcmaScript(tag.getTagId()) + "'"; } if (svtags != null) svtags += " ]"; } } return svtags; }
From source file:com.sonicle.webtop.mail.Service.java
public void 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 . j a va 2s .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 processRunAdvancedSearch(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {/*from w w w .j a v a 2 s .co m*/ try { if (ast != null && ast.isRunning()) { throw new Exception("Advanced search is still running!"); } MailAccount account = getAccount(request); String folder = request.getParameter("folder"); String strashspam = request.getParameter("trashspam"); String ssubfolders = request.getParameter("subfolders"); String sandor = request.getParameter("andor"); String sentries[] = request.getParameterValues("entries"); boolean subfolders = ssubfolders.equals("true"); boolean trashspam = strashspam.equals("true"); boolean and = sandor.equals("and"); AdvancedSearchEntry entries[] = new AdvancedSearchEntry[sentries.length]; for (int i = 0; i < sentries.length; ++i) { entries[i] = new AdvancedSearchEntry(sentries[i]); } if (folder.startsWith("folder:")) { folder = folder.substring(7); ast = new AdvancedSearchThread(this, account, folder, trashspam, subfolders, and, entries); } else { int folderType = folder.equals("personal") ? AdvancedSearchThread.FOLDERTYPE_PERSONAL : folder.equals("shared") ? AdvancedSearchThread.FOLDERTYPE_SHARED : AdvancedSearchThread.FOLDERTYPE_ALL; ast = new AdvancedSearchThread(this, account, folderType, trashspam, subfolders, and, entries); } ast.start(); out.println("{\nresult: true\n}"); } catch (Exception exc) { Service.logger.error("Exception", exc); out.println("{\nresult: false, text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}"); } }