下面列出了怎么用javax.mail.util.SharedByteArrayInputStream的API类实例代码及写法,或者点击链接到github查看源代码。
@Override
protected InputStream getContentStream() throws MessagingException
{
try
{
if (this.contentStream == null)
{
if (content != null)
{
return new SharedByteArrayInputStream(content);
}
else
{
throw new MessagingException("No content");
}
}
return this.contentStream;
}
catch (Exception e)
{
throw new MessagingException(e.getMessage(),e);
}
}
@Test
void validTextCalendarShouldNotBeSanitized() throws Exception {
FakeMail mail = FakeMail.builder()
.name("mail")
.mimeMessage(
MimeMessageBuilder.mimeMessageBuilder()
.setMultipartWithBodyParts(
MimeMessageBuilder.bodyPartBuilder()
.type("text/calendar")
.data("Not empty")
.addHeader("X-CUSTOM", "Because it is a valid ICS it should not be pushed in body")))
.build();
testee.service(mail);
Object content = mail.getMessage().getContent();
assertThat(content).isInstanceOf(Multipart.class);
Multipart multipart = (Multipart) content;
assertThat(multipart.getCount()).isEqualTo(1);
SharedByteArrayInputStream inputStream = (SharedByteArrayInputStream) multipart.getBodyPart(0).getContent();
assertThat(IOUtils.toString(inputStream, StandardCharsets.UTF_8))
.doesNotContain("X-CUSTOM");
}
private Mono<MessageRepresentation>
message(ResultSet rows, CassandraMessageId cassandraMessageId, FetchType fetchType) {
if (rows.isExhausted()) {
return Mono.empty();
}
Row row = rows.one();
return buildContentRetriever(fetchType, row).map(content ->
new MessageRepresentation(
cassandraMessageId,
row.getTimestamp(INTERNAL_DATE),
row.getLong(FULL_CONTENT_OCTETS),
row.getInt(BODY_START_OCTET),
new SharedByteArrayInputStream(content),
getPropertyBuilder(row),
hasAttachment(row),
getAttachments(row).collect(Guavate.toImmutableList())));
}
@Test
void messageAssertShouldSucceedWithTwoEqualsMessages() throws IOException {
String headerString = "name: headerName\n\n";
String bodyString = "body\n.\n";
Date date = new Date();
SimpleMailboxMessage message1 = new SimpleMailboxMessage(MESSAGE_ID, date, headerString.length() + bodyString.length(),
headerString.length(), new SharedByteArrayInputStream((headerString + bodyString).getBytes()), new Flags(), new PropertyBuilder(), MAILBOX_ID);
message1.setUid(UID);
SimpleMailboxMessage message2 = new SimpleMailboxMessage(MESSAGE_ID, date, headerString.length() + bodyString.length(),
headerString.length(), new SharedByteArrayInputStream((headerString + bodyString).getBytes()), new Flags(), new PropertyBuilder(), MAILBOX_ID);
message2.setUid(UID);
MessageAssert.assertThat(message1).isEqualTo(message2, MessageMapper.FetchType.Full);
}
@Test
void messageAssertShouldSucceedWhenBodyMismatchInFetchHeaderMode() throws IOException {
String headerString = "name: headerName\n\n";
String bodyString = "body\n.\n";
Date date = new Date();
SimpleMailboxMessage message1 = new SimpleMailboxMessage(MESSAGE_ID, date, headerString.length() + bodyString.length(),
headerString.length(), new SharedByteArrayInputStream((headerString + bodyString).getBytes()), new Flags(), new PropertyBuilder(), MAILBOX_ID);
message1.setUid(UID);
bodyString = "work\n.\n";
SimpleMailboxMessage message2 = new SimpleMailboxMessage(MESSAGE_ID, date, headerString.length() + bodyString.length(),
headerString.length(), new SharedByteArrayInputStream((headerString + bodyString).getBytes()), new Flags(), new PropertyBuilder(), MAILBOX_ID);
message2.setUid(UID);
MessageAssert.assertThat(message1).isEqualTo(message2, MessageMapper.FetchType.Headers);
}
@Test
void messageAssertShouldFailWhenBodyMismatchInFetchBodyMode() {
String headerString = "name: headerName\n\n";
String bodyString = "body\n.\n";
Date date = new Date();
SimpleMailboxMessage message1 = new SimpleMailboxMessage(MESSAGE_ID, date, headerString.length() + bodyString.length(),
headerString.length(), new SharedByteArrayInputStream((headerString + bodyString).getBytes()), new Flags(), new PropertyBuilder(), MAILBOX_ID);
message1.setUid(UID);
bodyString = "work\n.\n";
SimpleMailboxMessage message2 = new SimpleMailboxMessage(MESSAGE_ID, date, headerString.length() + bodyString.length(),
headerString.length(), new SharedByteArrayInputStream((headerString + bodyString).getBytes()), new Flags(), new PropertyBuilder(), MAILBOX_ID);
message2.setUid(UID);
assertThatThrownBy(() -> MessageAssert.assertThat(message1).isEqualTo(message2, MessageMapper.FetchType.Body))
.isInstanceOf(AssertionError.class);
}
public MetaDataWithContent appendMessageInMailbox(org.apache.james.mime4j.dom.Message message,
MessageManager messageManager,
Flags flags,
MailboxSession session) throws MailboxException {
byte[] messageContent = asBytes(message);
SharedByteArrayInputStream content = new SharedByteArrayInputStream(messageContent);
Date internalDate = new Date();
AppendResult appendResult = messageManager.appendMessage(MessageManager.AppendCommand.builder()
.withFlags(flags)
.build(content), session);
ComposedMessageId ids = appendResult.getId();
return MetaDataWithContent.builder()
.uid(ids.getUid())
.keywords(Keywords.lenientFactory().fromFlags(flags))
.internalDate(internalDate.toInstant())
.sharedContent(content)
.size(messageContent.length)
.attachments(appendResult.getMessageAttachments())
.mailboxId(messageManager.getId())
.messageId(ids.getMessageId())
.build();
}
/**
* Constructs a new MimeMessage with content initialized from the
* <code>source</code> MimeMessage. The new message is independent
* of the original. <p>
*
* Note: The current implementation is rather inefficient, copying
* the data more times than strictly necessary.
*
* @param source the message to copy content from
* @exception MessagingException for failures
* @since JavaMail 1.2
*/
public MimeMessage(MimeMessage source) throws MessagingException {
super(source.session);
flags = source.getFlags();
if (flags == null) // make sure flags is always set
flags = new Flags();
ByteArrayOutputStream bos;
int size = source.getSize();
if (size > 0)
bos = new ByteArrayOutputStream(size);
else
bos = new ByteArrayOutputStream();
try {
strict = source.strict;
source.writeTo(bos);
bos.close();
SharedByteArrayInputStream bis =
new SharedByteArrayInputStream(bos.toByteArray());
parse(bis);
bis.close();
saved = true;
} catch (IOException ex) {
// should never happen, but just in case...
throw new MessagingException("IOException while copying message",
ex);
}
}
/**
* Send message.
*
* @param messageBody MIME message body
* @throws IOException on error
*/
public void sendMessage(byte[] messageBody) throws IOException {
try {
sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody)));
} catch (MessagingException e) {
throw new IOException(e.getMessage());
}
}
/**
* Send message.
*
* @param messageBody MIME message body
* @throws IOException on error
*/
public void sendMessage(byte[] messageBody) throws IOException {
try {
sendMessage(new MimeMessage(null, new SharedByteArrayInputStream(messageBody)));
} catch (MessagingException e) {
throw new IOException(e.getMessage());
}
}
public void testGetContent() throws IOException, MessagingException {
byte[] content = session.getContent(message);
assertNotNull(content);
MimeMessage mimeMessage = new MimeMessage(null, new SharedByteArrayInputStream(content));
assertTrue(mimeMessage.getHeader("To")[0].indexOf("[email protected]") >= 0);
assertEquals("Test subject", mimeMessage.getSubject());
assertEquals("Test message\n", mimeMessage.getContent());
}
private SimpleMailboxMessage createMessage(Mailbox mailbox) throws MailboxException {
int size = 45;
int bodyStartOctet = 25;
byte[] content = "Subject: test\r\n\r\nBody\r\n".getBytes(StandardCharsets.UTF_8);
SimpleMailboxMessage message = new SimpleMailboxMessage(MESSAGE_ID, new Date(),
size, bodyStartOctet, new SharedByteArrayInputStream(content), new Flags(), new PropertyBuilder(),
mailbox.getMailboxId());
MessageMetaData messageMetaData = mapperFactory.createMessageMapper(null).add(mailbox, message);
message.setUid(messageMetaData.getUid());
return message;
}
/**
* Create a copy of the given message
*/
public JPAStreamingMailboxMessage(JPAMailbox mailbox, MessageUid uid, ModSeq modSeq, MailboxMessage message) throws MailboxException {
super(mailbox, uid, modSeq, message);
try {
this.content = new SharedByteArrayInputStream(IOUtils.toByteArray(message.getFullContent()));
this.header = getHeaderContent();
this.body = getBodyContent();
} catch (IOException e) {
throw new MailboxException("Unable to parse message",e);
}
}
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
messageUtils = new MessageUtils(uidProvider, modSeqProvider);
message = new SimpleMailboxMessage(MESSAGE_ID, new Date(), CONTENT.length(), BODY_START,
new SharedByteArrayInputStream(CONTENT.getBytes()), new Flags(), new PropertyBuilder(), mailbox.getMailboxId());
}
public MessageRepresentation(MessageId messageId, Date internalDate, Long size, Integer bodySize, SharedByteArrayInputStream content,
PropertyBuilder propertyBuilder, boolean hasAttachment, List<MessageAttachmentRepresentation> attachments) {
this.messageId = messageId;
this.internalDate = internalDate;
this.size = size;
this.bodySize = bodySize;
this.content = content;
this.propertyBuilder = propertyBuilder;
this.hasAttachment = hasAttachment;
this.attachments = attachments;
}
private SimpleMailboxMessage createMessage(MessageId messageId, String content, int bodyStart, PropertyBuilder propertyBuilder, Collection<MessageAttachmentMetadata> attachments) {
return SimpleMailboxMessage.builder()
.messageId(messageId)
.mailboxId(MAILBOX_ID)
.uid(messageUid)
.internalDate(new Date())
.bodyStartOctet(bodyStart)
.size(content.length())
.content(new SharedByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)))
.flags(new Flags())
.propertyBuilder(propertyBuilder)
.addAttachments(attachments)
.build();
}
private static SharedByteArrayInputStream copyFullContent(MailboxMessage original) throws MailboxException {
try {
return new SharedByteArrayInputStream(IOUtils.toByteArray(original.getFullContent()));
} catch (IOException e) {
throw new MailboxException("Unable to parse message", e);
}
}
private static MailboxMessage createMessage(MailboxId mailboxId, Flags flags, MessageId messageId, MessageUid uid) {
MailboxMessage mailboxMessage = new SimpleMailboxMessage(messageId, new Date(), MESSAGE_CONTENT.length, 1256,
new SharedByteArrayInputStream(MESSAGE_CONTENT), flags, new PropertyBuilder(), mailboxId);
mailboxMessage.setModSeq(MOD_SEQ);
mailboxMessage.setUid(uid);
return mailboxMessage;
}
private MailboxMessage createMessage(Flags messageFlags) {
String content = "Any content";
int bodyStart = 10;
return new SimpleMailboxMessage(new DefaultMessageId(), new Date(), content.length(), bodyStart,
new SharedByteArrayInputStream(content.getBytes()), messageFlags, new PropertyBuilder(), TestId.of(1));
}
private SimpleMailboxMessage createMessage(Mailbox mailbox, String content, int bodyStart, PropertyBuilder propertyBuilder) {
return new SimpleMailboxMessage(mapperProvider.generateMessageId(),
new Date(),
content.length(),
bodyStart,
new SharedByteArrayInputStream(content.getBytes()),
new Flags(),
propertyBuilder,
mailbox.getMailboxId());
}
private MailboxMessage createMailboxMessage(MailboxId mailboxId, MessageId messageId, MessageUid uid, Date internalDate,
String content, int bodyStart, PropertyBuilder propertyBuilder) {
SimpleMailboxMessage simpleMailboxMessage = new SimpleMailboxMessage(messageId, internalDate, content.length(),
bodyStart, new SharedByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)), new Flags(), propertyBuilder, mailboxId);
simpleMailboxMessage.setUid(uid);
simpleMailboxMessage.setModSeq(ModSeq.first());
return simpleMailboxMessage;
}
private MailboxMessage createMessage(Mailbox mailbox, MessageId messageId, String content, int bodyStart, PropertyBuilder propertyBuilder) {
SimpleMailboxMessage simpleMailboxMessage = new SimpleMailboxMessage(messageId, INTERNAL_DATE, content.length(),
bodyStart, new SharedByteArrayInputStream(content.getBytes()), new Flags(), propertyBuilder, mailbox.getMailboxId());
simpleMailboxMessage.setUid(MESSAGE_UID);
return simpleMailboxMessage;
}
@BeforeEach
void setUp() {
message1 = new SimpleMailboxMessage(MESSAGE_ID, DATE, HEADER_STRING.length() + BODY_STRING.length(),
HEADER_STRING.length(), new SharedByteArrayInputStream((HEADER_STRING + BODY_STRING).getBytes()), new Flags(), new PropertyBuilder(), MAILBOX_ID);
message1.setUid(UID);
message1.setModSeq(MODSEQ);
}
public MailboxMessage build(MessageId messageId) throws Exception {
byte[] headerContent = getHeaderContent();
SimpleMailboxMessage mailboxMessage = new SimpleMailboxMessage(messageId, internalDate, size, headerContent.length,
new SharedByteArrayInputStream(Bytes.concat(headerContent, body)), flags, new PropertyBuilder(), mailboxId, NO_ATTACHMENTS);
mailboxMessage.setUid(uid);
return mailboxMessage;
}
@Test
public void serviceShouldSendMultipartMailContainingDSNPart() throws Exception {
FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
.mailetName(MAILET_NAME)
.mailetContext(fakeMailContext)
.build();
dsnBounce.init(mailetConfig);
MailAddress senderMailAddress = new MailAddress("[email protected]");
FakeMail mail = FakeMail.builder()
.name(MAILET_NAME)
.sender(senderMailAddress)
.attribute(DELIVERY_ERROR_ATTRIBUTE)
.mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
.setText("My content"))
.recipient("[email protected]")
.lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
.remoteAddr("remoteHost")
.build();
dsnBounce.service(mail);
String expectedContent = "Reporting-MTA: dns; myhost\n" +
"Received-From-MTA: dns; 111.222.333.444\n" +
"\n" +
"Final-Recipient: rfc822; [email protected]\n" +
"Action: failed\n" +
"Status: Delivery error\n" +
"Diagnostic-Code: X-James; Delivery error\n" +
"Last-Attempt-Date: Thu, 8 Sep 2016 14:25:52 XXXXX (UTC)\n";
List<SentMail> sentMails = fakeMailContext.getSentMails();
assertThat(sentMails).hasSize(1);
SentMail sentMail = sentMails.get(0);
MimeMessage sentMessage = sentMail.getMsg();
MimeMultipart content = (MimeMultipart) sentMessage.getContent();
SharedByteArrayInputStream actualContent = (SharedByteArrayInputStream) content.getBodyPart(1).getContent();
assertThat(IOUtils.toString(actualContent, StandardCharsets.UTF_8)).isEqualTo(expectedContent);
}
@Test
public void serviceShouldAttachTheOriginalMailHeadersOnlyWhenAttachmentIsEqualToHeads() throws Exception {
FakeMailetConfig mailetConfig = FakeMailetConfig.builder()
.mailetName(MAILET_NAME)
.mailetContext(fakeMailContext)
.setProperty("attachment", "heads")
.build();
dsnBounce.init(mailetConfig);
MailAddress senderMailAddress = new MailAddress("[email protected]");
FakeMail mail = FakeMail.builder()
.name(MAILET_NAME)
.sender(senderMailAddress)
.mimeMessage(MimeMessageBuilder.mimeMessageBuilder()
.setText("My content")
.addHeader("myHeader", "myValue")
.setSubject("mySubject"))
.recipient("[email protected]")
.lastUpdated(Date.from(Instant.parse("2016-09-08T14:25:52.000Z")))
.build();
dsnBounce.service(mail);
List<SentMail> sentMails = fakeMailContext.getSentMails();
assertThat(sentMails).hasSize(1);
SentMail sentMail = sentMails.get(0);
assertThat(sentMail.getSender()).isNull();
assertThat(sentMail.getRecipients()).containsOnly(senderMailAddress);
MimeMessage sentMessage = sentMail.getMsg();
MimeMultipart content = (MimeMultipart) sentMessage.getContent();
BodyPart bodyPart = content.getBodyPart(2);
SharedByteArrayInputStream actualContent = (SharedByteArrayInputStream) bodyPart.getContent();
assertThat(IOUtils.toString(actualContent, StandardCharsets.UTF_8))
.contains("Subject: mySubject")
.contains("myHeader: myValue");
assertThat(bodyPart.getContentType()).isEqualTo("text/rfc822-headers; name=mySubject");
}
public MetaDataWithContent appendMessageInMailboxes(CreationMessageEntry createdEntry,
List<MailboxId> targetMailboxes,
MailboxSession session) throws MailboxException {
Preconditions.checkArgument(!targetMailboxes.isEmpty());
ImmutableList<MessageAttachmentMetadata> messageAttachments = getMessageAttachments(session, createdEntry.getValue().getAttachments());
byte[] messageContent = mimeMessageConverter.convert(createdEntry, messageAttachments, session);
SharedByteArrayInputStream content = new SharedByteArrayInputStream(messageContent);
Date internalDate = Date.from(createdEntry.getValue().getDate().toInstant());
MessageManager mailbox = mailboxManager.getMailbox(targetMailboxes.get(0), session);
AppendResult appendResult = mailbox.appendMessage(
MessageManager.AppendCommand.builder()
.withInternalDate(internalDate)
.withFlags(getFlags(createdEntry.getValue()))
.notRecent()
.build(content),
session);
ComposedMessageId ids = appendResult.getId();
if (targetMailboxes.size() > 1) {
messageIdManager.setInMailboxes(ids.getMessageId(), targetMailboxes, session);
}
return MetaDataWithContent.builder()
.uid(ids.getUid())
.keywords(createdEntry.getValue().getKeywords())
.internalDate(internalDate.toInstant())
.sharedContent(content)
.size(messageContent.length)
.attachments(appendResult.getMessageAttachments())
.mailboxId(mailbox.getId())
.messageId(ids.getMessageId())
.build();
}
@BeforeEach
void setup() throws Exception {
String headers = "From: [email protected]\n"
+ "To: [email protected]\n"
+ "Cc: [email protected], [email protected]\n"
+ "Bcc: [email protected]\n"
+ "Subject: news\n";
String content = headers
+ "Hello! How are you?";
message = MetaDataWithContent.builder()
.uid(MessageUid.of(2))
.keywords(Keywords.strictFactory().from(Keyword.SEEN))
.size(content.length())
.internalDate(Instant.now())
.sharedContent(new SharedByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8)))
.attachments(ImmutableList.of())
.mailboxId(InMemoryId.of(3))
.messageId(TestMessageId.of(2))
.build();
MessageContentExtractor messageContentExtractor = new MessageContentExtractor();
HtmlTextExtractor htmlTextExtractor = new JsoupHtmlTextExtractor();
BlobManager blobManager = mock(BlobManager.class);
when(blobManager.toBlobId(any(MessageId.class))).thenReturn(BlobId.fromString("fake"));
MessageIdManager messageIdManager = mock(MessageIdManager.class);
MessageFullViewFactory messageFullViewFactory = new MessageFullViewFactory(blobManager, messageContentExtractor, htmlTextExtractor, messageIdManager,
new MemoryMessageFastViewProjection(new RecordingMetricFactory()));
jmapMessage = messageFullViewFactory.fromMetaDataWithContent(message).block();
envelope = EnvelopeUtils.fromMessage(jmapMessage);
}
@Disabled("JAMES-3202 Limitation of the current correct mode reindexation. We only check metadata and fix "
+ "inconsistencies with ES, but we don't check for inconsistencies from ES to metadata")
@Test
void userReprocessingWithCorrectModeShouldRemoveOrphanMessagesInES() throws Exception {
MailboxSession systemSession = mailboxManager.createSystemSession(USERNAME);
MailboxId mailboxId = mailboxManager.createMailbox(INBOX, systemSession).get();
Mailbox mailbox = mailboxManager.getMailbox(mailboxId, systemSession).getMailboxEntity();
byte[] content = "Simple message content".getBytes(StandardCharsets.UTF_8);
MessageUid uid = MessageUid.of(22L);
SimpleMailboxMessage message = SimpleMailboxMessage.builder()
.messageId(InMemoryMessageId.of(42L))
.uid(uid)
.content(new SharedByteArrayInputStream(content))
.size(content.length)
.internalDate(new Date(ZonedDateTime.parse("2018-02-15T15:54:02Z").toEpochSecond()))
.bodyStartOctet(0)
.flags(new Flags("myFlags"))
.propertyBuilder(new PropertyBuilder())
.mailboxId(mailboxId)
.build();
searchIndex.add(systemSession, mailbox, message).block();
String taskId = with()
.queryParam("task", "reIndex")
.queryParam("mode", "fixOutdated")
.post()
.jsonPath()
.get("taskId");
given()
.basePath(TasksRoutes.BASE)
.when()
.get(taskId + "/await");
assertThatThrownBy(() -> searchIndex.retrieveIndexedFlags(mailbox, uid).block())
.isInstanceOf(IndexNotFoundException.class);
}
@Disabled("JAMES-3202 Limitation of the current correct mode reindexation. We only check metadata and fix "
+ "inconsistencies with ES, but we don't check for inconsistencies from ES to metadata")
@Test
void fullReprocessingWithCorrectModeShouldRemoveOrphanMessagesInES() throws Exception {
MailboxSession systemSession = mailboxManager.createSystemSession(USERNAME);
MailboxId mailboxId = mailboxManager.createMailbox(INBOX, systemSession).get();
Mailbox mailbox = mailboxManager.getMailbox(mailboxId, systemSession).getMailboxEntity();
byte[] content = "Simple message content".getBytes(StandardCharsets.UTF_8);
MessageUid uid = MessageUid.of(22L);
SimpleMailboxMessage message = SimpleMailboxMessage.builder()
.messageId(InMemoryMessageId.of(42L))
.uid(uid)
.content(new SharedByteArrayInputStream(content))
.size(content.length)
.internalDate(new Date(ZonedDateTime.parse("2018-02-15T15:54:02Z").toEpochSecond()))
.bodyStartOctet(0)
.flags(new Flags("myFlags"))
.propertyBuilder(new PropertyBuilder())
.mailboxId(mailboxId)
.build();
searchIndex.add(systemSession, mailbox, message).block();
String taskId = with()
.post("/mailboxes?task=reIndex&mode=fixOutdated")
.jsonPath()
.get("taskId");
given()
.basePath(TasksRoutes.BASE)
.when()
.get(taskId + "/await");
assertThatThrownBy(() -> searchIndex.retrieveIndexedFlags(mailbox, uid).block())
.isInstanceOf(IndexNotFoundException.class);
}