Search in sources :

Example 26 with SharedByteArrayInputStream

use of javax.mail.util.SharedByteArrayInputStream in project zm-mailbox by Zimbra.

the class ParsedMessage method init.

/**
     * Runs MIME mutators and converters, initializes {@link #mMimeMessage}, {@link #mExpandedMessage},
     * {@link #mFileInputStream} and {@link #mReceivedDate} based on message content.
     */
private void init(Long receivedDate, boolean indexAttachments) throws MessagingException, IOException {
    this.indexAttachments = indexAttachments;
    if (mimeMessage == null) {
        if (sharedStream == null) {
            throw new IOException("Content stream has not been initialized.");
        }
        if (!(sharedStream instanceof SharedInputStream)) {
            InputStream in = sharedStream;
            sharedStream = null;
            byte[] content = ByteUtil.getContent(in, 0);
            sharedStream = new SharedByteArrayInputStream(content);
        }
        mimeMessage = expandedMessage = new Mime.FixedMimeMessage(JMSession.getSession(), sharedStream);
    }
    // Run mutators.
    try {
        runMimeMutators();
    } catch (Exception e) {
        wasMutated = false;
        // Original stream has been read, so get a new one.
        mimeMessage = expandedMessage = new Mime.FixedMimeMessage(JMSession.getSession(), getRawInputStream());
    }
    if (wasMutated()) {
        // Original data is now invalid.
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        mimeMessage.writeTo(buffer);
        byte[] content = buffer.toByteArray();
        ByteUtil.closeStream(sharedStream);
        sharedStream = new SharedByteArrayInputStream(content);
        mimeMessage = expandedMessage = null;
        mimeMessage = expandedMessage = new Mime.FixedMimeMessage(JMSession.getSession(), sharedStream);
    }
    ExpandMimeMessage expand = new ExpandMimeMessage(mimeMessage);
    try {
        expand.expand();
        expandedMessage = expand.getExpanded();
    } catch (Exception e) {
        // roll back if necessary
        expandedMessage = mimeMessage;
        LOG.warn("exception while converting message; message will be analyzed unconverted", e);
    }
    // must set received-date before Lucene document is initialized
    if (receivedDate == null) {
        receivedDate = getZimbraDateHeader(mimeMessage);
    }
    setReceivedDate(receivedDate);
}
Also used : GZIPInputStream(java.util.zip.GZIPInputStream) SharedInputStream(javax.mail.internet.SharedInputStream) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) BlobInputStream(com.zimbra.cs.store.BlobInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SharedInputStream(javax.mail.internet.SharedInputStream) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MessagingException(javax.mail.MessagingException) ParseException(java.text.ParseException) AddressException(javax.mail.internet.AddressException) ServiceException(com.zimbra.common.service.ServiceException) IOException(java.io.IOException) ConversionException(com.zimbra.cs.convert.ConversionException) ObjectHandlerException(com.zimbra.cs.object.ObjectHandlerException) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream)

Example 27 with SharedByteArrayInputStream

use of javax.mail.util.SharedByteArrayInputStream 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 28 with SharedByteArrayInputStream

use of javax.mail.util.SharedByteArrayInputStream in project zm-mailbox by Zimbra.

the class ZMailboxUtil method addMessage.

private void addMessage(String folderId, String flags, String tags, long date, File file, boolean validate) throws ServiceException, IOException {
    //String aid = mMbox.uploadAttachments(new File[] {file}, 5000);
    // Buffering required for gzip check
    InputStream in = new BufferedInputStream(new FileInputStream(file));
    long sizeHint = -1;
    if (ByteUtil.isGzipped(in)) {
        in = new GZIPInputStream(in);
    } else {
        sizeHint = file.length();
    }
    byte[] data = ByteUtil.getContent(in, (int) sizeHint);
    if (validate && !EmailUtil.isRfc822Message(new ByteArrayInputStream(data))) {
        throw ZClientException.CLIENT_ERROR(file.getPath() + " does not contain a valid RFC 822 message", null);
    }
    try {
        if (date == -1) {
            MimeMessage mm = new ZMimeMessage(mSession, new SharedByteArrayInputStream(data));
            Date d = mm.getSentDate();
            if (d != null)
                date = d.getTime();
            else
                date = 0;
        }
    } catch (MessagingException e) {
        date = 0;
    }
    String id = mMbox.addMessage(folderId, flags, tags, date, data, false);
    stdout.format("%s (%s)%n", id, file.getPath());
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MessagingException(javax.mail.MessagingException) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) FileInputStream(java.io.FileInputStream) Date(java.util.Date) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) GZIPInputStream(java.util.zip.GZIPInputStream) BufferedInputStream(java.io.BufferedInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) MimeMessage(javax.mail.internet.MimeMessage) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage)

Example 29 with SharedByteArrayInputStream

use of javax.mail.util.SharedByteArrayInputStream in project zm-mailbox by Zimbra.

the class TestSpam method testSpam.

/**
     * Tests {@link Mime#isSpam}.
     */
@Test
public void testSpam() throws Exception {
    String coreContent = TestUtil.getTestMessage(NAME_PREFIX + " testSpam", USER_NAME, USER_NAME, null);
    MimeMessage msg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(coreContent.getBytes()));
    assertFalse("Msg should not be identified as spam", SpamHandler.isSpam(msg));
    // Test single-line spam header (common case)
    String headerName = prov.getConfig().getSpamHeader();
    String singleLineSpamContent = headerName + ": YES\r\n" + coreContent;
    msg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(singleLineSpamContent.getBytes()));
    assertTrue("Msg should be identified as spam", SpamHandler.isSpam(msg));
    // Test folded spam header (bug 24954).
    prov.getConfig().setSpamHeaderValue("spam.*");
    String folderSpamContent = headerName + ": spam, SpamAssassin (score=5.701, required 5,\r\n" + "   DCC_CHECK 1.37, FH_RELAY_NODNS 1.45, RATWARE_RCVD_PF 2.88)\r\n" + coreContent;
    msg = new ZMimeMessage(JMSession.getSession(), new SharedByteArrayInputStream(folderSpamContent.getBytes()));
    assertTrue("Msg should be identified as spam", SpamHandler.isSpam(msg));
}
Also used : ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) ZMimeMessage(com.zimbra.common.zmime.ZMimeMessage) MimeMessage(javax.mail.internet.MimeMessage) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) Test(org.junit.Test)

Example 30 with SharedByteArrayInputStream

use of javax.mail.util.SharedByteArrayInputStream in project zm-mailbox by Zimbra.

the class ZMimeParserTest method multipleContentTypes.

@Test
public void multipleContentTypes() throws Exception {
    ByteBuilder bb = new ByteBuilder(CharsetUtil.UTF_8);
    bb.append("Content-Type: text/plain\r\n");
    bb.append("From: <foo@example.com\r\n");
    bb.append("Subject: sample\r\n");
    bb.append("Content-Type: multipart/alternative; boundary=").append(BOUNDARY1).append("\r\n");
    bb.append("\r\n");
    bb.append("--").append(BOUNDARY1).append("\r\n");
    bb.append("Content-Type: text/plain\r\n");
    bb.append("\r\n");
    bb.append("foo!  bar!  loud noises\r\n\r\n");
    bb.append("--").append(BOUNDARY1).append("--\r\n");
    try {
        MimeMessage mm = new ZMimeMessage(getSession(), new SharedByteArrayInputStream(bb.toByteArray()));
        Assert.assertFalse("content isn't multipart", mm.getContent() instanceof MimeMultipart);
        Assert.assertEquals("text/plain", "text/plain", new ZContentType(mm.getContentType()).getBaseType());
    } catch (ClassCastException e) {
        Assert.fail("mishandled double Content-Type headers");
    }
}
Also used : ByteBuilder(com.zimbra.common.zmime.ZMimeUtility.ByteBuilder) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) SharedByteArrayInputStream(javax.mail.util.SharedByteArrayInputStream) Test(org.junit.Test)

Aggregations

SharedByteArrayInputStream (javax.mail.util.SharedByteArrayInputStream)61 MimeMessage (javax.mail.internet.MimeMessage)53 Test (org.junit.Test)47 ZMimeMessage (com.zimbra.common.zmime.ZMimeMessage)31 Session (javax.mail.Session)15 JMSession (com.zimbra.cs.util.JMSession)14 Transport (javax.mail.Transport)14 InputStream (java.io.InputStream)9 ParsedMessage (com.zimbra.cs.mime.ParsedMessage)7 ByteBuilder (com.zimbra.common.zmime.ZMimeUtility.ByteBuilder)6 Mailbox (com.zimbra.cs.mailbox.Mailbox)6 FixedMimeMessage (com.zimbra.cs.mime.Mime.FixedMimeMessage)6 MessagingException (javax.mail.MessagingException)6 ByteArrayInputStream (java.io.ByteArrayInputStream)5 MimeMultipart (javax.mail.internet.MimeMultipart)5 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)4 DeliveryOptions (com.zimbra.cs.mailbox.DeliveryOptions)4 Message (com.zimbra.cs.mailbox.Message)4 ParseMimeMessage (com.zimbra.cs.service.mail.ParseMimeMessage)4 SendMsgRequest (com.zimbra.soap.mail.message.SendMsgRequest)4