bp1.addHeader("Content-Transfer-Encoding", "binary");
bp1.addHeader("Content-ID", "part1@apache.org");
mp.addBodyPart(bp1);
// Create an attachment that is larger than the maximum heap
DataSource dataSource = new RandomDataSource((int)Math.min(Runtime.getRuntime().maxMemory(), Integer.MAX_VALUE));
MimeBodyPart bp2 = new MimeBodyPart();
bp2.setDataHandler(new DataHandler(dataSource));
bp2.addHeader("Content-Transfer-Encoding", "binary");
bp2.addHeader("Content-ID", "part2@apache.org");
mp.addBodyPart(bp2);
message.setContent(mp);
// Compute the correct content type
message.saveChanges();
// We use a pipe (with a producer running in a separate thread) because obviously we can't
// store the multipart in memory.
final PipedOutputStream pipeOut = new PipedOutputStream();
PipedInputStream pipeIn = new PipedInputStream(pipeOut);
Thread producerThread = new Thread(new Runnable() {
public void run() {
try {
try {
mp.writeTo(pipeOut);
} finally {
pipeOut.close();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
producerThread.start();
try {
// We configure Attachments to buffer MIME parts in memory. If the part content is not
// streamed, then this will result in an OOM error.
Attachments attachments = new Attachments(pipeIn, message.getContentType());
DataHandlerExt dh = (DataHandlerExt)attachments.getDataHandler("part2@apache.org");
IOTestUtils.compareStreams(dataSource.getInputStream(), dh.readOnce());
} finally {
pipeIn.close();
}
}