Example usage for javax.mail.internet ContentType ContentType

List of usage examples for javax.mail.internet ContentType ContentType

Introduction

In this page you can find the example usage for javax.mail.internet ContentType ContentType.

Prototype

public ContentType(String s) throws ParseException 

Source Link

Document

Constructor that takes a Content-Type string.

Usage

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * A 'safe' version of JavaMail getContentType(), i.e. don't throw
 * exceptions. The part is interogated for a valid content type. If the
 * content type is missing or invalid, a default content type of
 * "text/plain" is assumed, which is suggested by the MIME standard.
 *
 * @param part The part to interogate//w ww . ja va  2s .  c  om
 *
 * @return ContentType of the part
 *
 * @see javax.mail.Part
 */
public static ContentType getContentType(Part part) {
    String xtype = null;

    try {
        xtype = part.getContentType();
    } catch (MessagingException xex) {
    }

    if (xtype == null) {
        xtype = "text/plain"; // MIME default content type if missing
    }

    ContentType xctype = null;

    try {
        xctype = new ContentType(xtype.toLowerCase());
    } catch (ParseException xex) {
    }

    if (xctype == null) {
        xctype = new ContentType("text", "plain", null);
    }

    return xctype;
}

From source file:com.duroty.utils.mail.MessageUtilities.java

/**
 * DOCUMENT ME!/*from w  w w  .  ja v a  2s. c  om*/
 *
 * @param xtype DOCUMENT ME!
 *
 * @return DOCUMENT ME!
 */
public static ContentType getContentType(String xtype) {
    if (xtype == null) {
        xtype = "text/plain"; // MIME default content type if missing
    }

    ContentType xctype = null;

    try {
        xctype = new ContentType(xtype.toLowerCase());
    } catch (ParseException xex) {
    }

    if (xctype == null) {
        xctype = new ContentType("text", "plain", null);
    }

    return xctype;
}

From source file:com.linkedin.restli.server.TestRestLiServer.java

@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//w w w.ja  v a 2s. co  m
        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);
}

From source file:com.linkedin.restli.server.TestRestLiServer.java

@Test
public void testMultipartRelatedRequestNoUserAttachments() throws Exception {
    //This test verifies the server's ability to handle a multipart related request that has only one part which is
    //the rest.li payload; meaning there are no user defined attachments. Technically the client builders shouldn't do
    //this but we allow this to keep the protocol somewhat flexible.

    final AsyncStatusCollectionResource statusResource = getMockResource(AsyncStatusCollectionResource.class);

    statusResource.streamingAction(EasyMock.<String>anyObject(), EasyMock.<RestLiAttachmentReader>anyObject(),
            EasyMock.<Callback<Long>>anyObject());
    EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
        @Override//from   w w  w.j  a v  a2  s .  com
        public Object answer() throws Throwable {
            //Verify there are no attachments.
            final RestLiAttachmentReader attachmentReader = (RestLiAttachmentReader) EasyMock
                    .getCurrentArguments()[1];
            Assert.assertNull(attachmentReader);

            //Verify the action param.
            Assert.assertEquals((String) EasyMock.getCurrentArguments()[0], "someMetadata");

            //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();
    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) {
            Messages.toRestResponse(streamResponse, new Callback<RestResponse>() {
                @Override
                public void onError(Throwable e) {
                    Assert.fail();
                }

                @Override
                public void onSuccess(RestResponse result) {
                    Assert.assertEquals(result.getStatus(), 200);

                    try {
                        ContentType contentType = new ContentType(
                                streamResponse.getHeader(RestConstants.HEADER_CONTENT_TYPE));
                        Assert.assertEquals(contentType.getBaseType(),
                                RestConstants.HEADER_VALUE_APPLICATION_JSON);
                    } catch (ParseException parseException) {
                        Assert.fail();
                    }

                    //Verify the response body
                    Assert.assertEquals(result.getEntity().asAvroString(), "{\"value\":1234}");

                    EasyMock.verify(statusResource);
                    EasyMock.reset(statusResource);
                }
            });
        }

        @Override
        public void onError(Throwable e) {
            fail();
        }
    };

    _server.handleRequest(streamRequest, new RequestContext(), callback);
}

From source file:com.zimbra.cs.mailbox.calendar.Invite.java

protected ZComponent addInlineATTACHes(ZComponent comp) {
    MimeMessage mimeMsg = null;//  w  ww . ja  va2  s.  c  o  m
    try {
        mimeMsg = getMimeMessage();
    } catch (ServiceException e1) {
        return comp;
    }
    if (mimeMsg == null) {
        return comp;
    }
    try {
        List<MPartInfo> parts = Mime.getParts(mimeMsg, MimeConstants.P_CHARSET_UTF8);
        if (parts != null && !parts.isEmpty()) {
            for (MPartInfo body : parts.get(0).getChildren()) {
                if (body.isMultipart()) {
                    continue;
                }
                MimePart mp = body.getMimePart();
                String ctype = StringUtil.stripControlCharacters(body.getContentType());
                if (MimeConstants.CT_TEXT_CALENDAR.equalsIgnoreCase(ctype)) {
                    // A true calendar part has "method" parameter in the content type.
                    // Otherwise it's just an attachment that happens to be a .ics file.
                    try {
                        ContentType ct = new ContentType(body.getMimePart().getContentType());
                        if (ct.getParameter("method") != null) {
                            continue;
                        }
                    } catch (MessagingException e) {
                    }
                }
                String contentType = StringUtil.stripControlCharacters(body.getContentType());
                String fileName = Mime.getFilename(mp);
                try (InputStream in = mp.getInputStream()) {
                    byte[] rawBytes = IOUtils.toByteArray(in);
                    Attach attachment = Attach.fromUnencodedAndContentType(rawBytes, contentType);
                    if (!Strings.isNullOrEmpty(fileName)) {
                        attachment.setFileName(fileName);
                    }
                    comp.addProperty(attachment.toZProperty());
                }
            }
        }
    } catch (MessagingException | IOException e) {
        ZimbraLog.calendar.warn("Problem adding inline ATTACHes", e);
    }
    return comp;
}