Search in sources :

Example 1 with Attachment

use of com.zimbra.cs.mailbox.Contact.Attachment in project zm-mailbox by Zimbra.

the class ContactAutoComplete method queryFolders.

private void queryFolders(String str, String generatedQuery, Map<ItemId, Mountpoint> mountpoints, int limit, AutoCompleteResult result) throws ServiceException {
    Mailbox mbox = MailboxManager.getInstance().getMailboxByAccountId(getRequestedAcctId());
    SearchParams params = new SearchParams();
    params.setQueryString(generatedQuery);
    params.setDefaultField("contact:");
    params.setTypes(CONTACT_TYPES);
    params.setSortBy(SortBy.NONE);
    params.setLimit(limit + 1);
    params.setPrefetch(true);
    params.setFetchMode(SearchParams.Fetch.NORMAL);
    ZimbraLog.gal.debug("querying contact folders: %s", params.getQueryString());
    try (ZimbraQueryResults qres = mbox.index.search(SoapProtocol.Soap12, octxt, params)) {
        while (qres.hasNext()) {
            ZimbraHit hit = qres.getNext();
            Map<String, String> fields = null;
            ItemId id = null;
            int fid = 0;
            if (hit instanceof ContactHit) {
                Contact c = ((ContactHit) hit).getContact();
                ZimbraLog.gal.debug("hit: %d", c.getId());
                fields = c.getFields();
                id = new ItemId(c);
                fid = c.getFolderId();
                if (returnFullContactData) {
                    List<Attachment> contactAttachments = c.getAttachments();
                    if (contactAttachments != null && contactAttachments.size() != 0) {
                        fields.put("image", c.getId() + "_" + contactAttachments.get(0).getName());
                    }
                }
            } else if (hit instanceof ProxiedHit) {
                fields = new HashMap<String, String>();
                Element top = ((ProxiedHit) hit).getElement();
                id = new ItemId(top.getAttribute(MailConstants.A_ID), (String) null);
                ZimbraLog.gal.debug("hit: %s", id);
                ItemId fiid = new ItemId(top.getAttribute(MailConstants.A_FOLDER), (String) null);
                Mountpoint mp = mountpoints.get(fiid);
                if (mp != null) {
                    // if the hit came from a descendant folder of
                    // the mountpoint, we don't have a peer folder ID.
                    fid = mp.getId();
                } else {
                    fid = FOLDER_ID_MOUNTPOINT_SUBFOLDER;
                }
                for (Element elt : top.listElements(MailConstants.E_ATTRIBUTE)) {
                    try {
                        String name = elt.getAttribute(MailConstants.A_ATTRIBUTE_NAME);
                        fields.put(name, elt.getText());
                    } catch (ServiceException se) {
                        ZimbraLog.gal.warn("error handling proxied query result " + hit);
                    }
                }
                if (returnFullContactData) {
                    if (fields.containsKey("image")) {
                        fields.put("image", id.getAccountId() + "_" + id.getId() + "_image");
                    }
                }
            } else {
                continue;
            }
            addMatchedContacts(str, fields, fid, id, result);
            if (!result.canBeCached) {
                return;
            }
        }
    } catch (IOException e) {
    }
}
Also used : ZimbraHit(com.zimbra.cs.index.ZimbraHit) GalSearchParams(com.zimbra.cs.gal.GalSearchParams) SearchParams(com.zimbra.cs.index.SearchParams) HashMap(java.util.HashMap) Element(com.zimbra.common.soap.Element) Attachment(com.zimbra.cs.mailbox.Contact.Attachment) IOException(java.io.IOException) ItemId(com.zimbra.cs.service.util.ItemId) GalContact(com.zimbra.cs.account.GalContact) ProxiedHit(com.zimbra.cs.index.ProxiedHit) ContactHit(com.zimbra.cs.index.ContactHit) ServiceException(com.zimbra.common.service.ServiceException) ZimbraQueryResults(com.zimbra.cs.index.ZimbraQueryResults)

Example 2 with Attachment

use of com.zimbra.cs.mailbox.Contact.Attachment in project zm-mailbox by Zimbra.

the class ParsedContact method modify.

public ParsedContact modify(FieldDeltaList fieldDeltaList, List<Attachment> attachDelta, boolean discardExistingMembers) throws ServiceException {
    if (attachDelta != null && !attachDelta.isEmpty()) {
        try {
            validateImageAttachments(attachDelta);
        } catch (IOException ioe) {
            throw MailServiceException.MESSAGE_PARSE_ERROR(ioe);
        }
        for (Attachment attach : attachDelta) {
            // make sure we don't have anything referenced in both fieldDelta and attachDelta
            fieldDeltaList.removeAllAttrDeltaByName(attach.getName());
            // add the new attachments to the contact
            removeAttachment(attach.getName());
            if (contactAttachments == null) {
                contactAttachments = new ArrayList<Attachment>(attachDelta.size());
            }
            contactAttachments.add(attach);
        }
    }
    ContactGroup contactGroup = null;
    String encodedContactGroup = contactFields.get(ContactConstants.A_groupMember);
    contactGroup = encodedContactGroup == null ? ContactGroup.init() : ContactGroup.init(encodedContactGroup);
    boolean contactGroupMemberChanged = false;
    if (discardExistingMembers && contactGroup.hasMembers()) {
        contactGroup.removeAllMembers();
        contactGroupMemberChanged = true;
    }
    for (FieldDelta delta : fieldDeltaList.getDeltaList()) {
        if (delta instanceof AttrDelta) {
            processAttrDelta((AttrDelta) delta);
        } else if (delta instanceof GroupMemberDelta) {
            processGroupMemberDelta((GroupMemberDelta) delta, contactGroup);
            contactGroupMemberChanged = true;
        }
    }
    if (contactFields.isEmpty())
        throw ServiceException.INVALID_REQUEST("contact must have fields", null);
    if (contactGroupMemberChanged) {
        contactFields.put(ContactConstants.A_groupMember, contactGroup.encode());
    }
    digest = null;
    indexDocs = null;
    if (contactAttachments != null) {
        try {
            mimeMessage = generateMimeMessage(contactAttachments);
            // Original stream is now stale.
            ByteUtil.closeStream(sharedStream);
            sharedStream = null;
            initializeSizeAndDigest();
        } catch (MessagingException me) {
            throw MailServiceException.MESSAGE_PARSE_ERROR(me);
        } catch (IOException e) {
            throw MailServiceException.MESSAGE_PARSE_ERROR(e);
        }
    } else {
        // No attachments.  Wipe out any previous reference to a blob.
        ByteUtil.closeStream(sharedStream);
        sharedStream = null;
        mimeMessage = null;
        size = 0;
        digest = null;
    }
    return this;
}
Also used : MessagingException(javax.mail.MessagingException) Attachment(com.zimbra.cs.mailbox.Contact.Attachment) IOException(java.io.IOException) ContactGroup(com.zimbra.cs.mailbox.ContactGroup)

Example 3 with Attachment

use of com.zimbra.cs.mailbox.Contact.Attachment in project zm-mailbox by Zimbra.

the class ParsedContact method generateMimeMessage.

private static MimeMessage generateMimeMessage(List<Attachment> attachments) throws MessagingException {
    MimeMessage mm = new Mime.FixedMimeMessage(JMSession.getSession());
    MimeMultipart multi = new ZMimeMultipart("mixed");
    int part = 1;
    for (Attachment attach : attachments) {
        ContentDisposition cdisp = new ContentDisposition(Part.ATTACHMENT);
        cdisp.setParameter("filename", attach.getFilename()).setParameter("field", attach.getName());
        MimeBodyPart bp = new ZMimeBodyPart();
        // it gets called before setting Content-Type and CTE headers.
        try {
            bp.setDataHandler(new DataHandler(new ByteArrayDataSource(attach.getContent(), attach.getContentType())));
        } catch (IOException e) {
            throw new MessagingException("could not generate mime part content", e);
        }
        bp.addHeader("Content-Disposition", cdisp.toString());
        bp.addHeader("Content-Type", attach.getContentType());
        bp.addHeader("Content-Transfer-Encoding", MimeConstants.ET_8BIT);
        multi.addBodyPart(bp);
        attach.setPartName(Integer.toString(part++));
    }
    mm.setContent(multi);
    mm.saveChanges();
    return mm;
}
Also used : ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MessagingException(javax.mail.MessagingException) Attachment(com.zimbra.cs.mailbox.Contact.Attachment) DataHandler(javax.activation.DataHandler) IOException(java.io.IOException) ContentDisposition(com.zimbra.common.mime.ContentDisposition) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) MimeMultipart(javax.mail.internet.MimeMultipart) ZMimeMultipart(com.zimbra.common.zmime.ZMimeMultipart) ZMimeBodyPart(com.zimbra.common.zmime.ZMimeBodyPart) MimeBodyPart(javax.mail.internet.MimeBodyPart) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource)

Example 4 with Attachment

use of com.zimbra.cs.mailbox.Contact.Attachment in project zm-mailbox by Zimbra.

the class ParsedContact method init.

private void init(Map<String, ? extends Object> fields, InputStream in) throws ServiceException {
    if (fields == null) {
        throw ServiceException.INVALID_REQUEST("contact must have fields", null);
    }
    // Initialized shared stream.
    try {
        if (in instanceof SharedInputStream) {
            sharedStream = in;
        } else if (in != null) {
            byte[] content = ByteUtil.getContent(in, 1024);
            sharedStream = new SharedByteArrayInputStream(content);
        }
    } catch (IOException e) {
        throw MailServiceException.MESSAGE_PARSE_ERROR(e);
    }
    // Initialize fields.
    Map<String, String> map = new HashMap<String, String>();
    for (Map.Entry<String, ? extends Object> entry : fields.entrySet()) {
        String key = StringUtil.stripControlCharacters(entry.getKey());
        String value = null;
        if (entry.getValue() instanceof String[]) {
            // encode multi value attributes as JSONObject
            try {
                value = Contact.encodeMultiValueAttr((String[]) entry.getValue());
            } catch (JSONException e) {
                ZimbraLog.index.warn("Error encoding multi valued attribute " + key, e);
            }
        } else if (entry.getValue() instanceof String) {
            value = StringUtil.stripControlCharacters((String) entry.getValue());
        } else if (entry.getValue() instanceof ContactGroup) {
            value = ((ContactGroup) entry.getValue()).encode();
        }
        if (key != null && !key.trim().isEmpty() && !Strings.isNullOrEmpty(value)) {
            if (key.length() > ContactConstants.MAX_FIELD_NAME_LENGTH) {
                throw ServiceException.INVALID_REQUEST("too big filed name", null);
            } else if (value.length() > ContactConstants.MAX_FIELD_VALUE_LENGTH) {
                throw MailServiceException.CONTACT_TOO_BIG(ContactConstants.MAX_FIELD_VALUE_LENGTH, value.length());
            }
            map.put(key, value);
        }
    }
    if (map.isEmpty()) {
        throw ServiceException.INVALID_REQUEST("contact must have fields", null);
    } else if (map.size() > ContactConstants.MAX_FIELD_COUNT) {
        throw ServiceException.INVALID_REQUEST("too many fields", null);
    }
    contactFields = map;
    // Initialize attachments.
    if (sharedStream != null) {
        InputStream contentStream = null;
        try {
            // Parse attachments.
            contentStream = getContentStream();
            contactAttachments = parseBlob(contentStream);
            for (Attachment attach : contactAttachments) {
                contactFields.remove(attach.getName());
            }
            initializeSizeAndDigest();
        } catch (MessagingException me) {
            throw MailServiceException.MESSAGE_PARSE_ERROR(me);
        } catch (IOException ioe) {
            throw MailServiceException.MESSAGE_PARSE_ERROR(ioe);
        } finally {
            ByteUtil.closeStream(contentStream);
        }
    }
}
Also used : HashMap(java.util.HashMap) MessagingException(javax.mail.MessagingException) SharedInputStream(javax.mail.internet.SharedInputStream) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) InputStream(java.io.InputStream) JSONException(org.json.JSONException) Attachment(com.zimbra.cs.mailbox.Contact.Attachment) IOException(java.io.IOException) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) SharedInputStream(javax.mail.internet.SharedInputStream) ContactGroup(com.zimbra.cs.mailbox.ContactGroup) HashMap(java.util.HashMap) Map(java.util.Map)

Example 5 with Attachment

use of com.zimbra.cs.mailbox.Contact.Attachment in project zm-mailbox by Zimbra.

the class ContactTest method createInvalidImageAttachment.

/**
 * Tests Invalid image attachment (bug 71868).
 */
@Test
public void createInvalidImageAttachment() throws Exception {
    // Create a contact with an attachment.
    Map<String, String> attrs = new HashMap<String, String>();
    attrs.put("fullName", "Get Attachment Content");
    byte[] attachData = "attachment 1".getBytes();
    Attachment attachment = new Attachment(attachData, "image/png", "image", "file1.png");
    try {
        ParsedContact pc = new ParsedContact(attrs, Lists.newArrayList(attachment));
        Assert.fail("Expected INVALID_IMAGE exception");
    } catch (ServiceException se) {
        Assert.assertEquals("check the INVALID_IMAGE exception", "mail.INVALID_IMAGE", se.getCode());
    }
}
Also used : ParsedContact(com.zimbra.cs.mime.ParsedContact) ServiceException(com.zimbra.common.service.ServiceException) HashMap(java.util.HashMap) Attachment(com.zimbra.cs.mailbox.Contact.Attachment) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test)

Aggregations

Attachment (com.zimbra.cs.mailbox.Contact.Attachment)19 HashMap (java.util.HashMap)9 ServiceException (com.zimbra.common.service.ServiceException)7 ParsedContact (com.zimbra.cs.mime.ParsedContact)6 IOException (java.io.IOException)6 Test (org.junit.Test)6 Element (com.zimbra.common.soap.Element)5 ItemId (com.zimbra.cs.service.util.ItemId)5 Account (com.zimbra.cs.account.Account)4 ArrayList (java.util.ArrayList)4 MessagingException (javax.mail.MessagingException)4 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)4 ContactGroup (com.zimbra.cs.mailbox.ContactGroup)3 MailServiceException (com.zimbra.cs.mailbox.MailServiceException)3 Mailbox (com.zimbra.cs.mailbox.Mailbox)3 DataHandler (javax.activation.DataHandler)3 MimeMessage (javax.mail.internet.MimeMessage)3 TimeZoneMap (com.zimbra.common.calendar.TimeZoneMap)2 ContentDisposition (com.zimbra.common.mime.ContentDisposition)2 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)2