use of javax.mail.BodyPart in project rest.li by linkedin.
the class TestMIMEIntegrationReader method executeRequestAndAssert.
///////////////////////////////////////////////////////////////////////////////////////
private void executeRequestAndAssert(final ByteString requestPayload, final int chunkSize, final MimeMultipart mimeMultipart) throws Exception {
final VariableByteStringWriter variableByteStringWriter = new VariableByteStringWriter(requestPayload, chunkSize);
final EntityStream entityStream = EntityStreams.newEntityStream(variableByteStringWriter);
final StreamRequestBuilder builder = new StreamRequestBuilder(Bootstrap.createHttpURI(PORT, SERVER_URI));
//We add additional parameters since MIME supports this and we want to make sure we can still extract boundary
//properly.
final String contentTypeHeader = mimeMultipart.getContentType() + ";somecustomparameter=somecustomvalue" + ";anothercustomparameter=anothercustomvalue";
StreamRequest request = builder.setMethod("POST").setHeader(HEADER_CONTENT_TYPE, contentTypeHeader).build(entityStream);
final AtomicInteger status = new AtomicInteger(-1);
final CountDownLatch latch = new CountDownLatch(1);
Callback<StreamResponse> callback = expectSuccessCallback(latch, status, new HashMap<String, String>());
_client.streamRequest(request, callback);
latch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
Assert.assertEquals(status.get(), RestStatus.OK);
List<SinglePartMIMEReaderCallbackImpl> singlePartMIMEReaderCallbacks = _mimeServerRequestHandler._testMultiPartMIMEReaderCallback._singlePartMIMEReaderCallbacks;
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), mimeMultipart.getCount());
for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i++) {
//Actual
final SinglePartMIMEReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = mimeMultipart.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements()) {
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback._headers, expectedHeaders);
//Verify the body matches
if (currentExpectedPart.getContent() instanceof byte[]) {
Assert.assertEquals(currentCallback._finishedData.copyBytes(), currentExpectedPart.getContent());
} else {
//Default is String
Assert.assertEquals(new String(currentCallback._finishedData.copyBytes()), currentExpectedPart.getContent());
}
}
}
use of javax.mail.BodyPart in project rest.li by linkedin.
the class TestMIMEReaderDrain method testSingleAlternateTopRemaining.
@Test(dataProvider = "allTypesOfBodiesDataSource")
public void testSingleAlternateTopRemaining(final int chunkSize, final List<MimeBodyPart> bodyPartList) throws Exception {
//Execute the request, verify the correct header came back to ensure the server took the proper drain actions
//and return the payload so we can assert deeper.
executeRequestWithDrainStrategy(chunkSize, bodyPartList, SINGLE_ALTERNATE_TOP_REMAINING, "onDrainComplete");
//Single part alternates between consumption and draining the first 6 parts, then top level drains all of remaining.
//This means that parts 0, 2, 4 will be consumed and parts 1, 3, 5 will be drained.
List<SinglePartMIMEDrainReaderCallbackImpl> singlePartMIMEReaderCallbacks = _currentMultiPartMIMEReaderCallback.getSinglePartMIMEReaderCallbacks();
Assert.assertEquals(singlePartMIMEReaderCallbacks.size(), 6);
//First the consumed
for (int i = 0; i < singlePartMIMEReaderCallbacks.size(); i = i + 2) {
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements()) {
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify the body matches
if (currentExpectedPart.getContent() instanceof byte[]) {
Assert.assertEquals(currentCallback.getFinishedData().copyBytes(), currentExpectedPart.getContent());
} else {
//Default is String
Assert.assertEquals(new String(currentCallback.getFinishedData().copyBytes()), currentExpectedPart.getContent());
}
}
//Then the drained
for (int i = 1; i < singlePartMIMEReaderCallbacks.size(); i = i + 2) {
//Actual
final SinglePartMIMEDrainReaderCallbackImpl currentCallback = singlePartMIMEReaderCallbacks.get(i);
//Expected
final BodyPart currentExpectedPart = _currentMimeMultipartBody.getBodyPart(i);
//Construct expected headers and verify they match
final Map<String, String> expectedHeaders = new HashMap<String, String>();
@SuppressWarnings("unchecked") final Enumeration<Header> allHeaders = currentExpectedPart.getAllHeaders();
while (allHeaders.hasMoreElements()) {
final Header header = allHeaders.nextElement();
expectedHeaders.put(header.getName(), header.getValue());
}
Assert.assertEquals(currentCallback.getHeaders(), expectedHeaders);
//Verify that the bodies are empty
Assert.assertNull(currentCallback.getFinishedData(), null);
}
}
use of javax.mail.BodyPart in project disconf by knightliao.
the class SimpleMailSender method sendHtmlMail.
/**
* 以HTML格式发送邮件
*
* @param mailInfo 待发送的邮件信息
*/
public static boolean sendHtmlMail(MailSenderInfo mailInfo) {
try {
LOG.info("send to " + mailInfo.getFromAddress());
// 设置一些通用的数据
Message mailMessage = setCommon(mailInfo);
// MiniMultipart类是一个容器类,包含MimeBodyPart类型的对象
Multipart mainPart = new MimeMultipart();
// 创建一个包含HTML内容的MimeBodyPart
BodyPart html = new MimeBodyPart();
// 设置HTML内容
html.setContent(mailInfo.getContent(), "text/html; charset=utf-8");
mainPart.addBodyPart(html);
// 将MiniMultipart对象设置为邮件内容
mailMessage.setContent(mainPart);
// 发送邮件
Transport.send(mailMessage);
LOG.info("send to " + mailInfo.getFromAddress() + " dnoe.");
return true;
} catch (MessagingException ex) {
LOG.error(ex.toString(), ex);
}
return false;
}
use of javax.mail.BodyPart in project ats-framework by Axway.
the class MimePackage method setBody.
/**
* Replaces body parts with the specified content. <br>
* If this is a plain text only message, the provided HTML content will not
* affect the message in any way.
* <em>Note:</em> This method has effect only if there are already such (plain and/or HTML) parts.
*
* @param plainTextContent
* the text content of the message
* @param htmlContent
* the HTML content of the message
* @throws PackageException
*/
@PublicAtsApi
public void setBody(String plainTextContent, String htmlContent) throws PackageException {
try {
String messageContentType = message.getContentType();
if (messageContentType == null) {
// not expected as default should be "text/plain"
log.info("No content type is set yet. Body of message is not changed");
return;
} else {
// type is not not case-sensitive as mentioned in
// http://www.w3.org/Protocols/rfc1341/4_Content-Type.html and RFC 2045
messageContentType = messageContentType.toLowerCase();
}
if (messageContentType.startsWith(CONTENT_TYPE_TEXT_PLAIN)) {
// this is a text/plain message
message.setContent(plainTextContent, message.getContentType());
} else {
if (messageContentType.startsWith(CONTENT_TYPE_MULTIPART_PREFIX)) {
// this is a MULTIPART message
try {
BodyPart tmpBodyPart;
MimeMultipart tmpMultipartContent = (MimeMultipart) message.getContent();
for (int index = 0; index < tmpMultipartContent.getCount(); index++) {
tmpBodyPart = tmpMultipartContent.getBodyPart(index);
if (tmpBodyPart.getContentType().startsWith(CONTENT_PART_TYPE_TEXT_HTML)) {
// just replace content, do not create additional part
tmpBodyPart.setContent(htmlContent, tmpBodyPart.getContentType());
// for some reason after setting content there is match for text/plain too for the same body part
// so use if-else or continue
} else if (tmpBodyPart.getContentType().startsWith(CONTENT_PART_TYPE_TEXT_PLAIN)) {
// replace text part
tmpBodyPart.setContent(plainTextContent, tmpBodyPart.getContentType());
continue;
}
// do not check content type and go to process next part
}
} catch (IOException ioe) {
throw new PackageException("Could not add MIME body parts", ioe);
}
}
}
// make sure all changes to the message are saved before decomposing
try {
message.saveChanges();
} catch (MessagingException me) {
throw new PackageException("Could not save message changes", me);
}
// we need to decompose again, as a new part has been added
decompose();
} catch (MessagingException me) {
throw new PackageException(me);
}
}
use of javax.mail.BodyPart in project ats-framework by Axway.
the class MimePackage method getFirstBody.
/**
* Get the content of the first part with the specified content type
* <br>If this is a multipart message, we search only into the first nested level.
*
* @return the contents (body) of the first part with given content type.
* Null if such is not found in current or the direct sub-level
* @throws PackageException
*/
@PublicAtsApi
private String getFirstBody(String contentType) throws PackageException {
String textBody = null;
boolean storeReconnected;
try {
String messageContentType = message.getContentType().toLowerCase();
String contentDisposition = null;
storeReconnected = reconnectStoreIfClosed();
try {
if (messageContentType.startsWith(contentType)) {
contentDisposition = message.getDisposition();
if (!Part.ATTACHMENT.equalsIgnoreCase(contentDisposition)) {
// this is a plain text message
textBody = message.getContent().toString();
}
} else {
Object content = message.getContent();
if (content instanceof Multipart) {
// a multi-part message
Multipart parts = (Multipart) message.getContent();
// first look on top level
for (int i = 0; i < parts.getCount(); i++) {
BodyPart mimePart = parts.getBodyPart(i);
if (!(mimePart.getContent() instanceof Multipart)) {
textBody = getBodyIfNotAttachment(mimePart, contentType);
if (textBody != null) {
break;
}
}
}
if (textBody == null) {
// not found on top level - look multipart entries
for (int i = 0; i < parts.getCount(); i++) {
BodyPart mimePart = parts.getBodyPart(i);
if (mimePart.getContent() instanceof Multipart) {
Multipart nestedParts = (Multipart) mimePart.getContent();
for (int m = 0; m < nestedParts.getCount(); m++) {
BodyPart nestedMimePart = nestedParts.getBodyPart(m);
textBody = getBodyIfNotAttachment(nestedMimePart, contentType);
if (textBody != null) {
break;
}
}
}
if (textBody != null) {
break;
}
}
}
}
}
} finally {
closeStoreConnection(storeReconnected);
}
return textBody;
} catch (MessagingException e) {
throw new PackageException(e);
} catch (IOException e) {
throw new PackageException(e);
}
}
Aggregations