Search in sources :

Example 16 with ContentType

use of com.zimbra.common.mime.ContentType in project zm-mailbox by Zimbra.

the class ParseMimeMessageTest method attachPdfDocument.

@Test
public void attachPdfDocument() throws Exception {
    Account acct = Provisioning.getInstance().getAccount(MockProvisioning.DEFAULT_ACCOUNT_ID);
    Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(acct);
    OperationContext octxt = new OperationContext(acct);
    Document doc = mbox.createDocument(octxt, Mailbox.ID_FOLDER_BRIEFCASE, "testdoc", MimeConstants.CT_APPLICATION_PDF, "author", "description", new ByteArrayInputStream("test123".getBytes()));
    Element el = new Element.JSONElement(MailConstants.E_MSG);
    el.addAttribute(MailConstants.E_SUBJECT, "attach message");
    el.addElement(MailConstants.E_EMAIL).addAttribute(MailConstants.A_ADDRESS_TYPE, EmailType.TO.toString()).addAttribute(MailConstants.A_ADDRESS, "rcpt@zimbra.com");
    el.addElement(MailConstants.E_MIMEPART).addAttribute(MailConstants.A_CONTENT_TYPE, "text/plain").addAttribute(MailConstants.E_CONTENT, "This is the content.");
    el.addElement(MailConstants.E_ATTACH).addElement(MailConstants.E_DOC).addAttribute(MailConstants.A_ID, doc.getId());
    ZimbraSoapContext zsc = getMockSoapContext();
    MimeMessage mm = ParseMimeMessage.parseMimeMsgSoap(zsc, octxt, null, el, null, new ParseMimeMessage.MimeMessageData());
    MimeMultipart mmp = (MimeMultipart) mm.getContent();
    MimeBodyPart part = (MimeBodyPart) mmp.getBodyPart(1);
    Assert.assertEquals(MimeConstants.CT_APPLICATION_PDF, new ContentType(part.getContentType()).getContentType());
}
Also used : OperationContext(com.zimbra.cs.mailbox.OperationContext) Account(com.zimbra.cs.account.Account) ContentType(com.zimbra.common.mime.ContentType) Element(com.zimbra.common.soap.Element) Document(com.zimbra.cs.mailbox.Document) Mailbox(com.zimbra.cs.mailbox.Mailbox) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) ZimbraSoapContext(com.zimbra.soap.ZimbraSoapContext) MimeBodyPart(javax.mail.internet.MimeBodyPart) Test(org.junit.Test)

Example 17 with ContentType

use of com.zimbra.common.mime.ContentType in project zm-mailbox by Zimbra.

the class Get method handle.

@Override
public void handle(DavContext ctxt) throws DavException, IOException, ServiceException {
    DavResource resource = ctxt.getRequestedResource();
    HttpServletResponse resp = ctxt.getResponse();
    String contentType = resource.getContentType(ctxt);
    if (contentType != null) {
        ContentType ct = new ContentType(contentType);
        if (ct.getParameter(MimeConstants.P_CHARSET) == null)
            ct.setParameter(MimeConstants.P_CHARSET, MimeConstants.P_CHARSET_UTF8);
        resp.setContentType(ct.toString());
    }
    if (resource.hasEtag()) {
        ctxt.getResponse().setHeader(DavProtocol.HEADER_ETAG, resource.getEtag());
        ctxt.getResponse().setHeader(ETagHeaderFilter.ZIMBRA_ETAG_HEADER, resource.getEtag());
    }
    // resp.setContentLength(resource.getContentLength());
    if (!returnContent() || !resource.hasContent(ctxt))
        return;
    resp.setHeader("Content-Disposition", "attachment");
    ByteUtil.copy(resource.getContent(ctxt), true, ctxt.getResponse().getOutputStream(), false);
    resp.setStatus(ctxt.getStatus());
    ctxt.responseSent();
    if (ZimbraLog.dav.isDebugEnabled()) {
        StringBuilder sb = new StringBuilder("Response for DAV GET ").append(ctxt.getUri()).append("\n");
        if (contentType != null && contentType.startsWith("text")) {
            DavServlet.addResponseHeaderLoggingInfo(resp, sb);
            if (ZimbraLog.dav.isTraceEnabled()) {
                sb.append(new String(ByteUtil.getContent(resource.getContent(ctxt), 0), "UTF-8"));
            }
            ZimbraLog.dav.debug(sb);
        }
    }
}
Also used : DavResource(com.zimbra.cs.dav.resource.DavResource) ContentType(com.zimbra.common.mime.ContentType) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 18 with ContentType

use of com.zimbra.common.mime.ContentType in project zm-mailbox by Zimbra.

the class FileUploadServlet method handlePlainUpload.

/**
 * This is used when handling a POST request generated by {@link ZMailbox#uploadContentAsStream}
 *
 * @param req
 * @param resp
 * @param fmt
 * @param acct
 * @param limitByFileUploadMaxSize
 * @return
 * @throws IOException
 * @throws ServiceException
 */
List<Upload> handlePlainUpload(HttpServletRequest req, HttpServletResponse resp, String fmt, Account acct, boolean limitByFileUploadMaxSize) throws IOException, ServiceException {
    // metadata is encoded in the response's HTTP headers
    ContentType ctype = new ContentType(req.getContentType());
    String contentType = ctype.getContentType(), filename = ctype.getParameter("name");
    if (filename == null) {
        filename = new ContentDisposition(req.getHeader("Content-Disposition")).getParameter("filename");
    }
    if (filename == null || filename.trim().equals("")) {
        mLog.info("Rejecting upload with no name.");
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_NO_CONTENT, fmt, null, null, null);
        return Collections.emptyList();
    }
    // Unescape the filename so it actually displays correctly
    filename = StringEscapeUtils.unescapeHtml(filename);
    // store the fetched file as a normal upload
    ServletFileUpload upload = getUploader2(limitByFileUploadMaxSize);
    FileItem fi = upload.getFileItemFactory().createItem("upload", contentType, false, filename);
    try {
        // write the upload to disk, but make sure not to exceed the permitted max upload size
        long size = ByteUtil.copy(req.getInputStream(), false, fi.getOutputStream(), true, upload.getSizeMax() * 3);
        if ((upload.getSizeMax() >= 0) && (size > upload.getSizeMax())) {
            mLog.debug("handlePlainUpload(): deleting %s", fi);
            fi.delete();
            mLog.info("Exceeded maximum upload size of " + upload.getSizeMax() + " bytes: " + acct.getId());
            drainRequestStream(req);
            sendResponse(resp, HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, fmt, null, null, null);
            return Collections.emptyList();
        }
    } catch (IOException ioe) {
        mLog.warn("Unable to store upload.  Deleting %s", fi, ioe);
        fi.delete();
        drainRequestStream(req);
        sendResponse(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, fmt, null, null, null);
        return Collections.emptyList();
    }
    List<FileItem> items = new ArrayList<FileItem>(1);
    items.add(fi);
    Upload up = new Upload(acct.getId(), fi, filename);
    if (filename.endsWith(".har")) {
        File file = ((DiskFileItem) fi).getStoreLocation();
        try {
            Tika tika = new Tika();
            String mimeType = tika.detect(file);
            if (mimeType != null) {
                up.contentType = mimeType;
            }
        } catch (IOException e) {
            mLog.warn("Failed to detect file content type");
        }
    }
    mLog.info("Received plain: %s", up);
    synchronized (mPending) {
        mPending.put(up.uuid, up);
    }
    List<Upload> uploads = Arrays.asList(up);
    sendResponse(resp, HttpServletResponse.SC_OK, fmt, null, uploads, items);
    return uploads;
}
Also used : ContentType(com.zimbra.common.mime.ContentType) ArrayList(java.util.ArrayList) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) IOException(java.io.IOException) Tika(org.apache.tika.Tika) FileItem(org.apache.commons.fileupload.FileItem) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) ContentDisposition(com.zimbra.common.mime.ContentDisposition) File(java.io.File) DiskFileItem(org.apache.commons.fileupload.disk.DiskFileItem)

Example 19 with ContentType

use of com.zimbra.common.mime.ContentType in project zm-mailbox by Zimbra.

the class SaveDocument method fetchMimePart.

private Doc fetchMimePart(OperationContext octxt, AuthToken authtoken, ItemId itemId, String partId, String name, String ct, String description) throws ServiceException {
    String accountId = itemId.getAccountId();
    Account acct = Provisioning.getInstance().get(AccountBy.id, accountId);
    if (Provisioning.onLocalServer(acct)) {
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(acct);
        Message msg = mbox.getMessageById(octxt, itemId.getId());
        try {
            return new Doc(Mime.getMimePart(msg.getMimeMessage(), partId), name, ct);
        } catch (MessagingException e) {
            throw ServiceException.RESOURCE_UNREACHABLE("can't fetch mime part msgId=" + itemId + ", partId=" + partId, e);
        } catch (IOException e) {
            throw ServiceException.RESOURCE_UNREACHABLE("can't fetch mime part msgId=" + itemId + ", partId=" + partId, e);
        }
    }
    String url = UserServlet.getRestUrl(acct) + "?auth=co&id=" + itemId + "&part=" + partId;
    HttpClientBuilder clientBuilder = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HttpGet get = new HttpGet(url);
    authtoken.encode(clientBuilder, get, false, acct.getAttr(ZAttrProvisioning.A_zimbraMailHost));
    HttpClient client = clientBuilder.build();
    try {
        HttpResponse httpResp = HttpClientUtil.executeMethod(client, get);
        int statusCode = httpResp.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw ServiceException.RESOURCE_UNREACHABLE("can't fetch remote mime part", null, new InternalArgument(ServiceException.URL, url, Argument.Type.STR));
        }
        Header ctHeader = httpResp.getFirstHeader("Content-Type");
        ContentType contentType = new ContentType(ctHeader.getValue());
        return new Doc(httpResp.getEntity().getContent(), contentType, name, ct, description);
    } catch (HttpException e) {
        throw ServiceException.PROXY_ERROR(e, url);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("can't fetch remote mime part", e, new InternalArgument(ServiceException.URL, url, Argument.Type.STR));
    }
}
Also used : Account(com.zimbra.cs.account.Account) Message(com.zimbra.cs.mailbox.Message) ContentType(com.zimbra.common.mime.ContentType) MessagingException(javax.mail.MessagingException) HttpGet(org.apache.http.client.methods.HttpGet) InternalArgument(com.zimbra.common.service.ServiceException.InternalArgument) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpClientBuilder(org.apache.http.impl.client.HttpClientBuilder) Mailbox(com.zimbra.cs.mailbox.Mailbox) Header(org.apache.http.Header) HttpClient(org.apache.http.client.HttpClient) HttpException(org.apache.http.HttpException)

Example 20 with ContentType

use of com.zimbra.common.mime.ContentType in project zm-mailbox by Zimbra.

the class CreateContact method fetchItemPart.

static String fetchItemPart(ZimbraSoapContext zsc, OperationContext octxt, Mailbox mbox, ItemId iid, String part, String[] acceptableMimeTypes, String charsetWanted) throws ServiceException {
    String text = null;
    try {
        if (iid.isLocal()) {
            // fetch from local store
            if (!mbox.getAccountId().equals(iid.getAccountId())) {
                mbox = MailboxManager.getInstance().getMailboxByAccountId(iid.getAccountId());
            }
            Message msg = mbox.getMessageById(octxt, iid.getId());
            MimePart mp = Mime.getMimePart(msg.getMimeMessage(), part);
            String ctype = new ContentType(mp.getContentType()).getContentType();
            String fname = mp.getFileName();
            if (fname != null && (MimeConstants.CT_APPLICATION_OCTET_STREAM.equals(ctype) || MimeConstants.CT_APPLICATION_TNEF.equals(ctype))) {
                String guess = MimeDetect.getMimeDetect().detect(fname);
                if (guess != null) {
                    ctype = guess;
                }
            }
            boolean typeAcceptable;
            if (acceptableMimeTypes != null) {
                typeAcceptable = false;
                for (String type : acceptableMimeTypes) {
                    if (type != null && type.equalsIgnoreCase(ctype)) {
                        typeAcceptable = true;
                        break;
                    }
                }
            } else {
                typeAcceptable = true;
            }
            if (!typeAcceptable)
                throw MailServiceException.INVALID_CONTENT_TYPE(ctype);
            text = Mime.getStringContent(mp, charsetWanted);
        } else {
            // fetch from remote store
            Map<String, String> params = new HashMap<String, String>();
            params.put(UserServlet.QP_PART, part);
            byte[] content = UserServlet.getRemoteContent(zsc.getAuthToken(), iid, params);
            text = new String(content, MimeConstants.P_CHARSET_UTF8);
        }
    } catch (IOException e) {
        throw ServiceException.FAILURE("error fetching message part: iid=" + iid + ", part=" + part, e);
    } catch (MessagingException e) {
        throw ServiceException.FAILURE("error fetching message part: iid=" + iid + ", part=" + part, e);
    }
    return text;
}
Also used : Message(com.zimbra.cs.mailbox.Message) ContentType(com.zimbra.common.mime.ContentType) HashMap(java.util.HashMap) MessagingException(javax.mail.MessagingException) MimePart(javax.mail.internet.MimePart) IOException(java.io.IOException)

Aggregations

ContentType (com.zimbra.common.mime.ContentType)20 MimeBodyPart (javax.mail.internet.MimeBodyPart)8 MimeMessage (javax.mail.internet.MimeMessage)8 ContentDisposition (com.zimbra.common.mime.ContentDisposition)7 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)6 Mailbox (com.zimbra.cs.mailbox.Mailbox)6 IOException (java.io.IOException)6 ServiceException (com.zimbra.common.service.ServiceException)5 InputStream (java.io.InputStream)5 Element (com.zimbra.common.soap.Element)4 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)4 MimeMultipart (javax.mail.internet.MimeMultipart)4 MimePart (javax.mail.internet.MimePart)4 Account (com.zimbra.cs.account.Account)3 Document (com.zimbra.cs.mailbox.Document)3 MailServiceException (com.zimbra.cs.mailbox.MailServiceException)3 Message (com.zimbra.cs.mailbox.Message)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 MessagingException (javax.mail.MessagingException)3 ZVCalendar (com.zimbra.common.calendar.ZCalendar.ZVCalendar)2