Search in sources :

Example 31 with ContentType

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

the class TestRestLiServer method testMultipartRelatedRequestNoUserAttachments.

@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
        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);
}
Also used : ContentType(javax.mail.internet.ContentType) RestResponse(com.linkedin.r2.message.rest.RestResponse) 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) StreamResponse(com.linkedin.r2.message.stream.StreamResponse) ByteString(com.linkedin.data.ByteString) URI(java.net.URI) AsyncStatusCollectionResource(com.linkedin.restli.server.twitter.AsyncStatusCollectionResource) 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) FilterRequestContext(com.linkedin.restli.server.filter.FilterRequestContext) RequestContext(com.linkedin.r2.message.RequestContext) RestLiAttachmentReader(com.linkedin.restli.common.attachments.RestLiAttachmentReader) ByteStringWriter(com.linkedin.r2.message.stream.entitystream.ByteStringWriter) MultiPartMIMEWriter(com.linkedin.multipart.MultiPartMIMEWriter) Test(org.testng.annotations.Test) AfterTest(org.testng.annotations.AfterTest) BeforeTest(org.testng.annotations.BeforeTest)

Example 32 with ContentType

use of javax.mail.internet.ContentType in project ats-framework by Axway.

the class MimePackage method getAttachmentCharset.

/**
     * Get the attachment character set
     *
     * @param partIndex
     *            the index of the attachment
     * @return the character set for this attachment, null if there is no such
     * @throws PackageException
     */
@PublicAtsApi
public String getAttachmentCharset(int partIndex) throws PackageException {
    // first check if there is part at this position at all
    if (partIndex >= attachmentPartIndices.size()) {
        throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
    }
    try {
        MimePart part = getPart(attachmentPartIndices.get(partIndex));
        // get the content type header
        ContentType contentType = new ContentType(part.getContentType());
        return contentType.getParameter("charset");
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
Also used : ContentType(javax.mail.internet.ContentType) MessagingException(javax.mail.MessagingException) NoSuchMimePartException(com.axway.ats.action.objects.model.NoSuchMimePartException) MimePart(javax.mail.internet.MimePart) NoSuchMimePackageException(com.axway.ats.action.objects.model.NoSuchMimePackageException) PackageException(com.axway.ats.action.objects.model.PackageException) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 33 with ContentType

use of javax.mail.internet.ContentType in project ats-framework by Axway.

the class MimePackage method getAttachmentContentType.

/**
     * Get the attachment content type
     *
     * @param partIndex
     * @return
     * @throws PackageException
     */
@PublicAtsApi
public String getAttachmentContentType(int partIndex) throws PackageException {
    // first check if there is part at this position at all
    if (partIndex >= attachmentPartIndices.size()) {
        throw new NoSuchMimePartException("No attachment at position '" + partIndex + "'");
    }
    try {
        MimePart part = getPart(attachmentPartIndices.get(partIndex));
        // get the content type header
        ContentType contentType = new ContentType(part.getContentType());
        return contentType.getBaseType();
    } catch (MessagingException me) {
        throw new PackageException(me);
    }
}
Also used : ContentType(javax.mail.internet.ContentType) MessagingException(javax.mail.MessagingException) NoSuchMimePartException(com.axway.ats.action.objects.model.NoSuchMimePartException) MimePart(javax.mail.internet.MimePart) NoSuchMimePackageException(com.axway.ats.action.objects.model.NoSuchMimePackageException) PackageException(com.axway.ats.action.objects.model.PackageException) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 34 with ContentType

use of javax.mail.internet.ContentType in project nhin-d by DirectProject.

the class DefaultNHINDAgent method decryptSignedContent.

/*
     * Decrypts the signed message
     */
@SuppressWarnings("unchecked")
protected void decryptSignedContent(IncomingMessage message) {
    MimeEntity decryptedEntity = this.decryptMessage(message);
    CMSSignedData signatures;
    MimeEntity payload;
    try {
        if (SMIMEStandard.isContentEnvelopedSignature(new ContentType(decryptedEntity.getContentType()))) {
            signatures = cryptographer.deserializeEnvelopedSignature(decryptedEntity);
            payload = new MimeEntity(new ByteArrayInputStream(signatures.getContentInfo().getEncoded()));
        } else if (SMIMEStandard.isContentMultipartSignature(new ContentType(decryptedEntity.getContentType()))) {
            //
            // Extract the signature envelope. That contains both the signature and the actual message content
            //
            ByteArrayDataSource dataSource = new ByteArrayDataSource(decryptedEntity.getRawInputStream(), decryptedEntity.getContentType());
            MimeMultipart verifyMM = new MimeMultipart(dataSource);
            SignedEntity signedEntity = SignedEntity.load(verifyMM);
            signatures = cryptographer.deserializeSignatureEnvelope(signedEntity);
            payload = signedEntity.getContent();
        } else {
            throw new AgentException(AgentError.UnsignedMessage);
        }
        message.setSignature(signatures);
        //
        // Alter body to contain actual content. Also clean up mime headers on the message that were there to support
        // signatures etc
        //         	
        InternetHeaders headers = new InternetHeaders();
        // remove all mime headers
        Enumeration<Header> eHeaders = message.getMessage().getAllHeaders();
        while (eHeaders.hasMoreElements()) {
            Header hdr = (Header) eHeaders.nextElement();
            if (!MimeStandard.startsWith(hdr.getName(), MimeStandard.HeaderPrefix))
                headers.setHeader(hdr.getName(), hdr.getValue());
        }
        // add back in headers from original message
        eHeaders = payload.getAllHeaders();
        while (eHeaders.hasMoreElements()) {
            Header hdr = (Header) eHeaders.nextElement();
            headers.setHeader(hdr.getName(), hdr.getValue());
        }
        Message msg = new Message(headers, payload.getContentAsBytes());
        message.setMessage(msg);
    } catch (MessagingException e) {
        throw new MimeException(MimeError.InvalidBody, e);
    } catch (IOException e) {
        throw new MimeException(MimeError.InvalidBody, e);
    }
}
Also used : ContentType(javax.mail.internet.ContentType) InternetHeaders(javax.mail.internet.InternetHeaders) WrappedMessage(org.nhindirect.stagent.mail.WrappedMessage) Message(org.nhindirect.stagent.mail.Message) MimeMessage(javax.mail.internet.MimeMessage) MessagingException(javax.mail.MessagingException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) Header(javax.mail.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) MimeMultipart(javax.mail.internet.MimeMultipart) MimeEntity(org.nhindirect.stagent.mail.MimeEntity) MimeException(org.nhindirect.stagent.mail.MimeException) ByteArrayDataSource(javax.mail.util.ByteArrayDataSource) SignedEntity(org.nhindirect.stagent.cryptography.SignedEntity)

Example 35 with ContentType

use of javax.mail.internet.ContentType in project nhin-d by DirectProject.

the class SMIMECryptographerImpl_createSignatureEntityTest method validatedSignatureHeaders.

protected void validatedSignatureHeaders(MimeMultipart mm) throws Exception {
    /*
		 * explicit header checking for compliance with Applicability
		 * Statement v 1.2
		 */
    final ContentType type = new ContentType(mm.getContentType());
    assertTrue(type.match("multipart/signed"));
    assertEquals(SMIMEStandard.SignatureContentMediaType, type.getParameter("protocol"));
    assertEquals(CryptoAlgorithmsHelper.toDigestAlgorithmMicalg(DigestAlgorithm.SHA256), type.getParameter("micalg"));
    final ContentType signedTypetype = new ContentType(mm.getBodyPart(1).getContentType());
    assertTrue(signedTypetype.match(SMIMEStandard.SignatureContentMediaType));
}
Also used : ContentType(javax.mail.internet.ContentType)

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