Example usage for javax.mail Part getInputStream

List of usage examples for javax.mail Part getInputStream

Introduction

In this page you can find the example usage for javax.mail Part getInputStream.

Prototype

public InputStream getInputStream() throws IOException, MessagingException;

Source Link

Document

Return an input stream for this part's "content".

Usage

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

public void processSaveFileToCloud(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {/*from w w w.ja v  a2 s.c om*/
        MailAccount account = getAccount(request);
        String path = ServletUtils.getStringParameter(request, "path", true);
        String fileId = ServletUtils.getStringParameter(request, "fileId", true);
        int storeId = ServletUtils.getIntParameter(request, "storeId", true);
        String folder = ServletUtils.getStringParameter(request, "folder", true);
        int idAttach = ServletUtils.getIntParameter(request, "idAttach", true);
        int idMessage = ServletUtils.getIntParameter(request, "idMessage", true);

        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(folder);
        Message m = mcache.getMessage(idMessage);
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = mailData.getAttachmentPart(idAttach);
        String fileName = part.getFileName();
        InputStream is = part.getInputStream();

        vfsmanager.addStoreFileFromStream(storeId, path, fileName, is);

        MapItem data = new MapItem();
        data.add("success", true);
        new JsonResult(data).printTo(out);
    } catch (Exception ex) {
        Service.logger.error("Exception", ex);
        new JsonResult(false, ex.getMessage()).printTo(out);
    }

}

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

public void processCalendarRequest(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pcalaction = request.getParameter("calaction");
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pidattach = request.getParameter("idattach");
    try {/*from   w w w  .  j  a  va  2 s.c o m*/
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(pfoldername);
        long newmsguid = Long.parseLong(puidmessage);
        Message m = mcache.getMessage(newmsguid);
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach));

        ICalendarRequest ir = new ICalendarRequest(part.getInputStream());
        ICalendarManager cm = (ICalendarManager) WT.getServiceManager("com.sonicle.webtop.calendar", true,
                environment.getProfileId());
        if (pcalaction.equals("accept")) {
            Event ev = cm.addEventFromICal(cm.getBuiltInCalendar().getCalendarId(), ir.getCalendar());
            String ekey = cm.getEventInstanceKey(ev.getEventId());
            sendICalendarReply(account, ir, ((InternetAddress) m.getRecipients(RecipientType.TO)[0]),
                    PartStat.ACCEPTED);
            new JsonResult(ekey).printTo(out);

        } else if (pcalaction.equals("import")) {
            Event ev = cm.addEventFromICal(cm.getBuiltInCalendar().getCalendarId(), ir.getCalendar());
            String ekey = cm.getEventInstanceKey(ev.getEventId());
            new JsonResult(ekey).printTo(out);

        } else if (pcalaction.equals("cancel") || pcalaction.equals("update")) {
            cm.updateEventFromICal(ir.getCalendar());
            new JsonResult().printTo(out);

        } else {
            throw new Exception("Unsupported calendar request action : " + pcalaction);
        }
    } catch (Exception exc) {
        new JsonResult(exc).printTo(out);
        logger.error("Error sending " + pcalaction, exc);
    }
}

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

public void processGetContactFromVCard(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {//  w  ww  .ja va2  s.c o m
    try {
        String folder = ServletUtils.getStringParameter(request, "folder", true);
        int messageId = ServletUtils.getIntParameter(request, "messageId", true);
        int attachId = ServletUtils.getIntParameter(request, "attachId", true);
        String uploadTag = ServletUtils.getStringParameter(request, "uploadTag", true);

        MailAccount account = getAccount(request);
        account.checkStoreConnected();
        FolderCache mcache = account.getFolderCache(folder);
        Message m = mcache.getMessage(messageId);
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = mailData.getAttachmentPart(attachId);
        String filename = MailUtils.getPartFilename(part);

        InputStream is = part.getInputStream();
        try {
            List<ContactInput> results = new VCardInput().fromVCardFile(is, null);
            ContactInput ci = results.get(0);

            JsContactData js = new JsContactData(ci.contact);

            if (ci.contact.hasPicture()) {
                ContactPictureWithBytes picture = (ContactPictureWithBytes) ci.contact.getPicture();
                WebTopSession.UploadedFile upl = null;
                ByteArrayInputStream bais = null;
                try {
                    bais = new ByteArrayInputStream(picture.getBytes());
                    upl = addAsUploadedFile("com.sonicle.webtop.contacts", uploadTag,
                            StringUtils.defaultIfBlank(filename, "idAttach"), "text/vcard", bais);
                } finally {
                    IOUtils.closeQuietly(bais);
                }
                if (upl != null)
                    js.picture = upl.getUploadId();
            }
            new JsonResult(js).printTo(out);

        } finally {
            IOUtils.closeQuietly(is);
        }

    } catch (Exception ex) {
        Service.logger.error("Exception", ex);
        new JsonResult(ex).printTo(out);
    }
}

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

public void processAttachFromMail(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    try {/*  w  ww  .  ja v  a  2s  .c  o  m*/
        MailAccount account = getAccount(request);
        account.checkStoreConnected();

        String tag = request.getParameter("tag");
        String pfoldername = request.getParameter("folder");
        String puidmessage = request.getParameter("idmessage");
        String pidattach = request.getParameter("idattach");

        FolderCache mcache = account.getFolderCache(pfoldername);
        long uidmessage = Long.parseLong(puidmessage);
        Message m = mcache.getMessage(uidmessage);
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = mailData.getAttachmentPart(Integer.parseInt(pidattach));

        String ctype = part.getContentType();
        int ix = ctype.indexOf(";");
        if (ix > 0) {
            ctype = ctype.substring(0, ix);
        }

        String filename = part.getFileName();
        if (filename == null) {
            filename = "";
        }
        try {
            filename = MailUtils.decodeQString(filename);
        } catch (Exception exc) {
        }

        ctype = ServletHelper.guessMediaType(filename, ctype);

        File file = WT.createTempFile();
        int filesize = IOUtils.copy(part.getInputStream(), new FileOutputStream(file));
        WebTopSession.UploadedFile uploadedFile = new WebTopSession.UploadedFile(false, this.SERVICE_ID,
                file.getName(), tag, filename, filesize, ctype);
        environment.getSession().addUploadedFile(uploadedFile);

        MapItem data = new MapItem(); // Empty response data
        data.add("uploadId", uploadedFile.getUploadId());
        data.add("name", uploadedFile.getFilename());
        data.add("size", uploadedFile.getSize());
        data.add("editable", isFileEditableInDocEditor(filename));
        new JsonResult(data).printTo(out);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
        new JsonResult(false, exc.getMessage()).printTo(out);
    }
}

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 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 w  w w . j a v  a2 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 processGetForwardMessage(HttpServletRequest request, HttpServletResponse response,
        PrintWriter out) {// w ww . jav  a  2s . c om
    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 processGetAttachments(HttpServletRequest request, HttpServletResponse response) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puidmessage = request.getParameter("idmessage");
    String pids[] = request.getParameterValues("ids");
    String providername = request.getParameter("provider");
    String providerid = request.getParameter("providerid");

    try {//from   w w w .ja  v a  2 s  .c om
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        String name = m.getSubject();
        if (name == null) {
            name = "attachments";
        }
        try {
            name = MailUtils.decodeQString(name);
        } catch (Exception exc) {
        }
        name += ".zip";
        //prepare hashmap to hold already used pnames
        HashMap<String, String> pnames = new HashMap<String, String>();
        ServletUtils.setFileStreamHeaders(response, "application/x-zip-compressed", DispositionType.INLINE,
                name);
        JarOutputStream jos = new java.util.jar.JarOutputStream(response.getOutputStream());
        byte[] b = new byte[64 * 1024];
        for (String pid : pids) {
            Part part = mailData.getAttachmentPart(Integer.parseInt(pid));
            String pname = part.getFileName();
            if (pname == null) {
                pname = "unknown";
            }
            /*
            try {
               pname = MailUtils.decodeQString(pname, "iso-8859-1");
            } catch (Exception exc) {
            }
            */
            //keep name and extension
            String bpname = pname;
            String extpname = null;
            int ix = pname.lastIndexOf(".");
            if (ix > 0) {
                bpname = pname.substring(0, ix);
                extpname = pname.substring(ix + 1);
            }
            //check for existing pname and find an unused name
            int xid = 0;
            String rpname = pname;
            while (pnames.containsKey(rpname)) {
                rpname = bpname + " (" + (++xid) + ")";
                if (extpname != null)
                    rpname += "." + extpname;
            }

            JarEntry je = new JarEntry(rpname);
            jos.putNextEntry(je);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen()) {
                    folder.open(Folder.READ_ONLY);
                }
            }
            InputStream is = part.getInputStream();
            int len = 0;
            while ((len = is.read(b)) != -1) {
                jos.write(b, 0, len);
            }
            is.close();

            //remember used pname
            pnames.put(rpname, rpname);
        }
        jos.closeEntry();
        jos.flush();
        jos.close();

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}

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

public void processGetAttachment(HttpServletRequest request, HttpServletResponse response) {
    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 pcid = request.getParameter("cid");
    String purl = request.getParameter("url");
    String punknown = request.getParameter("unknown");
    String psaveas = request.getParameter("saveas");

    try {/*from   w w  w  . ja v  a2s  .c  om*/
        account.checkStoreConnected();
        FolderCache mcache = null;
        Message m = null;
        if (providername == null) {
            mcache = account.getFolderCache(pfoldername);
            long newmsguid = Long.parseLong(puidmessage);
            m = mcache.getMessage(newmsguid);
        } else {
            mcache = fcProvided;
            m = mcache.getProvidedMessage(providername, providerid);
        }
        IMAPMessage im = (IMAPMessage) m;
        im.setPeek(us.isManualSeen());
        HTMLMailData mailData = mcache.getMailData((MimeMessage) m);
        Part part = null;
        if (pcid != null) {
            part = mailData.getCidPart(pcid);
        } else if (purl != null) {
            part = mailData.getUrlPart(purl);
        } else if (pidattach != null) {
            part = mailData.getAttachmentPart(Integer.parseInt(pidattach));
        } else if (punknown != null) {
            part = mailData.getUnknownPart(Integer.parseInt(punknown));
        }

        //boolean wasseen = m.isSet(Flags.Flag.SEEN);
        if (part != null) {
            String ctype = "binary/octet-stream";
            if (psaveas == null) {
                ctype = part.getContentType();
                int ix = ctype.indexOf(";");
                if (ix > 0)
                    ctype = ctype.substring(0, ix);
            }
            String name = part.getFileName();
            if (name == null)
                name = "";
            try {
                name = MailUtils.decodeQString(name);
            } catch (Exception exc) {
            }
            name = name.trim();
            if (psaveas == null) {
                int ix = name.lastIndexOf(".");
                if (ix > 0) {
                    //String ext=name.substring(ix+1);
                    String xctype = ServletHelper.guessMediaType(name);
                    if (xctype != null)
                        ctype = xctype;
                }
            }
            ServletUtils.setFileStreamHeaders(response, ctype, DispositionType.INLINE, name);
            if (providername == null) {
                Folder folder = mailData.getFolder();
                if (!folder.isOpen())
                    folder.open(Folder.READ_ONLY);
            }
            InputStream is = part.getInputStream();
            OutputStream out = response.getOutputStream();
            fastStreamCopy(is, out);
            is.close();
            out.close();
            //if(!wasseen){
            //   if (us.isManualSeen()) {
            //   m.setFlag(Flags.Flag.SEEN, false);
            //   }
            //}
        }
        im.setPeek(false);

    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
}