final MIMEMessage mimeMessage = new MIMEMessage(stream,
mediaType.getParameters().get("boundary"),
mimeConfig);
boolean formData = MediaTypes.typeEqual(mediaType, MediaType.MULTIPART_FORM_DATA_TYPE);
MultiPart multiPart = formData ? new FormDataMultiPart() : new MultiPart();
final MessageBodyWorkers workers = messageBodyWorkers.get();
multiPart.setMessageBodyWorkers(workers);
MultivaluedMap<String, String> multiPartHeaders = multiPart.getHeaders();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
List<String> values = entry.getValue();
for (String value : values) {
multiPartHeaders.add(entry.getKey(), value);
}
}
boolean fileNameFix;
if (!formData) {
multiPart.setMediaType(mediaType);
fileNameFix = false;
} else {
// see if the User-Agent header corresponds to some version of MS Internet Explorer
// if so, need to set fileNameFix to true to handle issue http://java.net/jira/browse/JERSEY-759
String userAgent = headers.getFirst(HttpHeaders.USER_AGENT);
fileNameFix = userAgent != null && userAgent.contains(" MSIE ");
}
for (MIMEPart mimePart : mimeMessage.getAttachments()) {
BodyPart bodyPart = formData ? new FormDataBodyPart(fileNameFix) : new BodyPart();
// Configure providers.
bodyPart.setMessageBodyWorkers(workers);
// Copy headers.
for (Header header : mimePart.getAllHeaders()) {
bodyPart.getHeaders().add(header.getName(), header.getValue());
}
try {
String contentType = bodyPart.getHeaders().getFirst("Content-Type");
if (contentType != null)
bodyPart.setMediaType(MediaType.valueOf(contentType));
bodyPart.getContentDisposition();
} catch (IllegalArgumentException ex) {
throw new BadRequestException(ex);
}
// Copy data into a BodyPartEntity structure.
bodyPart.setEntity(new BodyPartEntity(mimePart));
// Add this BodyPart to our MultiPart.
multiPart.getBodyParts().add(bodyPart);
}
return multiPart;
}