Example usage for javax.mail Flags add

List of usage examples for javax.mail Flags add

Introduction

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

Prototype

public void add(Flags f) 

Source Link

Document

Add all the flags in the given Flags object to this Flags object.

Usage

From source file:org.apache.james.jmap.model.UpdateMessagePatch.java

public Flags applyToState(Flags currentFlags) {
    Flags newStateFlags = new Flags();

    if (isFlagged().orElse(currentFlags.contains(Flags.Flag.FLAGGED))) {
        newStateFlags.add(Flags.Flag.FLAGGED);
    }/*from w  w  w.  ja v  a 2 s  .c  om*/
    if (isAnswered().orElse(currentFlags.contains(Flags.Flag.ANSWERED))) {
        newStateFlags.add(Flags.Flag.ANSWERED);
    }
    boolean shouldMessageBeMarkSeen = isUnread().map(b -> !b).orElse(currentFlags.contains(Flags.Flag.SEEN));
    if (shouldMessageBeMarkSeen) {
        newStateFlags.add(Flags.Flag.SEEN);
    }
    return newStateFlags;
}

From source file:org.apache.james.mailbox.maildir.mail.MaildirMessageMapper.java

/**
 * @see org.apache.james.mailbox.store.mail.AbstractMessageMapper#copy(org.apache
 *      .james.mailbox.store.mail.model.Mailbox, long, long,
 *      MailboxMessage)/* w ww  .j  av a2  s  .com*/
 */
@Override
protected MessageMetaData copy(Mailbox mailbox, long uid, long modSeq, MailboxMessage original)
        throws MailboxException {
    SimpleMailboxMessage theCopy = SimpleMailboxMessage.copy(mailbox.getMailboxId(), original);
    Flags flags = theCopy.createFlags();
    flags.add(Flag.RECENT);
    theCopy.setFlags(flags);
    return save(mailbox, theCopy);
}

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

public Flags createFlags() {
    final Flags flags = new Flags();

    if (isAnswered()) {
        flags.add(Flags.Flag.ANSWERED);
    }//w w  w . j  ava  2  s.c  om
    if (isDeleted()) {
        flags.add(Flags.Flag.DELETED);
    }
    if (isDraft()) {
        flags.add(Flags.Flag.DRAFT);
    }
    if (isFlagged()) {
        flags.add(Flags.Flag.FLAGGED);
    }
    if (isRecent()) {
        flags.add(Flags.Flag.RECENT);
    }
    if (isSeen()) {
        flags.add(Flags.Flag.SEEN);
    }
    return flags;
}

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

/**
 * @see org.apache.james.mailbox.MessageManager#appendMessage(java.io.InputStream,
 *      java.util.Date, org.apache.james.mailbox.MailboxSession, boolean,
 *      javax.mail.Flags)/*from  w w  w. j av a 2  s  .  co m*/
 */
public long appendMessage(InputStream msgIn, Date internalDate, final MailboxSession mailboxSession,
        boolean isRecent, Flags flagsToBeSet) throws MailboxException {

    File file = null;
    TeeInputStream tmpMsgIn = null;
    BodyOffsetInputStream bIn = null;
    FileOutputStream out = null;
    SharedFileInputStream contentIn = null;

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

    try {
        // Create a temporary file and copy the message to it. We will work
        // with the file as
        // source for the InputStream
        file = File.createTempFile("imap", ".msg");
        out = new FileOutputStream(file);

        tmpMsgIn = new TeeInputStream(msgIn, out);

        bIn = new BodyOffsetInputStream(tmpMsgIn);
        // Disable line length... This should be handled by the smtp server
        // component and not the parser itself
        // https://issues.apache.org/jira/browse/IMAP-122
        MimeConfig config = MimeConfig.custom().setMaxLineLen(-1).setMaxHeaderLen(-1).build();

        final MimeTokenStream parser = new MimeTokenStream(config, new DefaultBodyDescriptorBuilder());

        parser.setRecursionMode(RecursionMode.M_NO_RECURSE);
        parser.parse(bIn);
        final HeaderImpl header = new HeaderImpl();

        EntityState next = parser.next();
        while (next != EntityState.T_BODY && next != EntityState.T_END_OF_STREAM
                && next != EntityState.T_START_MULTIPART) {
            if (next == EntityState.T_FIELD) {
                header.addField(parser.getField());
            }
            next = parser.next();
        }
        final MaximalBodyDescriptor descriptor = (MaximalBodyDescriptor) parser.getBodyDescriptor();
        final PropertyBuilder propertyBuilder = new PropertyBuilder();
        final String mediaType;
        final String mediaTypeFromHeader = descriptor.getMediaType();
        final String subType;
        if (mediaTypeFromHeader == null) {
            mediaType = "text";
            subType = "plain";
        } else {
            mediaType = mediaTypeFromHeader;
            subType = descriptor.getSubType();
        }
        propertyBuilder.setMediaType(mediaType);
        propertyBuilder.setSubType(subType);
        propertyBuilder.setContentID(descriptor.getContentId());
        propertyBuilder.setContentDescription(descriptor.getContentDescription());
        propertyBuilder.setContentLocation(descriptor.getContentLocation());
        propertyBuilder.setContentMD5(descriptor.getContentMD5Raw());
        propertyBuilder.setContentTransferEncoding(descriptor.getTransferEncoding());
        propertyBuilder.setContentLanguage(descriptor.getContentLanguage());
        propertyBuilder.setContentDispositionType(descriptor.getContentDispositionType());
        propertyBuilder.setContentDispositionParameters(descriptor.getContentDispositionParameters());
        propertyBuilder.setContentTypeParameters(descriptor.getContentTypeParameters());
        // Add missing types
        final String codeset = descriptor.getCharset();
        if (codeset == null) {
            if ("TEXT".equalsIgnoreCase(mediaType)) {
                propertyBuilder.setCharset("us-ascii");
            }
        } else {
            propertyBuilder.setCharset(codeset);
        }

        final String boundary = descriptor.getBoundary();
        if (boundary != null) {
            propertyBuilder.setBoundary(boundary);
        }
        if ("text".equalsIgnoreCase(mediaType)) {
            final CountingInputStream bodyStream = new CountingInputStream(parser.getInputStream());
            bodyStream.readAll();
            long lines = bodyStream.getLineCount();
            bodyStream.close();
            next = parser.next();
            if (next == EntityState.T_EPILOGUE) {
                final CountingInputStream epilogueStream = new CountingInputStream(parser.getInputStream());
                epilogueStream.readAll();
                lines += epilogueStream.getLineCount();
                epilogueStream.close();

            }
            propertyBuilder.setTextualLineCount(lines);
        }

        final Flags flags;
        if (flagsToBeSet == null) {
            flags = new Flags();
        } else {
            flags = flagsToBeSet;

            // Check if we need to trim the flags
            trimFlags(flags, mailboxSession);

        }
        if (isRecent) {
            flags.add(Flags.Flag.RECENT);
        }
        if (internalDate == null) {
            internalDate = new Date();
        }
        byte[] discard = new byte[4096];
        while (tmpMsgIn.read(discard) != -1) {
            // consume the rest of the stream so everything get copied to
            // the file now
            // via the TeeInputStream
        }
        int bodyStartOctet = (int) bIn.getBodyStartOffset();
        if (bodyStartOctet == -1) {
            bodyStartOctet = 0;
        }
        contentIn = new SharedFileInputStream(file);
        final int size = (int) file.length();

        final List<MessageAttachment> attachments = extractAttachments(contentIn);
        final MailboxMessage message = createMessage(internalDate, size, bodyStartOctet, contentIn, flags,
                propertyBuilder, attachments);

        new QuotaChecker(quotaManager, quotaRootResolver, mailbox).tryAddition(1, size);

        return locker.executeWithLock(mailboxSession, getMailboxPath(),
                new MailboxPathLocker.LockAwareExecution<Long>() {

                    @Override
                    public Long execute() throws MailboxException {
                        MessageMetaData data = appendMessageToStore(message, attachments, mailboxSession);

                        SortedMap<Long, MessageMetaData> uids = new TreeMap<Long, MessageMetaData>();
                        uids.put(data.getUid(), data);
                        dispatcher.added(mailboxSession, uids, getMailboxEntity());
                        return data.getUid();
                    }
                }, true);

    } catch (IOException e) {
        throw new MailboxException("Unable to parse message", e);
    } catch (MimeException e) {
        throw new MailboxException("Unable to parse message", e);
    } finally {
        IOUtils.closeQuietly(bIn);
        IOUtils.closeQuietly(tmpMsgIn);
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(contentIn);

        // delete the temporary file if one was specified
        if (file != null) {
            if (!file.delete()) {
                // Don't throw an IOException. The message could be appended
                // and the temporary file
                // will be deleted hopefully some day
            }
        }
    }

}

From source file:org.nuxeo.cm.event.MailInjectionListener.java

public void handleEvent(Event event) throws ClientException {
    MailService mailService = Framework.getService(MailService.class);
    MessageActionPipe pipe = mailService.getPipe(MAILBOX_PIPE);

    Visitor visitor = new Visitor(pipe);
    Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

    Folder rootFolder = null;//from ww w. j  a  v a  2 s  . c  o  m

    try (CoreSession session = CoreInstance.openCoreSessionSystem(null)) {
        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();
        initialExecutionContext.put(AbstractCaseManagementMailAction.CORE_SESSION_KEY, session);
        initialExecutionContext.put(AbstractCaseManagementMailAction.MIMETYPE_SERVICE_KEY,
                Framework.getService(MimetypeRegistry.class));
        initialExecutionContext.put(AbstractCaseManagementMailAction.CASEMANAGEMENT_SERVICE_KEY,
                Framework.getService(CaseDistributionService.class));

        // open store
        Store store = mailService.getConnectedStore(IMPORT_MAILBOX);
        rootFolder = store.getFolder(INBOX);
        rootFolder.open(Folder.READ_WRITE);
        Flags flags = new Flags();
        flags.add(Flag.SEEN);
        SearchTerm term = new FlagTerm(flags, false);
        Message[] unreadMessages = rootFolder.search(term);

        // perform import
        visitor.visit(unreadMessages, initialExecutionContext);

        // save session
        session.save();

        if (rootFolder.isOpen()) {
            try {
                rootFolder.close(true);
            } catch (MessagingException e) {
                log.error(e.getMessage(), e);
            }
        }
    } catch (MessagingException e) {
        log.error(e, e);
    }
}

From source file:org.nuxeo.ecm.platform.mail.utils.MailCoreHelper.java

protected static void doCheckMail(DocumentModel currentMailFolder, CoreSession coreSession)
        throws MessagingException {
    String email = (String) currentMailFolder.getPropertyValue(EMAIL_PROPERTY_NAME);
    String password = (String) currentMailFolder.getPropertyValue(PASSWORD_PROPERTY_NAME);
    if (!StringUtils.isEmpty(email) && !StringUtils.isEmpty(password)) {
        mailService = getMailService();/*  ww w  .  j  a v  a  2 s  . c  o m*/

        MessageActionPipe pipe = mailService.getPipe(PIPE_NAME);

        Visitor visitor = new Visitor(pipe);
        Thread.currentThread().setContextClassLoader(Framework.class.getClassLoader());

        // initialize context
        ExecutionContext initialExecutionContext = new ExecutionContext();

        initialExecutionContext.put(MIMETYPE_SERVICE_KEY, getMimeService());

        initialExecutionContext.put(PARENT_PATH_KEY, currentMailFolder.getPathAsString());

        initialExecutionContext.put(CORE_SESSION_KEY, coreSession);

        initialExecutionContext.put(LEAVE_ON_SERVER_KEY, Boolean.TRUE); // TODO should be an attribute in 'protocol'
                                                                        // schema

        Folder rootFolder = null;
        Store store = null;
        try {
            String protocolType = (String) currentMailFolder.getPropertyValue(PROTOCOL_TYPE_PROPERTY_NAME);
            initialExecutionContext.put(PROTOCOL_TYPE_KEY, protocolType);
            // log.debug(PROTOCOL_TYPE_KEY + ": " + (String) initialExecutionContext.get(PROTOCOL_TYPE_KEY));

            String host = (String) currentMailFolder.getPropertyValue(HOST_PROPERTY_NAME);
            String port = (String) currentMailFolder.getPropertyValue(PORT_PROPERTY_NAME);
            Boolean socketFactoryFallback = (Boolean) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_FALLBACK_PROPERTY_NAME);
            String socketFactoryPort = (String) currentMailFolder
                    .getPropertyValue(SOCKET_FACTORY_PORT_PROPERTY_NAME);
            Boolean starttlsEnable = (Boolean) currentMailFolder
                    .getPropertyValue(STARTTLS_ENABLE_PROPERTY_NAME);
            String sslProtocols = (String) currentMailFolder.getPropertyValue(SSL_PROTOCOLS_PROPERTY_NAME);
            Long emailsLimit = (Long) currentMailFolder.getPropertyValue(EMAILS_LIMIT_PROPERTY_NAME);
            long emailsLimitLongValue = emailsLimit == null ? EMAILS_LIMIT_DEFAULT : emailsLimit.longValue();

            String imapDebug = Framework.getProperty(IMAP_DEBUG, "false");

            Properties properties = new Properties();
            properties.put("mail.store.protocol", protocolType);
            // properties.put("mail.host", host);
            // Is IMAP connection
            if (IMAP.equals(protocolType)) {
                properties.put("mail.imap.host", host);
                properties.put("mail.imap.port", port);
                properties.put("mail.imap.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imap.debug", imapDebug);
                properties.put("mail.imap.partialfetch", "false");
            } else if (IMAPS.equals(protocolType)) {
                properties.put("mail.imaps.host", host);
                properties.put("mail.imaps.port", port);
                properties.put("mail.imaps.starttls.enable", starttlsEnable.toString());
                properties.put("mail.imaps.ssl.protocols", sslProtocols);
                properties.put("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.imaps.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.imaps.socketFactory.port", socketFactoryPort);
                properties.put("mail.imap.partialfetch", "false");
                properties.put("mail.imaps.partialfetch", "false");
            } else if (POP3S.equals(protocolType)) {
                properties.put("mail.pop3s.host", host);
                properties.put("mail.pop3s.port", port);
                properties.put("mail.pop3s.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
                properties.put("mail.pop3s.socketFactory.fallback", socketFactoryFallback.toString());
                properties.put("mail.pop3s.socketFactory.port", socketFactoryPort);
                properties.put("mail.pop3s.ssl.protocols", sslProtocols);
            } else {
                // Is POP3 connection
                properties.put("mail.pop3.host", host);
                properties.put("mail.pop3.port", port);
            }

            properties.put("user", email);
            properties.put("password", password);

            Session session = Session.getInstance(properties);

            store = session.getStore();
            store.connect(email, password);

            String folderName = INBOX; // TODO should be an attribute in 'protocol' schema
            rootFolder = store.getFolder(folderName);

            // need RW access to update message flags
            rootFolder.open(Folder.READ_WRITE);

            Message[] allMessages = rootFolder.getMessages();
            // VDU
            log.debug("nbr of messages in folder:" + allMessages.length);

            FetchProfile fetchProfile = new FetchProfile();
            fetchProfile.add(FetchProfile.Item.FLAGS);
            fetchProfile.add(FetchProfile.Item.ENVELOPE);
            fetchProfile.add(FetchProfile.Item.CONTENT_INFO);
            fetchProfile.add("Message-ID");
            fetchProfile.add("Content-Transfer-Encoding");

            rootFolder.fetch(allMessages, fetchProfile);

            if (rootFolder instanceof IMAPFolder) {
                // ((IMAPFolder)rootFolder).doCommand(FetchProfile)
            }

            List<Message> unreadMessagesList = new ArrayList<Message>();
            for (Message message : allMessages) {
                Flags flags = message.getFlags();
                int unreadMessagesListSize = unreadMessagesList.size();
                if (flags != null && !flags.contains(Flag.SEEN)
                        && unreadMessagesListSize < emailsLimitLongValue) {
                    unreadMessagesList.add(message);
                    if (unreadMessagesListSize == emailsLimitLongValue - 1) {
                        break;
                    }
                }
            }

            Message[] unreadMessagesArray = unreadMessagesList.toArray(new Message[unreadMessagesList.size()]);

            // perform email import
            visitor.visit(unreadMessagesArray, initialExecutionContext);

            // perform flag update globally
            Flags flags = new Flags();
            flags.add(Flag.SEEN);

            boolean leaveOnServer = (Boolean) initialExecutionContext.get(LEAVE_ON_SERVER_KEY);
            if ((IMAP.equals(protocolType) || IMAPS.equals(protocolType)) && leaveOnServer) {
                flags.add(Flag.SEEN);
            } else {
                flags.add(Flag.DELETED);
            }
            rootFolder.setFlags(unreadMessagesArray, flags, true);

        } finally {
            if (rootFolder != null && rootFolder.isOpen()) {
                rootFolder.close(true);
            }
            if (store != null) {
                store.close();
            }
        }
    }
}

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

private void setMessageFlags(Message[] filteredMessages) throws MessagingException {
    boolean recentFlagSupported = false;

    Flags flags = this.getFolder().getPermanentFlags();

    if (flags != null) {
        recentFlagSupported = flags.contains(Flags.Flag.RECENT);
    }/*from w w w. j av a 2  s  .  co m*/
    for (Message message : filteredMessages) {
        if (!recentFlagSupported) {
            if (flags != null && flags.contains(Flags.Flag.USER)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("USER flags are supported by this mail server. Flagging message with '"
                            + SI_USER_FLAG + "' user flag");
                }
                Flags siFlags = new Flags();
                siFlags.add(SI_USER_FLAG);
                message.setFlags(siFlags, true);
            } else {
                if (logger.isDebugEnabled()) {
                    logger.debug(
                            "USER flags are not supported by this mail server. Flagging message with system flag");
                }
                message.setFlag(Flags.Flag.FLAGGED, true);
            }
        }
        this.setAdditionalFlags(message);
    }
}