Search in sources :

Example 86 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project rest.li by linkedin.

the class TestMIMEReaderExceptions method incorrectHeaderFormat.

@Test(dataProvider = "multiplePartsDataSource")
public void incorrectHeaderFormat(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception {
    //Use Javax to create a multipart payload. Then we just modify the location of the consecutive CRLFs.
    MimeMultipart multiPartMimeBody = new MimeMultipart();
    //Add your body parts
    for (final MimeBodyPart bodyPart : bodyPartList) {
        multiPartMimeBody.addBodyPart(bodyPart);
    }
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    multiPartMimeBody.writeTo(byteArrayOutputStream);
    final byte[] mimePayload = byteArrayOutputStream.toByteArray();
    final byte[] contentTypeColonBytes = (MultiPartMIMEUtils.CONTENT_TYPE_HEADER + ":").getBytes();
    for (int i = 0; i < mimePayload.length - contentTypeColonBytes.length; i++) {
        final byte[] currentWindow = Arrays.copyOfRange(mimePayload, i, i + contentTypeColonBytes.length);
        if (Arrays.equals(currentWindow, contentTypeColonBytes)) {
            mimePayload[i + currentWindow.length - 1] = 15;
            break;
        }
    }
    final ByteString requestPayload = ByteString.copy(mimePayload);
    executeRequestWithDesiredException(requestPayload, chunkSize, multiPartMimeBody.getContentType(), "Malformed multipart mime request. Individual headers are improperly formatted.");
    //No single part readers should have been created.
    Assert.assertEquals(_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks().size(), 0);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteString(com.linkedin.data.ByteString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart) Test(org.testng.annotations.Test)

Example 87 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project rest.li by linkedin.

the class TestMIMEReaderExceptions method payloadMissingFinalBoundary.

@Test(dataProvider = "multiplePartsDataSource")
public void payloadMissingFinalBoundary(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception {
    MimeMultipart multiPartMimeBody = new MimeMultipart();
    //Add your body parts
    for (final MimeBodyPart bodyPart : bodyPartList) {
        multiPartMimeBody.addBodyPart(bodyPart);
    }
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    multiPartMimeBody.writeTo(byteArrayOutputStream);
    final byte[] mimePayload = byteArrayOutputStream.toByteArray();
    //To simulate the missing boundary, we have to trim 3 bytes off of the end. We need to snip the very last 2 bytes
    //because javax mail places a CRLF at the very end (which is not needed) and then another byte before that (which is a
    //hyphen) so that the final boundary never occurs.
    final byte[] trimmedMimePayload = Arrays.copyOf(mimePayload, mimePayload.length - 3);
    final ByteString requestPayload = ByteString.copy(trimmedMimePayload);
    executeRequestWithDesiredException(requestPayload, chunkSize, multiPartMimeBody.getContentType(), "Malformed multipart mime request. Finishing boundary missing!");
    List<SinglePartMIMEExceptionReaderCallbackImpl> singlePartMIMEReaderCallbacks = _currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
    Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), multiPartMimeBody.getCount());
    //The last one should have gotten a stream error
    for (int i = 0; i < singlePartMIMEReaderCallbacks.size() - 1; i++) {
        //Actual
        final SinglePartMIMEExceptionReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
        //Expected
        final BodyPart currentExpectedPart = multiPartMimeBody.getBodyPart(i);
        //Construct expected headers and verify they match
        final Map<String, String> expectedHeaders = new HashMap<String, String>();
        @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
        while (allHeaders.hasMoreElements()) {
            final Header header = allHeaders.nextElement();
            expectedHeaders.put(header.getName(), header.getValue());
        }
        Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
        //Verify the body matches
        Assert.assertNotNull(currentCallback.getFinishedData());
        if (currentExpectedPart.getContent() instanceof byte[]) {
            Assert.assertEquals(currentCallback.getFinishedData().copyBytes(), currentExpectedPart.getContent());
        } else {
            //Default is String
            Assert.assertEquals(new String(currentCallback.getFinishedData().copyBytes()), currentExpectedPart.getContent());
        }
    }
    SinglePartMIMEExceptionReaderCallbackImpl singlePartMIMEExceptionReaderCallback = singlePartMIMEReaderCallbacks.get(singlePartMIMEReaderCallbacks.size() - 1);
    Assert.assertNull(singlePartMIMEExceptionReaderCallback.getFinishedData());
    Assert.assertTrue(singlePartMIMEExceptionReaderCallback.getStreamError() instanceof MultiPartIllegalFormatException);
    try {
        singlePartMIMEExceptionReaderCallback.getSinglePartMIMEReader().requestPartData();
        Assert.fail();
    } catch (SinglePartFinishedException singlePartFinishedException) {
    //pass
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) HashMap(java.util.HashMap) ByteString(com.linkedin.data.ByteString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteString(com.linkedin.data.ByteString) SinglePartFinishedException(com.linkedin.multipart.exceptions.SinglePartFinishedException) Header(javax.mail.Header) MimeMultipart(javax.mail.internet.MimeMultipart) MultiPartIllegalFormatException(com.linkedin.multipart.exceptions.MultiPartIllegalFormatException) MimeBodyPart(javax.mail.internet.MimeBodyPart) Test(org.testng.annotations.Test)

Example 88 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project rest.li by linkedin.

the class TestMIMEReaderExceptions method prematureHeaderTermination.

@Test(dataProvider = "multiplePartsDataSource")
public void prematureHeaderTermination(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception {
    //Use Javax to create a multipart payload. Then we just modify the location of the consecutive CRLFs.
    MimeMultipart multiPartMimeBody = new MimeMultipart();
    //Add your body parts
    for (final MimeBodyPart bodyPart : bodyPartList) {
        multiPartMimeBody.addBodyPart(bodyPart);
    }
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    multiPartMimeBody.writeTo(byteArrayOutputStream);
    final byte[] mimePayload = byteArrayOutputStream.toByteArray();
    //Find where the consecutive CRLFs are after the occurrences of the headers and modify it
    for (int i = 0; i < mimePayload.length - 4; i++) {
        final byte[] currentWindow = Arrays.copyOfRange(mimePayload, i, i + 4);
        if (Arrays.equals(currentWindow, MultiPartMIMEUtils.CONSECUTIVE_CRLFS_BYTES)) {
            //Set a random byte.
            mimePayload[i] = 15;
        }
    }
    final ByteString requestPayload = ByteString.copy(mimePayload);
    executeRequestWithDesiredException(requestPayload, chunkSize, multiPartMimeBody.getContentType(), "Malformed multipart mime request. Premature termination of headers within a part.");
    //No single part readers should have been created.
    Assert.assertEquals(_currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks().size(), 0);
}
Also used : MimeMultipart(javax.mail.internet.MimeMultipart) ByteString(com.linkedin.data.ByteString) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MimeBodyPart(javax.mail.internet.MimeBodyPart) Test(org.testng.annotations.Test)

Example 89 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project rest.li by linkedin.

the class TestMIMEIntegrationReaderDrain method testSingleAlternateTopRemaining.

@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSingleAlternateTopRemaining(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception {
    //Execute the request, verify the correct header came back to ensure the server took the proper draining actions
    //and return the payload so we can assert deeper.
    MimeMultipart mimeMultipart = executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_ALTERNATE_TOP_REMAINING, "onDrainComplete");
    //Single part alternates between consumption and draining the first 6 parts, then top level drains all of remaining.
    //This means that parts 0, 2, 4 will be consumed and parts 1, 3, 5 will be drained.
    List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks = _mimeServerRequestDrainHandler.getTestMultiPartMIMEReaderCallback().getSinglePartMIMEReaderCallbacks();
    Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 6);
    //First the consumed
    for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i = i + 2) {
        //Actual

        final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
        //Expected

        final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i);
        //Construct expected headers and verify they match

        final Map<String, String> expectedHeaders = new HashMap<String, String>();
        @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
        while (allHeaders.hasMoreElements()) {
            final Header header = allHeaders.nextElement();
            expectedHeaders.put(header.getName(), header.getValue());
        }
        Assert.assertEquals(currentCallback._headers, expectedHeaders);
        //Verify the body matches
        if (currentExpectedPart.getContent() instanceof byte[]) {
            Assert.assertEquals(currentCallback._finishedData.copyBytes(), currentExpectedPart.getContent());
        } else {
            //Default is String
            Assert.assertEquals(new String(currentCallback._finishedData.copyBytes()), currentExpectedPart.getContent());
        }
    }
    //Then the drained
    for (int i = 1; i < singlePartMIMEReaderCallbacks.size(); i = i + 2) {
        //Actual

        final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
        //Expected

        final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i);
        //Construct expected headers and verify they match

        final Map<String, String> expectedHeaders = new HashMap<String, String>();
        @SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
        while (allHeaders.hasMoreElements()) {
            final Header header = allHeaders.nextElement();
            expectedHeaders.put(header.getName(), header.getValue());
        }
        Assert.assertEquals(currentCallback._headers, expectedHeaders);
        //Verify that the bodies are empty
        Assert.assertEquals(currentCallback._finishedData, ByteString.empty());
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Header(javax.mail.Header) MimeMultipart(javax.mail.internet.MimeMultipart) HashMap(java.util.HashMap) ByteString(com.linkedin.data.ByteString) Test(org.testng.annotations.Test)

Example 90 with MimeBodyPart

use of javax.mail.internet.MimeBodyPart in project rest.li by linkedin.

the class TestMIMEIntegrationReaderDrain method executeRequestWithDrainStrategy.

///////////////////////////////////////////////////////////////////////////////////////
private MimeMultipart executeRequestWithDrainStrategy(final int chunkSize, final List<MimeBodyPart> bodyPartList, final String drainStrategy, final String serverHeaderPrefix) throws Exception {
    MimeMultipart multiPartMimeBody = new MimeMultipart();
    //Add your body parts
    for (final MimeBodyPart bodyPart : bodyPartList) {
        multiPartMimeBody.addBodyPart(bodyPart);
    }
    final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    multiPartMimeBody.writeTo(byteArrayOutputStream);
    final ByteString requestPayload = ByteString.copy(byteArrayOutputStream.toByteArray());
    final VariableByteStringWriter variableByteStringWriter = new VariableByteStringWriter(requestPayload, chunkSize);
    final EntityStream entityStream = EntityStreams.newEntityStream(variableByteStringWriter);
    final StreamRequestBuilder builder = new StreamRequestBuilder(Bootstrap.createHttpURI(PORT, SERVER_URI));
    StreamRequest request = builder.setMethod("POST").setHeader(HEADER_CONTENT_TYPE, multiPartMimeBody.getContentType()).setHeader(DRAIN_HEADER, drainStrategy).build(entityStream);
    final AtomicInteger status = new AtomicInteger(-1);
    final CountDownLatch latch = new CountDownLatch(1);
    final Map<String, String> responseHeaders = new HashMap<String, String>();
    Callback<StreamResponse> callback = expectSuccessCallback(latch, status, responseHeaders);
    _client.streamRequest(request, callback);
    latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
    Assert.assertEquals(status.get(), RestStatus.OK);
    Assert.assertEquals(responseHeaders.get(DRAIN_HEADER), serverHeaderPrefix + drainStrategy);
    return multiPartMimeBody;
}
Also used : VariableByteStringWriter(com.linkedin.multipart.utils.VariableByteStringWriter) HashMap(java.util.HashMap) ByteString(com.linkedin.data.ByteString) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteString(com.linkedin.data.ByteString) CountDownLatch(java.util.concurrent.CountDownLatch) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) EntityStream(com.linkedin.r2.message.stream.entitystream.EntityStream) MimeMultipart(javax.mail.internet.MimeMultipart) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Aggregations

MimeBodyPart (javax.mail.internet.MimeBodyPart)172 MimeMultipart (javax.mail.internet.MimeMultipart)111 MimeMessage (javax.mail.internet.MimeMessage)65 MessagingException (javax.mail.MessagingException)64 IOException (java.io.IOException)49 DataHandler (javax.activation.DataHandler)39 ByteString (com.linkedin.data.ByteString)38 ByteArrayOutputStream (java.io.ByteArrayOutputStream)37 BodyPart (javax.mail.BodyPart)35 InternetAddress (javax.mail.internet.InternetAddress)31 ZMimeBodyPart (com.zimbra.common.zmime.ZMimeBodyPart)30 Test (org.testng.annotations.Test)28 ZMimeMultipart (com.zimbra.common.zmime.ZMimeMultipart)23 Multipart (javax.mail.Multipart)20 InputStream (java.io.InputStream)18 ArrayList (java.util.ArrayList)17 HashMap (java.util.HashMap)16 Session (javax.mail.Session)16 Date (java.util.Date)15 Properties (java.util.Properties)15