Java Code Examples for javax.mail.Flags

The following examples show how to use javax.mail.Flags. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: micro-integrator   Author: wso2   File: GreenMailServer.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * Delete all emails in the inbox.
 *
 * @param protocol protocol used to connect to the server
 * @throws MessagingException if we're unable to connect to the store
 */
public static void deleteAllEmails(String protocol, GreenMailUser user) throws MessagingException {
    Folder inbox = null;
    Store store = getConnection(user, protocol);
    try {
        inbox = store.getFolder(EMAIL_INBOX);
        inbox.open(Folder.READ_WRITE);
        Message[] messages = inbox.getMessages();

        for (Message message : messages) {
            message.setFlag(Flags.Flag.DELETED, true);
            log.info("Deleted email Subject : " + message.getSubject());
        }
    } finally {
        if (inbox != null) {
            inbox.close(true);
        }
        if (store != null) {
            store.close();
        }
    }
}
 
Example #2
Source Project: james-project   Author: apache   File: CassandraIndexTableHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void updateIndexOnDeleteShouldNotDecrementUnseenMessageCountWhenSeen() throws Exception {
    MailboxMessage message = mock(MailboxMessage.class);
    when(message.createFlags()).thenReturn(new Flags());
    when(message.getUid()).thenReturn(MESSAGE_UID);
    testee.updateIndexOnAdd(message, MAILBOX_ID).block();

    testee.updateIndexOnDelete(new ComposedMessageIdWithMetaData(
            new ComposedMessageId(MAILBOX_ID, CASSANDRA_MESSAGE_ID, MESSAGE_UID),
            new Flags(Flags.Flag.SEEN),
            MODSEQ),
        MAILBOX_ID).block();

    Long actual = mailboxCounterDAO.countUnseenMessagesInMailbox(mailbox).block();
    assertThat(actual).isEqualTo(1);
}
 
Example #3
Source Project: james-project   Author: apache   File: CassandraIndexTableHandlerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void updateIndexOnFlagsUpdateShouldRemoveMessageInDeletedMessageWhenDeletedFlagIsUnset() {
    MailboxMessage message = mock(MailboxMessage.class);
    when(message.createFlags()).thenReturn(new Flags());
    when(message.getUid()).thenReturn(MESSAGE_UID);
    testee.updateIndexOnAdd(message, MAILBOX_ID).block();

    deletedMessageDAO.addDeleted(MAILBOX_ID, MESSAGE_UID).block();

    testee.updateIndexOnFlagsUpdate(MAILBOX_ID, UpdatedFlags.builder()
        .uid(MESSAGE_UID)
        .newFlags(new Flags())
        .oldFlags(new Flags(Flags.Flag.DELETED))
        .modSeq(MODSEQ)
        .build()).block();

    assertThat(
        deletedMessageDAO
            .retrieveDeletedMessage(MAILBOX_ID, MessageRange.all())
            .collectList()
            .block())
        .isEmpty();
}
 
Example #4
Source Project: james-project   Author: apache   File: CassandraMessageIdToImapUidDAOTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void updateShouldUpdateRecentFlag() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    ComposedMessageId composedMessageId = new ComposedMessageId(mailboxId, messageId, messageUid);
    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags(Flag.RECENT))
            .modSeq(ModSeq.of(2))
            .build();
    testee.updateMetadata(expectedComposedMessageId, ModSeq.of(1)).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example #5
Source Project: greenmail   Author: greenmail-mail-test   File: CommandParser.java    License: Apache License 2.0 6 votes vote down vote up
public void setFlag(String flagString, Flags flags) {
    if (flagString.equalsIgnoreCase(MessageFlags.ANSWERED)) {
        flags.add(Flags.Flag.ANSWERED);
    } else if (flagString.equalsIgnoreCase(MessageFlags.DELETED)) {
        flags.add(Flags.Flag.DELETED);
    } else if (flagString.equalsIgnoreCase(MessageFlags.DRAFT)) {
        flags.add(Flags.Flag.DRAFT);
    } else if (flagString.equalsIgnoreCase(MessageFlags.FLAGGED)) {
        flags.add(Flags.Flag.FLAGGED);
    } else if (flagString.equalsIgnoreCase(MessageFlags.SEEN)) {
        flags.add(Flags.Flag.SEEN);
    } else if (flagString.equalsIgnoreCase(MessageFlags.RECENT)) {
        flags.add(Flags.Flag.RECENT);
    } else {
        // User flag
        flags.add(flagString);
    }
}
 
Example #6
Source Project: james-project   Author: apache   File: CassandraMessageIdToImapUidDAOTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void updateShouldUpdateDeletedFlag() {
    CassandraMessageId messageId = messageIdFactory.of(UUIDs.timeBased());
    CassandraId mailboxId = CassandraId.timeBased();
    MessageUid messageUid = MessageUid.of(1);

    ComposedMessageId composedMessageId = new ComposedMessageId(mailboxId, messageId, messageUid);
    testee.insert(ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags())
            .modSeq(ModSeq.of(1))
            .build())
        .block();

    ComposedMessageIdWithMetaData expectedComposedMessageId = ComposedMessageIdWithMetaData.builder()
            .composedMessageId(composedMessageId)
            .flags(new Flags(Flag.DELETED))
            .modSeq(ModSeq.of(2))
            .build();
    testee.updateMetadata(expectedComposedMessageId, ModSeq.of(1)).block();

    List<ComposedMessageIdWithMetaData> messages = testee.retrieve(messageId, Optional.of(mailboxId)).collectList().block();
    assertThat(messages).containsOnly(expectedComposedMessageId);
}
 
Example #7
Source Project: james-project   Author: apache   File: AbstractCombinationManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void getMetadataFromMessageManagerShouldReturnRecentMessageWhenSetInMailboxesFromMessageIdManager() throws Exception {
    Flags recent = new Flags(Flag.RECENT);
    ComposedMessageId messageId = messageManager1.appendMessage(
        MessageManager.AppendCommand.builder()
            .withFlags(recent)
            .build(mailContent), session).getId();

    long mailbox2NextUid = messageManager2.getMetaData(true, session, MessageManager.MailboxMetaData.FetchGroup.UNSEEN_COUNT).getUidNext().asLong();
    messageIdManager.setInMailboxes(messageId.getMessageId(), ImmutableList.of(mailbox1.getMailboxId(), mailbox2.getMailboxId()), session);

    List<MessageUid> messageUids = messageManager2.getMetaData(true, session, MessageManager.MailboxMetaData.FetchGroup.UNSEEN_COUNT).getRecent();

    assertThat(messageUids).hasSize(1);
    assertThat(messageUids.get(0).asLong()).isGreaterThanOrEqualTo(mailbox2NextUid);
}
 
Example #8
Source Project: alfresco-repository   Author: Alfresco   File: AlfrescoImapFolder.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Returns the list of messages that have no {@link javax.mail.Flags.Flag#DELETED} flag set for current user.
 * 
 * @return the list of non-deleted messages.
 */
@Override
protected List<SimpleStoredMessage> getNonDeletedMessagesInternal()
{
    if (logger.isDebugEnabled())
    {
        logger.debug("[getNonDeletedMessagesInternal] " + this);
    }
    List<SimpleStoredMessage> result = new ArrayList<SimpleStoredMessage>();

    Collection<SimpleStoredMessage> values = getMessagesInternal();
    for (SimpleStoredMessage message : values)
    {
        if (!getFlags(message).contains(Flags.Flag.DELETED))
        {
            result.add(message);
        }

    }
    if (logger.isDebugEnabled() && folderInfo != null)
    {
        logger.debug(folderInfo.getName() + " - Non deleted messages count:" + result.size());
    }
    return result;
}
 
Example #9
Source Project: james-project   Author: apache   File: GetMessageListMethodTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getMessageListShouldReturnAllMessagesWhenPositionIsNotGiven() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox");

    LocalDate date = LocalDate.now();
    ComposedMessageId message1 = mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
            new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), convertToDate(date.plusDays(1)), false, new Flags());
    ComposedMessageId message2 = mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
            new ByteArrayInputStream("Subject: test2\r\n\r\ntestmail".getBytes()), convertToDate(date), false, new Flags());
    await();

    given()
        .header("Authorization", aliceAccessToken.asString())
        .body("[[\"getMessageList\", {}, \"#0\"]]")
    .when()
        .post("/jmap")
    .then()
        .statusCode(200)
        .body(NAME, equalTo("messageList"))
        .body(ARGUMENTS + ".messageIds", containsInAnyOrder(message1.getMessageId().serialize(), message2.getMessageId().serialize()));
}
 
Example #10
Source Project: james-project   Author: apache   File: CassandraMessageIdToImapUidDAO.java    License: Apache License 2.0 6 votes vote down vote up
public Mono<Boolean> updateMetadata(ComposedMessageIdWithMetaData composedMessageIdWithMetaData, ModSeq oldModSeq) {
    ComposedMessageId composedMessageId = composedMessageIdWithMetaData.getComposedMessageId();
    Flags flags = composedMessageIdWithMetaData.getFlags();
    return cassandraAsyncExecutor.executeReturnApplied(update.bind()
            .setLong(MOD_SEQ, composedMessageIdWithMetaData.getModSeq().asLong())
            .setBool(ANSWERED, flags.contains(Flag.ANSWERED))
            .setBool(DELETED, flags.contains(Flag.DELETED))
            .setBool(DRAFT, flags.contains(Flag.DRAFT))
            .setBool(FLAGGED, flags.contains(Flag.FLAGGED))
            .setBool(RECENT, flags.contains(Flag.RECENT))
            .setBool(SEEN, flags.contains(Flag.SEEN))
            .setBool(USER, flags.contains(Flag.USER))
            .setSet(USER_FLAGS, ImmutableSet.copyOf(flags.getUserFlags()))
            .setUUID(MESSAGE_ID, ((CassandraMessageId) composedMessageId.getMessageId()).get())
            .setUUID(MAILBOX_ID, ((CassandraId) composedMessageId.getMailboxId()).asUuid())
            .setLong(IMAP_UID, composedMessageId.getUid().asLong())
            .setLong(MOD_SEQ_CONDITION, oldModSeq.asLong()));
}
 
Example #11
Source Project: javamail-mock2   Author: salyh   File: MailboxFolder.java    License: Apache License 2.0 6 votes vote down vote up
public synchronized Message[] getByFlags(final Flags flags, final boolean mustSet /*final Folder folder*/) throws MessagingException {
    checkExists();
    final List<MockMessage> sms = new ArrayList<MockMessage>();
    int num = 0;

    for (final MockMessage mockMessage : new TreeSet<MockMessage>(messages.values())) {

        if (mustSet && mockMessage.getFlags().contains(flags) || !mustSet && !mockMessage.getFlags().contains(flags)) {
            mockMessage.setMessageNumber(++num);
            // mockMessage.setFolder(folder);
            sms.add(mockMessage);
        }

    }
    logger.debug("getByFlags() for " + getFullName() + " returns " + sms.size());
    return sms.toArray(new Message[sms.size()]);
}
 
Example #12
Source Project: james-project   Author: apache   File: FlagsExtraField.java    License: Apache License 2.0 6 votes vote down vote up
private static String systemFlagToString(Flags.Flag flag) throws RuntimeException {
    if (flag == Flags.Flag.ANSWERED) {
        return "\\ANSWERED";
    } else if (flag == Flags.Flag.DELETED) {
        return "\\DELETED";
    } else if (flag == Flags.Flag.DRAFT) {
        return "\\DRAFT";
    } else if (flag == Flags.Flag.FLAGGED) {
        return "\\FLAGGED";
    } else if (flag == Flags.Flag.RECENT) {
        return "\\RECENT";
    } else if (flag == Flags.Flag.SEEN) {
        return "\\SEEN";
    }
    throw new RuntimeException("Unknown system flag");
}
 
Example #13
Source Project: james-project   Author: apache   File: GetMessageListMethodTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void getMessageListUnsetAnsweredFilterShouldReturnOnlyNotAnsweredMessages() throws Exception {
    mailboxProbe.createMailbox(MailboxConstants.USER_NAMESPACE, ALICE.asString(), "mailbox");

    ComposedMessageId messageNotAnswered = mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
        new ByteArrayInputStream("Subject: test\r\n\r\ntestmail".getBytes()), new Date(), false, new Flags());
    ComposedMessageId messageAnswered = mailboxProbe.appendMessage(ALICE.asString(), ALICE_MAILBOX,
        ClassLoader.getSystemResourceAsStream("eml/twoAttachments.eml"), new Date(), false, new Flags(Flags.Flag.ANSWERED));

    await();

    given()
        .header("Authorization", aliceAccessToken.asString())
        .body("[[\"getMessageList\", {\"filter\":{\"isAnswered\":\"false\"}}, \"#0\"]]")
    .when()
        .post("/jmap")
    .then()
        .statusCode(200)
        .body(NAME, equalTo("messageList"))
        .body(ARGUMENTS + ".messageIds", allOf(
                containsInAnyOrder(messageNotAnswered.getMessageId().serialize()),
                not(containsInAnyOrder(messageAnswered.getMessageId().serialize()))));
}
 
Example #14
Source Project: james-project   Author: apache   File: MailboxMessageAssertTest.java    License: Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source Project: james-project   Author: apache   File: AbstractCombinationManagerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void setFlagsFromMessageManagerAndSetFlagsFromMessageIdManagerShouldUpdateSameApplicableFlag() throws Exception {
    Flags customFlag1 = new Flags(Flag.ANSWERED);
    Flags customFlag2 = new Flags("customFlag2");
    MessageId messageId = messageManager1.appendMessage(
        MessageManager.AppendCommand.builder()
            .withFlags(customFlag1)
            .build(mailContent), session)
        .getId().getMessageId();


    messageIdManager.setFlags(customFlag2, FlagsUpdateMode.ADD, messageId, ImmutableList.of(mailbox1.getMailboxId()), session);
    messageManager1.setFlags(customFlag2, FlagsUpdateMode.ADD, MessageRange.all(), session);

    Flags applicableFlags = messageManager1.getApplicableFlags(session);

    assertThat(applicableFlags)
        .isEqualTo(ApplicableFlagBuilder
            .from(customFlag1, customFlag2)
            .build());
}
 
Example #16
Source Project: james-project   Author: apache   File: MessageFlags.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns IMAP formatted String naming flags.
 * 
 * @return <code>Collection</code> of <code>String</code>'s naming the
 *         flags.
 */
public static Collection<String> names(Flags flags) {
    final Collection<String> results = new ArrayList<>();
    if (flags.contains(Flags.Flag.ANSWERED)) {
        results.add(ANSWERED_OUTPUT_CAPITALISED);
    }
    if (flags.contains(Flags.Flag.DELETED)) {
        results.add(DELETED_OUTPUT_CAPITALISED);
    }
    if (flags.contains(Flags.Flag.DRAFT)) {
        results.add(DRAFT_OUTPUT_CAPITALISED);
    }
    if (flags.contains(Flags.Flag.FLAGGED)) {
        results.add(FLAGGED_OUTPUT_CAPITALISED);
    }
    if (flags.contains(Flags.Flag.RECENT)) {
        results.add(RECENT_OUTPUT_CAPITALISED);
    }
    if (flags.contains(Flags.Flag.SEEN)) {
        results.add(SEEN_OUTPUT_CAPITALISED);
    }
    
    // Add user flags
    String[] userFlags = flags.getUserFlags();
    Collections.addAll(results, userFlags);

    if (flags.contains(Flags.Flag.USER)) {
        results.add(USER_OUTPUT_CAPITALISED);
    }
    return results;
}
 
Example #17
Source Project: james-project   Author: apache   File: GetMessagesMethodStepdefs.java    License: Apache License 2.0 5 votes vote down vote up
@Given("^the user has a message \"([^\"]*)\" in \"([^\"]*)\" mailbox, composed of a multipart with inlined text part and inlined html part$")
public void appendMessageFromFileInlinedMultipart(String messageName, String mailbox) throws Exception {
    ZonedDateTime dateTime = ZonedDateTime.parse("2014-10-30T14:12:00Z");
    MessageId id = mainStepdefs.mailboxProbe.appendMessage(userStepdefs.getConnectedUser(),
        MailboxPath.forUser(Username.of(userStepdefs.getConnectedUser()), mailbox),
        ClassLoader.getSystemResourceAsStream("eml/inlinedMultipart.eml"),
        Date.from(dateTime.toInstant()), false, new Flags())
        .getMessageId();
    messageIdStepdefs.addMessageId(messageName, id);
    mainStepdefs.awaitMethod.run();
}
 
Example #18
Source Project: james-project   Author: apache   File: ApplicableFlagBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void shouldNeverRetainRecentAndUserFlag() {
    Flags result = ApplicableFlagBuilder.builder()
        .add(new Flags(Flags.Flag.RECENT))
        .add(new Flags(Flags.Flag.USER))
        .build();

    SoftAssertions.assertSoftly(softly -> {
        softly.assertThat(result.contains(Flags.Flag.RECENT)).isFalse();
        softly.assertThat(result.contains(Flags.Flag.USER)).isFalse();
    });
}
 
Example #19
Source Project: javamail-mock2   Author: salyh   File: IMAPMockFolder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void setFlags(final Message[] msgs, final Flags flag, final boolean value) throws MessagingException {
    abortIdle();
    checkOpened();

    for (final Message message : msgs) {

        final Message m = mailboxFolder.getById(((MockMessage) message).getMockid());

        if (m != null) {
            m.setFlags(flag, value);
        }
    }

}
 
Example #20
Source Project: mnIMAPSync   Author: manusa   File: MessageDeleter.java    License: Apache License 2.0 5 votes vote down vote up
public void run() {
    long deleted = 0L;
    long skipped = 0L;
    try {
        final Folder targetFolder = storeDeleter.getTargetStore().getFolder(targetFolderName);
        //Opens a new connection per Thread
        targetFolder.open(Folder.READ_WRITE);
        final Message[] targetMessages = targetFolder.getMessages(start, end);
        targetFolder.fetch(targetMessages, MessageId.addHeaders(new FetchProfile()));
        for (Message message : targetMessages) {
            try {
                final MessageId id = new MessageId(message);
                if (!sourceFolderMessages.contains(id)) {
                    message.setFlag(Flags.Flag.DELETED, true);
                    deleted++;
                } else {
                    skipped++;
                }
            } catch (MessageId.MessageIdException ex) {
                //Usually messages that ran into this exception are spammy, so we skip them.
                skipped++;
            }
        }
        //Close folder and expunge flagged messages
        //Expunge only if folder is read write
        if (targetFolder.getMode() == Folder.READ_ONLY) {
            targetFolder.close(false);
        } else {
            targetFolder.close(expunge);
        }
    } catch (MessagingException messagingException) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, messagingException);
    }
    storeDeleter.updatedMessagesDeletedCount(deleted);
    storeDeleter.updateMessagesSkippedCount(skipped);
}
 
Example #21
Source Project: james-project   Author: apache   File: FlagExtraFieldTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void getLocalFileDataLengthShouldReturnIntegerSize() {
    FlagsExtraField testee = new FlagsExtraField(new Flags());

    assertThat(testee.getLocalFileDataLength().getValue())
        .isEqualTo(0);
}
 
Example #22
Source Project: james-project   Author: apache   File: CassandraIndexTableHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void updateIndexOnAddShouldAddRecentWhenRecent() {
    MailboxMessage message = mock(MailboxMessage.class);
    when(message.createFlags()).thenReturn(new Flags(Flags.Flag.RECENT));
    when(message.getUid()).thenReturn(MESSAGE_UID);

    testee.updateIndexOnAdd(message, MAILBOX_ID).block();

    assertThat(mailboxRecentsDAO.getRecentMessageUidsInMailbox(MAILBOX_ID)
        .collectList()
        .block())
        .containsOnly(MESSAGE_UID);
}
 
Example #23
Source Project: james-project   Author: apache   File: MessageMetadataViewFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void fromMessageResultsShouldCombineKeywords() throws Exception {
    messageIdManager.setInMailboxes(message1.getMessageId(), ImmutableList.of(bobInbox.getId(), bobMailbox.getId()), session);
    bobMailbox.setFlags(new Flags(Flags.Flag.FLAGGED), MessageManager.FlagsUpdateMode.REPLACE, MessageRange.all(), session);

    MessageMetadataView actual = testee.fromMessageIds(ImmutableList.of(message1.getMessageId()), session).collectList().block().get(0);
    SoftAssertions.assertSoftly(softly -> {
       softly.assertThat(actual.getId()).isEqualTo(message1.getMessageId());
       softly.assertThat(actual.getKeywords()).isEqualTo(Keywords.strictFactory().from(Keyword.SEEN, Keyword.FLAGGED).asMap());
    });
}
 
Example #24
Source Project: james-project   Author: apache   File: UpdatedFlagsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void isUnchangedShouldReturnFalseWhenFlagOnlyInNewFlag() {
    UpdatedFlags updatedFlags = UpdatedFlags.builder()
        .newFlags(new Flags(Flags.Flag.RECENT))
        .oldFlags(new Flags())
        .uid(UID)
        .modSeq(MOD_SEQ)
        .build();

    assertThat(updatedFlags.isUnchanged(Flags.Flag.RECENT)).isFalse();
}
 
Example #25
Source Project: james-project   Author: apache   File: MessageMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void flagsReplacementShouldReturnAnUpdatedFlagHighlightingTheReplacement() throws MailboxException {
    saveMessages();
    ModSeq modSeq = messageMapper.getHighestModSeq(benwaInboxMailbox);
    Iterator<UpdatedFlags> updatedFlags = messageMapper.updateFlags(benwaInboxMailbox,
            new FlagsUpdateCalculator(new Flags(Flags.Flag.FLAGGED), FlagsUpdateMode.REPLACE), MessageRange.one(message1.getUid()));
    assertThat(Lists.newArrayList(updatedFlags))
        .containsOnly(UpdatedFlags.builder()
            .uid(message1.getUid())
            .modSeq(modSeq.next())
            .oldFlags(new Flags())
            .newFlags(new Flags(Flags.Flag.FLAGGED))
            .build());
}
 
Example #26
Source Project: james-project   Author: apache   File: StoreMessageManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Map<MessageUid, Flags> setFlags(final Flags flags, final FlagsUpdateMode flagsUpdateMode, final MessageRange set, MailboxSession mailboxSession) throws MailboxException {

    if (!isWriteable(mailboxSession)) {
        throw new ReadOnlyException(getMailboxPath());
    }

    trimFlags(flags, mailboxSession);

    MessageMapper messageMapper = mapperFactory.getMessageMapper(mailboxSession);

    Iterator<UpdatedFlags> it = messageMapper.execute(() -> messageMapper.updateFlags(getMailboxEntity(), new FlagsUpdateCalculator(flags, flagsUpdateMode), set));
    List<UpdatedFlags> updatedFlags = Iterators.toStream(it).collect(Guavate.toImmutableList());

    eventBus.dispatch(EventFactory.flagsUpdated()
            .randomEventId()
            .mailboxSession(mailboxSession)
            .mailbox(getMailboxEntity())
            .updatedFlags(updatedFlags)
            .build(),
            new MailboxIdRegistrationKey(mailbox.getMailboxId()))
        .subscribeOn(Schedulers.elastic())
        .block();

    return updatedFlags.stream().collect(Guavate.toImmutableMap(
        UpdatedFlags::getUid,
        UpdatedFlags::getNewFlags));
}
 
Example #27
Source Project: james-project   Author: apache   File: FlagExtraFieldTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void getCentralDirectoryDataShouldReturnByteArraysOfSystemFlagSet() {
    Flags flags = new Flags();
    flags.add(Flags.Flag.SEEN);
    FlagsExtraField testee = new FlagsExtraField(flags);

    assertThat(testee.getCentralDirectoryData())
        .isEqualTo("\\SEEN".getBytes(StandardCharsets.UTF_8));
}
 
Example #28
Source Project: james-project   Author: apache   File: MessageIdMapperTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
void setFlagsShouldWorkWithConcurrencyWithRemove() throws Exception {
    Assume.assumeTrue(mapperProvider.getSupportedCapabilities().contains(MapperProvider.Capabilities.THREAD_SAFE_FLAGS_UPDATE));
    message1.setUid(mapperProvider.generateMessageUid());
    message1.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message1);

    int threadCount = 4;
    int updateCount = 20;
    ConcurrentTestRunner.builder()
        .operation((threadNumber, step) -> {
            if (step  < updateCount / 2) {
                sut.setFlags(message1.getMessageId(),
                    ImmutableList.of(message1.getMailboxId()),
                    new Flags("custom-" + threadNumber + "-" + step),
                    FlagsUpdateMode.ADD);
            } else {
                sut.setFlags(message1.getMessageId(),
                    ImmutableList.of(message1.getMailboxId()),
                    new Flags("custom-" + threadNumber + "-" + (updateCount - step - 1)),
                    FlagsUpdateMode.REMOVE);
            }
        })
        .threadCount(threadCount)
        .operationCount(updateCount)
        .runSuccessfullyWithin(Duration.ofMinutes(1));

    List<MailboxMessage> messages = sut.find(ImmutableList.of(message1.getMessageId()), MessageMapper.FetchType.Body);
    assertThat(messages).hasSize(1);
    assertThat(messages.get(0).createFlags().getUserFlags()).isEmpty();
}
 
Example #29
Source Project: james-project   Author: apache   File: OldKeywordTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void applyStateShouldReturnUnreadFlagWhenUnreadSetOnSeenMessage() {
    Optional<OldKeyword> testee = OldKeyword.builder()
        .isUnread(Optional.of(true))
        .computeOldKeyword();

    assertThat(testee.get().applyToState(new Flags(Flag.SEEN))).isEqualTo(new Flags());
}
 
Example #30
Source Project: james-project   Author: apache   File: UpdateMessagePatchTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void applyStateShouldKeepKeywordsWhenNoKeywordPatchDefined() {
    UpdateMessagePatch messagePatch = UpdateMessagePatch.builder()
        .build();
    Flags flags = FlagsBuilder.builder()
        .add(Flags.Flag.DELETED, Flags.Flag.RECENT, Flags.Flag.DRAFT)
        .build();
    assertThat(messagePatch.applyToState(flags)).isEqualTo(flags);
}