Search in sources :

Example 26 with ContentType

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

the class QueryTunnelUtil method createMultiPartEntity.

/**
   * Helper function to create multi-part MIME
   *
   * @param entity         the body of a request
   * @param entityContentType content type of the body
   * @param query          a query part of a request
   *
   * @return a ByteString that represents a multi-part encoded entity that contains both
   */
private static MimeMultipart createMultiPartEntity(final ByteString entity, final String entityContentType, String query) throws MessagingException {
    MimeMultipart multi = new MimeMultipart(MIXED);
    // Create current entity with the associated type
    MimeBodyPart dataPart = new MimeBodyPart();
    ContentType contentType = new ContentType(entityContentType);
    if (MULTIPART.equals(contentType.getBaseType())) {
        MimeMultipart nested = new MimeMultipart(new DataSource() {

            @Override
            public InputStream getInputStream() throws IOException {
                return entity.asInputStream();
            }

            @Override
            public OutputStream getOutputStream() throws IOException {
                return null;
            }

            @Override
            public String getContentType() {
                return entityContentType;
            }

            @Override
            public String getName() {
                return null;
            }
        });
        dataPart.setContent(nested, contentType.getBaseType());
    } else {
        dataPart.setContent(entity.copyBytes(), contentType.getBaseType());
    }
    dataPart.setHeader(HEADER_CONTENT_TYPE, entityContentType);
    // Encode query params as form-urlencoded
    MimeBodyPart argPart = new MimeBodyPart();
    argPart.setContent(query, FORM_URL_ENCODED);
    argPart.setHeader(HEADER_CONTENT_TYPE, FORM_URL_ENCODED);
    multi.addBodyPart(argPart);
    multi.addBodyPart(dataPart);
    return multi;
}
Also used : ContentType(javax.mail.internet.ContentType) MimeMultipart(javax.mail.internet.MimeMultipart) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) ByteString(com.linkedin.data.ByteString) MimeBodyPart(javax.mail.internet.MimeBodyPart) DataSource(javax.activation.DataSource)

Example 27 with ContentType

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

the class RestLiServer method verifyAttachmentSupportNotNeeded.

private boolean verifyAttachmentSupportNotNeeded(final Request request, final Callback<RestResponse> callback) {
    final Map<String, String> requestHeaders = request.getHeaders();
    try {
        final String contentTypeString = requestHeaders.get(RestConstants.HEADER_CONTENT_TYPE);
        if (contentTypeString != null) {
            final ContentType contentType = new ContentType(contentTypeString);
            if (contentType.getBaseType().equalsIgnoreCase(RestConstants.HEADER_VALUE_MULTIPART_RELATED)) {
                callback.onError(RestException.forError(415, "This server cannot handle requests with a content type of multipart/related"));
                return true;
            }
        }
        final String acceptTypeHeader = requestHeaders.get(RestConstants.HEADER_ACCEPT);
        if (acceptTypeHeader != null) {
            final List<String> acceptTypes = MIMEParse.parseAcceptType(acceptTypeHeader);
            for (final String acceptType : acceptTypes) {
                if (acceptType.equalsIgnoreCase(RestConstants.HEADER_VALUE_MULTIPART_RELATED)) {
                    callback.onError(RestException.forError(406, "This server cannot handle requests with an accept type of multipart/related"));
                    return true;
                }
            }
        }
    } catch (ParseException parseException) {
        callback.onError(RestException.forError(400, "Unable to parse content or accept types."));
        return true;
    }
    return false;
}
Also used : ContentType(javax.mail.internet.ContentType) ByteString(com.linkedin.data.ByteString) ParseException(javax.mail.internet.ParseException)

Example 28 with ContentType

use of javax.mail.internet.ContentType in project camel by apache.

the class MimeMultipartDataFormat method unmarshal.

@Override
public Object unmarshal(Exchange exchange, InputStream stream) throws IOException, MessagingException {
    MimeBodyPart mimeMessage;
    String contentType;
    Message camelMessage;
    Object content = null;
    if (headersInline) {
        mimeMessage = new MimeBodyPart(stream);
        camelMessage = exchange.getOut();
        MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
        contentType = mimeMessage.getHeader(CONTENT_TYPE, null);
        // write the MIME headers not generated by javamail as Camel headers
        Enumeration<?> headersEnum = mimeMessage.getNonMatchingHeaders(STANDARD_HEADERS);
        while (headersEnum.hasMoreElements()) {
            Object ho = headersEnum.nextElement();
            if (ho instanceof Header) {
                Header header = (Header) ho;
                camelMessage.setHeader(header.getName(), header.getValue());
            }
        }
    } else {
        // check if this a multipart at all. Otherwise do nothing
        contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class);
        if (contentType == null) {
            return stream;
        }
        try {
            ContentType ct = new ContentType(contentType);
            if (!ct.match("multipart/*")) {
                return stream;
            }
        } catch (ParseException e) {
            LOG.warn("Invalid Content-Type " + contentType + " ignored");
            return stream;
        }
        camelMessage = exchange.getOut();
        MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        IOHelper.copyAndCloseInput(stream, bos);
        InternetHeaders headers = new InternetHeaders();
        extractHeader(CONTENT_TYPE, camelMessage, headers);
        extractHeader(MIME_VERSION, camelMessage, headers);
        mimeMessage = new MimeBodyPart(headers, bos.toByteArray());
        bos.close();
    }
    DataHandler dh;
    try {
        dh = mimeMessage.getDataHandler();
        if (dh != null) {
            content = dh.getContent();
            contentType = dh.getContentType();
        }
    } catch (MessagingException e) {
        LOG.warn("cannot parse message, no unmarshalling done");
    }
    if (content instanceof MimeMultipart) {
        MimeMultipart mp = (MimeMultipart) content;
        content = mp.getBodyPart(0);
        for (int i = 1; i < mp.getCount(); i++) {
            BodyPart bp = mp.getBodyPart(i);
            DefaultAttachment camelAttachment = new DefaultAttachment(bp.getDataHandler());
            @SuppressWarnings("unchecked") Enumeration<Header> headers = bp.getAllHeaders();
            while (headers.hasMoreElements()) {
                Header header = headers.nextElement();
                camelAttachment.addHeader(header.getName(), header.getValue());
            }
            camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment);
        }
    }
    if (content instanceof BodyPart) {
        BodyPart bp = (BodyPart) content;
        camelMessage.setBody(bp.getInputStream());
        contentType = bp.getContentType();
        if (contentType != null && !DEFAULT_CONTENT_TYPE.equals(contentType)) {
            camelMessage.setHeader(CONTENT_TYPE, contentType);
            ContentType ct = new ContentType(contentType);
            String charset = ct.getParameter("charset");
            if (charset != null) {
                camelMessage.setHeader(Exchange.CONTENT_ENCODING, MimeUtility.javaCharset(charset));
            }
        }
    } else {
        // If we find no body part, try to leave the message alone
        LOG.info("no MIME part found");
    }
    return camelMessage;
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) Message(org.apache.camel.Message) MimeMessage(javax.mail.internet.MimeMessage) ContentType(javax.mail.internet.ContentType) InternetHeaders(javax.mail.internet.InternetHeaders) MessagingException(javax.mail.MessagingException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataHandler(javax.activation.DataHandler) Header(javax.mail.Header) MimeMultipart(javax.mail.internet.MimeMultipart) ParseException(javax.mail.internet.ParseException) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) MimeBodyPart(javax.mail.internet.MimeBodyPart)

Example 29 with ContentType

use of javax.mail.internet.ContentType in project camel by apache.

the class MimeMultipartDataFormat method marshal.

@Override
public void marshal(Exchange exchange, Object graph, OutputStream stream) throws NoTypeConversionAvailableException, MessagingException, IOException {
    if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) {
        ContentType contentType = getContentType(exchange);
        // remove the Content-Type header. This will be wrong afterwards...
        exchange.getOut().removeHeader(Exchange.CONTENT_TYPE);
        byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph);
        Session session = Session.getInstance(System.getProperties());
        MimeMessage mm = new MimeMessage(session);
        MimeMultipart mp = new MimeMultipart(multipartSubType);
        BodyPart part = new MimeBodyPart();
        writeBodyPart(bodyContent, part, contentType);
        mp.addBodyPart(part);
        for (Map.Entry<String, Attachment> entry : exchange.getIn().getAttachmentObjects().entrySet()) {
            String attachmentFilename = entry.getKey();
            Attachment attachment = entry.getValue();
            part = new MimeBodyPart();
            part.setDataHandler(attachment.getDataHandler());
            part.setFileName(MimeUtility.encodeText(attachmentFilename, "UTF-8", null));
            String ct = attachment.getDataHandler().getContentType();
            contentType = new ContentType(ct);
            part.setHeader(CONTENT_TYPE, ct);
            if (!contentType.match("text/*") && binaryContent) {
                part.setHeader(CONTENT_TRANSFER_ENCODING, "binary");
            }
            // Set headers to the attachment
            for (String headerName : attachment.getHeaderNames()) {
                List<String> values = attachment.getHeaderAsList(headerName);
                for (String value : values) {
                    part.setHeader(headerName, value);
                }
            }
            mp.addBodyPart(part);
            exchange.getOut().removeAttachment(attachmentFilename);
        }
        mm.setContent(mp);
        // a String
        if (headersInline && includeHeaders != null) {
            for (Map.Entry<String, Object> entry : exchange.getIn().getHeaders().entrySet()) {
                if (includeHeaders.matcher(entry.getKey()).matches()) {
                    String headerStr = ExchangeHelper.convertToType(exchange, String.class, entry.getValue());
                    if (headerStr != null) {
                        mm.setHeader(entry.getKey(), headerStr);
                    }
                }
            }
        }
        mm.saveChanges();
        Enumeration<?> hl = mm.getAllHeaders();
        List<String> headers = new ArrayList<String>();
        if (!headersInline) {
            while (hl.hasMoreElements()) {
                Object ho = hl.nextElement();
                if (ho instanceof Header) {
                    Header h = (Header) ho;
                    exchange.getOut().setHeader(h.getName(), h.getValue());
                    headers.add(h.getName());
                }
            }
            mm.saveChanges();
        }
        mm.writeTo(stream, headers.toArray(new String[0]));
    } else {
        // keep the original data
        InputStream is = ExchangeHelper.convertToMandatoryType(exchange, InputStream.class, graph);
        IOHelper.copyAndCloseInput(is, stream);
    }
}
Also used : MimeBodyPart(javax.mail.internet.MimeBodyPart) BodyPart(javax.mail.BodyPart) ContentType(javax.mail.internet.ContentType) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) Attachment(org.apache.camel.Attachment) DefaultAttachment(org.apache.camel.impl.DefaultAttachment) Header(javax.mail.Header) MimeMessage(javax.mail.internet.MimeMessage) MimeMultipart(javax.mail.internet.MimeMultipart) MimeBodyPart(javax.mail.internet.MimeBodyPart) Map(java.util.Map) Session(javax.mail.Session)

Example 30 with ContentType

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

the class TestRestLiServer method testRequestAttachmentsAndResponseAttachments.

@Test
public void testRequestAttachmentsAndResponseAttachments() throws Exception {
    //This test verifies the server's ability to accept request attachments and send back response attachments. This is the
    //main test to verify the wire protocol for streaming. We send a payload that contains the rest.li payload and some attachments
    //and we send a response back with a rest.li payload and some attachments.
    //Define the server side resource attachments to be sent back.
    final RestLiResponseAttachments.Builder responseAttachmentsBuilder = new RestLiResponseAttachments.Builder();
    responseAttachmentsBuilder.appendSingleAttachment(new RestLiTestAttachmentDataSource("1", ByteString.copyString("one", Charset.defaultCharset())));
    Capture<ResourceContext> resourceContextCapture = new Capture<ResourceContext>();
    final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class, EasyMock.capture(resourceContextCapture));
    statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(), EasyMock.<Callback<Long>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {

        @Override
        public Object answer() throws Throwable {
            //Verify there are still attachments to be read.
            final RestLiAttachmentReader attachmentReader = (RestLiAttachmentReader) EasyMock.getCurrentArguments()[1];
            Assert.assertFalse(attachmentReader.haveAllAttachmentsFinished());
            //Verify the action param.
            Assert.assertEquals((String) EasyMock.getCurrentArguments()[0], "someMetadata");
            //Set the response attachments
            resourceContextCapture.getValue().setResponseAttachments(responseAttachmentsBuilder.build());
            //Now respond back to the request.
            @SuppressWarnings("unchecked") Callback<Long> callback = (Callback<Long>) EasyMock.getCurrentArguments()[2];
            callback.onSuccess(1234l);
            return null;
        }
    });
    EasyMock.replay(statusResource);
    //Now we create a multipart/related payload.
    final String payload = "{\"metadata\": \"someMetadata\"}";
    final ByteStringWriter byteStringWriter = new ByteStringWriter(ByteString.copyString(payload, Charset.defaultCharset()));
    final MultiPartMIMEWriter.Builder builder = new MultiPartMIMEWriter.Builder();
    AttachmentUtils.appendSingleAttachmentToBuilder(builder, new RestLiTestAttachmentDataSource("2", ByteString.copyString("two", Charset.defaultCharset())));
    final MultiPartMIMEWriter writer = AttachmentUtils.createMultiPartMIMEWriter(byteStringWriter, "application/json", builder);
    final StreamRequest streamRequest = MultiPartMIMEStreamRequestFactory.generateMultiPartMIMEStreamRequest(new URI("/asyncstatuses/?action=streamingAction"), "related", writer, Collections.<String, String>emptyMap(), "POST", ImmutableMap.of(RestConstants.HEADER_ACCEPT, RestConstants.HEADER_VALUE_MULTIPART_RELATED), Collections.emptyList());
    final Callback<StreamResponse> callback = new Callback<StreamResponse>() {

        @Override
        public void onSuccess(StreamResponse streamResponse) {
            //Before reading the data make sure top level type is multipart/related
            Assert.assertEquals(streamResponse.getStatus(), 200);
            try {
                ContentType contentType = new ContentType(streamResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE));
                Assert.assertEquals(contentType.getBaseType(), RestConstants.HEADER_VALUE_MULTIPART_RELATED);
            } catch (ParseException parseException) {
                Assert.fail();
            }
            final CountDownLatch countDownLatch = new CountDownLatch(1);
            MultiPartMIMEFullReaderCallback fullReaderCallback = new MultiPartMIMEFullReaderCallback(countDownLatch);
            final MultiPartMIMEReader reader = MultiPartMIMEReader.createAndAcquireStream(streamResponse);
            reader.registerReaderCallback(fullReaderCallback);
            try {
                countDownLatch.await(3000, TimeUnit.MILLISECONDS);
            } catch (InterruptedException interruptedException) {
                Assert.fail();
            }
            final List<SinglePartMIMEFullReaderCallback> singlePartMIMEReaderCallbacks = fullReaderCallback.getSinglePartMIMEReaderCallbacks();
            Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 2);
            //Verify first part is Action response.
            Assert.assertEquals(singlePartMIMEReaderCallbacks.get(0).getHeaders().get(RestConstants.HEADER_CONTENT_TYPE), RestConstants.HEADER_VALUE_APPLICATION_JSON);
            Assert.assertEquals(singlePartMIMEReaderCallbacks.get(0).getFinishedData().asAvroString(), "{\"value\":1234}");
            //Verify the second part matches what the server should have sent back
            Assert.assertEquals(singlePartMIMEReaderCallbacks.get(1).getHeaders().get(RestConstants.HEADER_CONTENT_ID), "1");
            Assert.assertEquals(singlePartMIMEReaderCallbacks.get(1).getFinishedData().asString(Charset.defaultCharset()), "one");
            EasyMock.verify(statusResource);
            EasyMock.reset(statusResource);
        }

        @Override
        public void onError(Throwable e) {
            fail();
        }
    };
    _server.handleRequest(streamRequest, new RequestContext(), callback);
}
Also used : ContentType(javax.mail.internet.ContentType) RestRequestBuilder(com.linkedin.r2.message.rest.RestRequestBuilder) ErrorResponseBuilder(com.linkedin.restli.internal.server.response.ErrorResponseBuilder) StreamRequestBuilder(com.linkedin.r2.message.stream.StreamRequestBuilder) RestResponseBuilder(com.linkedin.r2.message.rest.RestResponseBuilder) ByteString(com.linkedin.data.ByteString) URI(java.net.URI) Capture(org.easymock.Capture) SinglePartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback) RestLiTestAttachmentDataSource(com.linkedin.restli.internal.testutils.RestLiTestAttachmentDataSource) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) MultiPartMIMEWriter(com.linkedin.multipart.MultiPartMIMEWriter) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) MultiPartMIMEReader(com.linkedin.multipart.MultiPartMIMEReader) CountDownLatch(java.util.concurrent.CountDownLatch) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) MultiPartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback) StreamRequest(com.linkedin.r2.message.stream.StreamRequest) SinglePartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.SinglePartMIMEFullReaderCallback) Callback(com.linkedin.common.callback.Callback) MultiPartMIMEFullReaderCallback(com.linkedin.multipart.utils.MIMETestUtils.MultiPartMIMEFullReaderCallback) ParseException(javax.mail.internet.ParseException) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Aggregations

ContentType (javax.mail.internet.ContentType)40 IOException (java.io.IOException)17 MessagingException (javax.mail.MessagingException)14 MimeBodyPart (javax.mail.internet.MimeBodyPart)14 ByteString (com.linkedin.data.ByteString)10 MimeMessage (javax.mail.internet.MimeMessage)9 MimeMultipart (javax.mail.internet.MimeMultipart)9 InputStream (java.io.InputStream)8 ParseException (javax.mail.internet.ParseException)8 MimePart (javax.mail.internet.MimePart)6 PackageException (com.axway.ats.action.objects.model.PackageException)5 DataHandler (javax.activation.DataHandler)5 BodyPart (javax.mail.BodyPart)5 NoSuchMimePackageException (com.axway.ats.action.objects.model.NoSuchMimePackageException)4 NoSuchMimePartException (com.axway.ats.action.objects.model.NoSuchMimePartException)4 PublicAtsApi (com.axway.ats.common.PublicAtsApi)4 RestRequestBuilder (com.linkedin.r2.message.rest.RestRequestBuilder)3 ZComponent (com.zimbra.common.calendar.ZCalendar.ZComponent)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 URI (java.net.URI)3