Example usage for javax.mail Flags Flags

List of usage examples for javax.mail Flags Flags

Introduction

In this page you can find the example usage for javax.mail Flags Flags.

Prototype

public Flags(String flag) 

Source Link

Document

Construct a Flags object initialized with the given user flag.

Usage

From source file:org.apache.james.mailbox.store.mail.model.MessageIdMapperTest.java

@Test
public void setFlagsShouldNotModifyModSeqWhenMailboxIdsIsEmpty() throws Exception {
    message1.setUid(mapperProvider.generateMessageUid());
    long modSeq = mapperProvider.generateModSeq(benwaInboxMailbox);
    message1.setModSeq(modSeq);//  ww w. ja v  a2  s . c om
    sut.save(message1);

    MessageId messageId = message1.getMessageId();
    Flags newFlags = new Flags(Flag.ANSWERED);
    sut.setFlags(messageId, ImmutableList.of(), newFlags, FlagsUpdateMode.REMOVE);

    List<MailboxMessage> messages = sut.find(ImmutableList.of(messageId), MessageMapper.FetchType.Body);
    assertThat(messages).hasSize(1);
    assertThat(messages.get(0).getModSeq()).isEqualTo(modSeq);
}

From source file:org.apache.james.mailbox.store.mail.model.MessageIdMapperTest.java

@Test
public void setFlagsShouldUpdateModSeqWhenMessageIsInOneMailbox() throws Exception {
    message1.setUid(mapperProvider.generateMessageUid());
    long modSeq = mapperProvider.generateModSeq(benwaInboxMailbox);
    message1.setModSeq(modSeq);// ww  w  .j  a v a 2 s. c om
    sut.save(message1);

    MessageId messageId = message1.getMessageId();
    sut.setFlags(messageId, ImmutableList.of(message1.getMailboxId()), new Flags(Flag.ANSWERED),
            FlagsUpdateMode.ADD);

    List<MailboxMessage> messages = sut.find(ImmutableList.of(messageId), MessageMapper.FetchType.Body);
    assertThat(messages).hasSize(1);
    assertThat(messages.get(0).getModSeq()).isGreaterThan(modSeq);
}

From source file:org.apache.james.mailbox.store.mail.model.MessageIdMapperTest.java

@Test
public void setFlagsShouldNotModifyFlagsWhenMailboxIdsIsEmpty() throws Exception {
    message1.setUid(mapperProvider.generateMessageUid());
    long modSeq = mapperProvider.generateModSeq(benwaInboxMailbox);
    message1.setModSeq(modSeq);//from   w ww  .j  a va2s. c  o  m
    Flags initialFlags = new Flags(Flags.Flag.DRAFT);
    message1.setFlags(initialFlags);
    sut.save(message1);

    MessageId messageId = message1.getMessageId();
    Flags newFlags = new Flags(Flag.ANSWERED);
    sut.setFlags(messageId, ImmutableList.of(), newFlags, FlagsUpdateMode.REMOVE);

    List<MailboxMessage> messages = sut.find(ImmutableList.of(messageId), MessageMapper.FetchType.Body);
    assertThat(messages).hasSize(1);
    assertThat(messages.get(0).createFlags()).isEqualTo(initialFlags);
}

From source file:org.springframework.integration.mail.ImapMailReceiverTests.java

@SuppressWarnings("resource")
@Test//  www.  j a va 2s.c  o m
public void testInitialIdleDelayWhenRecentIsSupported() throws Exception {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext(
            "ImapIdleChannelAdapterParserTests-context.xml", ImapIdleChannelAdapterParserTests.class);
    ImapIdleChannelAdapter adapter = context.getBean("simpleAdapter", ImapIdleChannelAdapter.class);

    QueueChannel channel = new QueueChannel();
    adapter.setOutputChannel(channel);

    ImapMailReceiver receiver = new ImapMailReceiver("imap:foo");
    receiver = spy(receiver);
    receiver.setBeanFactory(mock(BeanFactory.class));
    receiver.afterPropertiesSet();

    final IMAPFolder folder = mock(IMAPFolder.class);
    given(folder.getPermanentFlags()).willReturn(new Flags(Flags.Flag.RECENT));
    given(folder.isOpen()).willReturn(false).willReturn(true);
    given(folder.exists()).willReturn(true);

    DirectFieldAccessor adapterAccessor = new DirectFieldAccessor(adapter);
    adapterAccessor.setPropertyValue("mailReceiver", receiver);

    Field storeField = AbstractMailReceiver.class.getDeclaredField("store");
    storeField.setAccessible(true);
    Store store = mock(Store.class);
    given(store.isConnected()).willReturn(true);
    given(store.getFolder(Mockito.any(URLName.class))).willReturn(folder);
    storeField.set(receiver, store);

    willAnswer(invocation -> folder).given(receiver).getFolder();

    MimeMessage mailMessage = mock(MimeMessage.class);
    Flags flags = mock(Flags.class);
    given(mailMessage.getFlags()).willReturn(flags);
    final Message[] messages = new Message[] { mailMessage };

    willAnswer(invocation -> messages).given(receiver).searchForNewMessages();

    willAnswer(invocation -> null).given(receiver).fetchMessages(messages);

    final CountDownLatch idles = new CountDownLatch(2);
    willAnswer(invocation -> {
        idles.countDown();
        Thread.sleep(5000);
        return null;
    }).given(folder).idle();

    adapter.start();

    /*
     * Idle takes 5 seconds; since this server supports RECENT, we should
     * not receive any early messages.
     */
    assertNull(channel.receive(3000));
    assertNotNull(channel.receive(5000));
    assertTrue(idles.await(5, TimeUnit.SECONDS));
    adapter.stop();
    context.close();
}

From source file:org.apache.james.mailbox.store.mail.model.MessageIdMapperTest.java

@Test
public void setFlagsShouldUpdateFlagsWhenMessageIsInTwoMailboxes() throws Exception {
    message1.setUid(mapperProvider.generateMessageUid());
    message1.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message1);/*from ww w.  j a  v a2  s.c  o m*/

    SimpleMailboxMessage message1InOtherMailbox = SimpleMailboxMessage.copy(benwaWorkMailbox.getMailboxId(),
            message1);
    message1InOtherMailbox.setUid(mapperProvider.generateMessageUid());
    message1InOtherMailbox.setModSeq(mapperProvider.generateModSeq(benwaWorkMailbox));
    sut.save(message1InOtherMailbox);

    MessageId messageId = message1.getMessageId();
    sut.setFlags(messageId, ImmutableList.of(message1.getMailboxId(), message1InOtherMailbox.getMailboxId()),
            new Flags(Flag.ANSWERED), FlagsUpdateMode.ADD);

    List<MailboxMessage> messages = sut.find(ImmutableList.of(messageId), MessageMapper.FetchType.Body);
    assertThat(messages).hasSize(2);
    assertThat(messages.get(0).isAnswered()).isTrue();
    assertThat(messages.get(1).isAnswered()).isTrue();
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder.// w w  w  .ja  va2 s  . co  m
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

From source file:org.apache.james.mailbox.store.StoreMessageManager.java

/**
 * Return a List which holds all uids of recent messages and optional reset
 * the recent flag on the messages for the uids
 * //from w w  w . j av a 2  s.  c o  m
 * @param reset
 * @param mailboxSession
 * @return list
 * @throws MailboxException
 */
protected List<Long> recent(final boolean reset, MailboxSession mailboxSession) throws MailboxException {
    if (reset) {
        if (!isWriteable(mailboxSession)) {
            throw new ReadOnlyException(getMailboxPath(), mailboxSession.getPathDelimiter());
        }
    }
    final MessageMapper messageMapper = mapperFactory.getMessageMapper(mailboxSession);

    return messageMapper.execute(new Mapper.Transaction<List<Long>>() {

        public List<Long> run() throws MailboxException {
            final List<Long> members = messageMapper.findRecentMessageUidsInMailbox(getMailboxEntity());

            // Convert to MessageRanges so we may be able to optimize the
            // flag update
            List<MessageRange> ranges = MessageRange.toRanges(members);
            for (MessageRange range : ranges) {
                if (reset) {
                    // only call save if we need to
                    messageMapper.updateFlags(getMailboxEntity(),
                            new FlagsUpdateCalculator(new Flags(Flag.RECENT), FlagsUpdateMode.REMOVE), range);
                }
            }
            return members;
        }

    });

}

From source file:org.apache.james.mailbox.store.mail.model.MessageIdMapperTest.java

@Test
public void setFlagsShouldWorkWhenCalledOnFirstMessage() throws Exception {
    message1.setUid(mapperProvider.generateMessageUid());
    message1.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message1);//from w  ww.j  av a 2 s .c o m
    message2.setUid(mapperProvider.generateMessageUid());
    message2.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message2);
    message3.setUid(mapperProvider.generateMessageUid());
    message3.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message3);
    message4.setUid(mapperProvider.generateMessageUid());
    message4.setModSeq(mapperProvider.generateModSeq(benwaInboxMailbox));
    sut.save(message4);

    MessageId messageId = message1.getMessageId();
    sut.setFlags(messageId, ImmutableList.of(message1.getMailboxId()), new Flags(Flag.ANSWERED),
            FlagsUpdateMode.ADD);

    List<MailboxMessage> messages = sut.find(ImmutableList.of(messageId), MessageMapper.FetchType.Body);
    assertThat(messages).hasSize(1);
    assertThat(messages.get(0).isAnswered()).isTrue();
}

From source file:org.exist.xquery.modules.mail.MessageListFunctions.java

private SearchTerm parseFlagTerm(Node terms) throws XPathException {
    SearchTerm st = null;//from  w ww.  j a  va  2 s  .com

    String flag = ((Element) terms).getAttribute("flag");
    String value = ((Element) terms).getAttribute("value");

    if (StringUtils.isEmpty(value)) {
        throw (new XPathException(this,
                "value not specified for term with type: " + ((Element) terms).getAttribute("type")));
    }

    if (flag != null && flag.length() > 0) {
        Flags flags = null;

        if (flag.equalsIgnoreCase("answered")) {
            flags = new Flags(Flags.Flag.ANSWERED);
        } else if (flag.equalsIgnoreCase("deleted")) {
            flags = new Flags(Flags.Flag.DELETED);
        } else if (flag.equalsIgnoreCase("draft")) {
            flags = new Flags(Flags.Flag.DRAFT);
        } else if (flag.equalsIgnoreCase("recent")) {
            flags = new Flags(Flags.Flag.RECENT);
        } else if (flag.equalsIgnoreCase("seen")) {
            flags = new Flags(Flags.Flag.SEEN);
        } else {
            throw (new XPathException(this, "Invalid flag: " + flag + ", for term with type: "
                    + ((Element) terms).getAttribute("type")));
        }

        st = new FlagTerm(flags, value.equalsIgnoreCase("true"));
    } else {
        throw (new XPathException(this, "flag attribute must be specified for term with type: "
                + ((Element) terms).getAttribute("type")));
    }

    return (st);
}

From source file:org.alfresco.repo.imap.AlfrescoImapFolder.java

/**
 *  Creates the EML message in the specified folder.
 *  //from ww w.  j a  v a  2s .  com
 *  @param folderFileInfo The folder to create message in.
 *  @param message The original MimeMessage.
 *  @return ID of the new message created 
 * @throws FileNotFoundException 
 * @throws FileExistsException 
 * @throws MessagingException 
 * @throws IOException 
 */
private long createMimeMessageInFolder(FileInfo folderFileInfo, MimeMessage message, Flags flags)
        throws FileExistsException, FileNotFoundException, IOException, MessagingException {
    String name = AlfrescoImapConst.MESSAGE_PREFIX + GUID.generate();
    FileFolderService fileFolderService = serviceRegistry.getFileFolderService();
    FileInfo messageFile = fileFolderService.create(folderFileInfo.getNodeRef(), name,
            ContentModel.TYPE_CONTENT);
    final long newMessageUid = (Long) messageFile.getProperties().get(ContentModel.PROP_NODE_DBID);
    name = AlfrescoImapConst.MESSAGE_PREFIX + newMessageUid + AlfrescoImapConst.EML_EXTENSION;
    fileFolderService.rename(messageFile.getNodeRef(), name);
    Flags newFlags = new Flags(flags);
    newFlags.add(Flag.RECENT);
    imapService.setFlags(messageFile, newFlags, true);

    if (extractAttachmentsEnabled) {
        imapService.extractAttachments(messageFile.getNodeRef(), message);
    }
    // Force persistence of the message to the repository
    new IncomingImapMessage(messageFile, serviceRegistry, message);
    return newMessageUid;
}