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;
}
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;
}
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;
}
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);
}
}
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);
}
Aggregations