Search in sources :

Example 31 with NoSuchItemException

use of com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException in project zm-mailbox by Zimbra.

the class Mailbox method createTagInternal.

Tag createTagInternal(int tagId, String name, Color color, boolean listed) throws ServiceException {
    try {
        Tag tag = getTagByName(name);
        if (!listed) {
            // want an implicitly-created tag but there's already a listed tag, so just return it unchanged
            return tag;
        } else if (tag.isListed()) {
            // can't have two listed tags with the same name
            throw MailServiceException.ALREADY_EXISTS(name);
        }
        // promote an implicitly-created tag to a listed tag
        markItemCreated(tag);
        tag.setListed();
        if (!name.equals(tag.getName())) {
            tag.rename(name);
        }
        tag.setColor(color);
        return tag;
    } catch (NoSuchItemException nsie) {
        // no conflict, so just create the new tag as requested
        return Tag.create(this, getNextItemId(tagId), name, color, listed);
    }
}
Also used : AlterItemTag(com.zimbra.cs.redolog.op.AlterItemTag) CreateTag(com.zimbra.cs.redolog.op.CreateTag) DbTag(com.zimbra.cs.db.DbTag) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException)

Example 32 with NoSuchItemException

use of com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException in project zm-mailbox by Zimbra.

the class ContentServlet method getCommand.

private void getCommand(HttpServletRequest req, HttpServletResponse resp, AuthToken token) throws ServletException, IOException {
    ItemId iid = null;
    try {
        iid = new ItemId(req.getParameter(PARAM_MSGID), (String) null);
    } catch (ServiceException e) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errInvalidId, req));
        return;
    }
    String part = req.getParameter(PARAM_PART);
    String fmt = req.getParameter(PARAM_FORMAT);
    String dumpsterParam = req.getParameter(PARAM_DUMPSTER);
    boolean fromDumpster = dumpsterParam != null && !dumpsterParam.equals("0") && !dumpsterParam.equalsIgnoreCase("false");
    try {
        // need to proxy the fetch if the mailbox lives on another server
        if (!iid.isLocal()) {
            // wrong server; proxy to the right one...
            proxyServletRequest(req, resp, iid.getAccountId());
            return;
        }
        String authId = token.getAccountId();
        String accountId = iid.getAccountId() != null ? iid.getAccountId() : authId;
        AccountUtil.addAccountToLogContext(Provisioning.getInstance(), accountId, ZimbraLog.C_NAME, ZimbraLog.C_ID, token);
        if (!accountId.equalsIgnoreCase(authId))
            ZimbraLog.addToContext(ZimbraLog.C_AID, authId);
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(accountId);
        if (mbox == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errMailboxNotFound, req));
            return;
        }
        ZimbraLog.addMboxToContext(mbox.getId());
        MailItem item = mbox.getItemById(new OperationContext(token), iid.getId(), MailItem.Type.UNKNOWN, fromDumpster);
        if (item == null) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errMessageNotFound, req));
            return;
        }
        try {
            if (part == null) {
                // they want the entire message...
                boolean sync = "1".equals(req.getParameter(PARAM_SYNC));
                StringBuffer hdr = new StringBuffer();
                if (sync) {
                    // for sync, return metadata as headers to avoid extra SOAP round-trips
                    resp.addHeader("X-Zimbra-Tags", TagUtil.getTagIdString(item));
                    resp.addHeader("X-Zimbra-Tag-Names", TagUtil.encodeTags(item.getTags()));
                    resp.addHeader("X-Zimbra-Flags", item.getFlagString());
                    resp.addHeader("X-Zimbra-Received", Long.toString(item.getDate()));
                    resp.addHeader("X-Zimbra-Modified", Long.toString(item.getChangeDate()));
                    // also return metadata inline in the message content for now
                    hdr.append("X-Zimbra-Tags: ").append(TagUtil.getTagIdString(item)).append("\n");
                    hdr.append("X-Zimbra-Tag-Names: ").append(TagUtil.encodeTags(item.getTags()));
                    hdr.append("X-Zimbra-Flags: ").append(item.getFlagString()).append("\n");
                    hdr.append("X-Zimbra-Received: ").append(item.getDate()).append("\n");
                    hdr.append("X-Zimbra-Modified: ").append(item.getChangeDate()).append("\n");
                }
                if (item instanceof Message) {
                    Message msg = (Message) item;
                    if (sync) {
                        resp.addHeader("X-Zimbra-Conv", Integer.toString(msg.getConversationId()));
                        hdr.append("X-Zimbra-Conv: ").append(msg.getConversationId()).append("\n");
                        resp.getOutputStream().write(hdr.toString().getBytes());
                    }
                    resp.setContentType(MimeConstants.CT_TEXT_PLAIN);
                    InputStream is = msg.getContentStream();
                    ByteUtil.copy(is, true, resp.getOutputStream(), false);
                } else if (item instanceof CalendarItem) {
                    CalendarItem calItem = (CalendarItem) item;
                    if (sync) {
                        resp.getOutputStream().write(hdr.toString().getBytes());
                    }
                    resp.setContentType(MimeConstants.CT_TEXT_PLAIN);
                    if (iid.hasSubpart()) {
                        int invId = iid.getSubpartId();
                        MimeMessage mm = calItem.getSubpartMessage(invId);
                        if (mm == null) {
                            // Backward compatibility for pre-5.0.16 ZDesktop: Build a MIME message on the fly.
                            Invite[] invs = calItem.getInvites(invId);
                            if (invs != null && invs.length > 0) {
                                Invite invite = invs[0];
                                mm = CalendarMailSender.createCalendarMessage(invite);
                            }
                        }
                        if (mm != null)
                            mm.writeTo(resp.getOutputStream());
                    } else {
                        InputStream is = calItem.getRawMessage();
                        if (is != null)
                            ByteUtil.copy(is, true, resp.getOutputStream(), false);
                    }
                }
                return;
            } else {
                MimePart mp = null;
                if (item instanceof Message) {
                    mp = getMimePart((Message) item, part);
                } else {
                    CalendarItem calItem = (CalendarItem) item;
                    if (iid.hasSubpart()) {
                        MimeMessage mbp = calItem.getSubpartMessage(iid.getSubpartId());
                        if (mbp != null)
                            mp = Mime.getMimePart(mbp, part);
                    } else {
                        mp = getMimePart(calItem, part);
                    }
                }
                if (mp != null) {
                    String contentType = mp.getContentType();
                    if (contentType == null) {
                        contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM;
                    }
                    if (contentType.toLowerCase().startsWith(MimeConstants.CT_TEXT_HTML) && (FORMAT_DEFANGED_HTML.equals(fmt) || FORMAT_DEFANGED_HTML_NOT_IMAGES.equals(fmt))) {
                        sendbackDefangedHtml(mp, contentType, resp, fmt);
                    } else {
                        if (!isTrue(Provisioning.A_zimbraAttachmentsViewInHtmlOnly, mbox.getAccountId())) {
                            sendbackOriginalDoc(mp, contentType, req, resp);
                        } else {
                            req.setAttribute(ATTR_MIMEPART, mp);
                            req.setAttribute(ATTR_MSGDIGEST, item.getDigest());
                            req.setAttribute(ATTR_CONTENTURL, req.getRequestURL().toString());
                            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(CONVERSION_PATH);
                            dispatcher.forward(req, resp);
                        }
                    }
                    return;
                }
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST, L10nUtil.getMessage(MsgKey.errPartNotFound, req));
            }
        } catch (MessagingException e) {
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } catch (NoSuchItemException e) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, L10nUtil.getMessage(MsgKey.errNoSuchItem, req));
    } catch (ServiceException e) {
        returnError(resp, e);
    } finally {
        ZimbraLog.clearContext();
    }
/*
         out.println("hello world "+req.getParameter("id"));
         out.println("path info: "+req.getPathInfo());
         out.println("pathtrans: "+req.getPathTranslated());
         */
}
Also used : OperationContext(com.zimbra.cs.mailbox.OperationContext) Message(com.zimbra.cs.mailbox.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException) RequestDispatcher(javax.servlet.RequestDispatcher) CalendarItem(com.zimbra.cs.mailbox.CalendarItem) MailItem(com.zimbra.cs.mailbox.MailItem) ServiceException(com.zimbra.common.service.ServiceException) Mailbox(com.zimbra.cs.mailbox.Mailbox) MimeMessage(javax.mail.internet.MimeMessage) MimePart(javax.mail.internet.MimePart) Invite(com.zimbra.cs.mailbox.calendar.Invite)

Example 33 with NoSuchItemException

use of com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException in project zm-mailbox by Zimbra.

the class UserServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    UserServletContext context = null;
    ZimbraLog.clearContext();
    addRemoteIpToLoggingContext(req);
    try {
        context = createContext(req, resp, this);
        if (!checkAuthentication(context)) {
            sendError(context, req, resp, L10nUtil.getMessage(MsgKey.errMustAuthenticate, req));
            return;
        }
        checkTargetAccountStatus(context);
        if (proxyIfRemoteTargetAccount(req, resp, context)) {
            return;
        }
        // or basic auth, authAccount is set to anonymous account.
        if (context.getAuthAccount() != null) {
            ZimbraLog.addAccountNameToContext(context.getAuthAccount().getName());
        }
        doAuthGet(req, resp, context);
    } catch (ServiceException se) {
        if (se.getCode() == ServiceException.PERM_DENIED || se instanceof NoSuchItemException)
            sendError(context, req, resp, L10nUtil.getMessage(MsgKey.errNoSuchItem, req));
        else if (se.getCode() == AccountServiceException.MAINTENANCE_MODE || se.getCode() == AccountServiceException.ACCOUNT_INACTIVE)
            sendError(context, req, resp, se.getMessage());
        else
            throw new ServletException(se);
    } catch (UserServletException e) {
        // add check for ServiceException root cause?
        resp.sendError(e.getHttpStatusCode(), e.getMessage());
    } finally {
        ZimbraLog.clearContext();
    }
}
Also used : ServletException(javax.servlet.ServletException) AccountServiceException(com.zimbra.cs.account.AccountServiceException) ServiceException(com.zimbra.common.service.ServiceException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException)

Example 34 with NoSuchItemException

use of com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException in project zm-mailbox by Zimbra.

the class OctopusPatchFormatter method saveCallback.

// Formatter API
@Override
public void saveCallback(UserServletContext context, String contentType, Folder folder, String filename) throws IOException, ServiceException, UserServletException {
    log.info("Uploading patch for " + filename);
    if (filename == null) {
        throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST, "Missing filename");
    }
    MailItem item = null;
    Mailbox mbox = folder.getMailbox();
    try {
        item = mbox.getItemByPath(context.opContext, filename, folder.getId());
        if (!(item instanceof Document))
            throw new UserServletException(HttpServletResponse.SC_BAD_REQUEST, "cannot overwrite existing object at that path");
    } catch (NoSuchItemException e) {
        log.debug("No document found at " + filename + "(folder id=" + folder.getId() + "; will create new one");
    }
    PatchInputStream pis = null;
    PatchStore.IncomingPatch ip = null;
    try {
        ip = patchStore.createIncomingPatch(context.targetAccount.getId());
        int defaultFileId = 0;
        int defaultVersion = 0;
        if (item != null) {
            defaultFileId = item.getId();
            defaultVersion = item.getVersion();
        }
        pis = PatchInputStream.create(context.getRequestInputStream(), // the current (target) user's view
        context.targetMailbox, context.opContext, defaultFileId, defaultVersion, ip.getOutputStream(), ip.getManifest());
        String creator = context.getAuthAccount() == null ? null : context.getAuthAccount().getName();
        if (contentType == null) {
            contentType = MimeDetect.getMimeDetect().detect(filename);
            if (contentType == null)
                contentType = MimeConstants.CT_APPLICATION_OCTET_STREAM;
        }
        log.debug("Storing blob");
        Blob blob = StoreManager.getInstance().storeIncoming(pis);
        log.debug("Creating parsed document; filename=" + filename + ", contentType=" + contentType + ", creator=" + creator);
        ParsedDocument pd = new ParsedDocument(blob, filename, contentType, System.currentTimeMillis(), creator, context.req.getHeader("X-Zimbra-Description"), true);
        log.debug("Parsed document created " + filename);
        // scan upload for viruses
        StringBuffer info = new StringBuffer();
        UploadScanner.Result result = UploadScanner.acceptStream(pis, info);
        if (result == UploadScanner.REJECT)
            throw MailServiceException.UPLOAD_REJECTED(filename, info.toString());
        if (result == UploadScanner.ERROR)
            throw MailServiceException.SCAN_ERROR(filename);
        if (item == null) {
            log.debug("Creating new document " + filename);
            item = mbox.createDocument(context.opContext, folder.getId(), pd, MailItem.Type.DOCUMENT, 0);
        } else {
            log.debug("Creating new version of the document " + filename + ", current version: " + item.getVersion());
            item = mbox.addDocumentRevision(context.opContext, item.getId(), pd);
        }
        patchStore.acceptPatch(ip, item.getId(), item.getVersion());
        NativeFormatter.sendZimbraHeaders(context, context.resp, item);
    } catch (PatchException e) {
        log.error("Patch upload failed: " + e);
        patchStore.rejectPatch(ip);
        throw new UserServletException(HttpServletResponse.SC_CONFLICT, "patch cannot be applied, try uploading whole file", e);
    } finally {
        try {
            pis.close();
        } catch (Exception e) {
            log.error("Exception during PatchInputStream close, ignored: " + e);
        }
    }
}
Also used : Blob(com.zimbra.cs.store.Blob) UserServletException(com.zimbra.cs.service.UserServletException) PatchStore(com.zimbra.cs.octosync.store.PatchStore) Document(com.zimbra.cs.mailbox.Document) ParsedDocument(com.zimbra.cs.mime.ParsedDocument) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException) UploadScanner(com.zimbra.cs.service.mail.UploadScanner) PatchException(com.zimbra.cs.octosync.PatchException) ServletException(javax.servlet.ServletException) ServiceException(com.zimbra.common.service.ServiceException) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException) IOException(java.io.IOException) FileNotFoundException(java.io.FileNotFoundException) UserServletException(com.zimbra.cs.service.UserServletException) MailServiceException(com.zimbra.cs.mailbox.MailServiceException) MailItem(com.zimbra.cs.mailbox.MailItem) Mailbox(com.zimbra.cs.mailbox.Mailbox) ParsedDocument(com.zimbra.cs.mime.ParsedDocument) PatchInputStream(com.zimbra.cs.octosync.PatchInputStream) PatchException(com.zimbra.cs.octosync.PatchException)

Example 35 with NoSuchItemException

use of com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException in project zm-mailbox by Zimbra.

the class Mailbox method alterTag.

public void alterTag(OperationContext octxt, int[] itemIds, MailItem.Type type, String tagName, boolean addTag, TargetConstraint tcon) throws ServiceException {
    AlterItemTag redoRecorder = new AlterItemTag(mId, itemIds, type, tagName, addTag, tcon);
    boolean success = false;
    try {
        beginTransaction("alterTag", octxt, redoRecorder);
        setOperationTargetConstraint(tcon);
        Tag tag;
        try {
            tag = getTagByName(tagName);
        } catch (NoSuchItemException nsie) {
            if (tagName.startsWith(Tag.FLAG_NAME_PREFIX)) {
                throw nsie;
            }
            Tag.NormalizedTags ntags = new NormalizedTags(this, new String[] { tagName }, addTag);
            if (ntags.getTags().length == 0) {
                success = true;
                return;
            }
            tag = getTagByName(ntags.getTags()[0]);
        }
        alterTag(itemIds, type, tag, addTag);
        success = true;
    } finally {
        endTransaction(success);
    }
}
Also used : NormalizedTags(com.zimbra.cs.mailbox.Tag.NormalizedTags) AlterItemTag(com.zimbra.cs.redolog.op.AlterItemTag) CreateTag(com.zimbra.cs.redolog.op.CreateTag) DbTag(com.zimbra.cs.db.DbTag) NoSuchItemException(com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException) AlterItemTag(com.zimbra.cs.redolog.op.AlterItemTag)

Aggregations

NoSuchItemException (com.zimbra.cs.mailbox.MailServiceException.NoSuchItemException)50 Mailbox (com.zimbra.cs.mailbox.Mailbox)21 ServiceException (com.zimbra.common.service.ServiceException)20 MailServiceException (com.zimbra.cs.mailbox.MailServiceException)15 MailItem (com.zimbra.cs.mailbox.MailItem)11 Test (org.junit.Test)11 Account (com.zimbra.cs.account.Account)10 OperationContext (com.zimbra.cs.mailbox.OperationContext)10 ItemId (com.zimbra.cs.service.util.ItemId)10 Folder (com.zimbra.cs.mailbox.Folder)9 MimeMessage (javax.mail.internet.MimeMessage)8 Element (com.zimbra.common.soap.Element)7 Mountpoint (com.zimbra.cs.mailbox.Mountpoint)7 IOException (java.io.IOException)7 AccountServiceException (com.zimbra.cs.account.AccountServiceException)6 ParsedMessage (com.zimbra.cs.mime.ParsedMessage)6 ArrayList (java.util.ArrayList)6 DbMailItem (com.zimbra.cs.db.DbMailItem)5 DbTag (com.zimbra.cs.db.DbTag)5 Document (com.zimbra.cs.mailbox.Document)5