Example usage for javax.mail Folder HOLDS_FOLDERS

List of usage examples for javax.mail Folder HOLDS_FOLDERS

Introduction

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

Prototype

int HOLDS_FOLDERS

To view the source code for javax.mail Folder HOLDS_FOLDERS.

Click Source Link

Document

This folder can contain other folders

Usage

From source file:edu.stanford.muse.email.ImapPopEmailStore.java

/** recursively collect all folder names under f into list */
private void collect_folder_names(Store store, List<FolderInfo> list, Folder f) throws MessagingException {
    // ignore hidden files
    if (f.getFullName().startsWith("."))
        return;/* w w w .  jav  a  2  s .  c  o m*/
    if (f.getFullName().indexOf("/.") >= 0 || f.getFullName().indexOf("\\.") >= 0)
        return;

    // hack for csl-mail which takes too long to return all the folders
    if (connectOptions.server.startsWith("csl-mail") && f.getFullName().indexOf("/") >= 0)
        return;

    // TOFIX: apparently imap folders can have both messages and children
    Folder f_children[] = null;
    boolean hasMessages = true, hasChildren = false;
    boolean isPop = "pop3".equals(connectOptions.protocol) || "pop3s".equals(connectOptions.protocol);

    if (!isPop) {
        // if its imap, check for children
        hasChildren = (f.getType() & Folder.HOLDS_FOLDERS) != 0;
        hasMessages = (f.getType() & Folder.HOLDS_MESSAGES) != 0;
    }

    if (hasMessages) {
        folderBeingScanned = f.getFullName();
        Pair<Folder, Integer> pair = openFolder(store, f.getFullName());
        int count = pair.getSecond();
        if (count != -1)
            pair.getFirst().close(false);

        //         System.out.println ("full name = " + Util.blur(f.getFullName()) + " count = " + count);

        list.add(new FolderInfo(getAccountID(), f.getFullName(), f.getFullName(), count));
        folderBeingScanned = null;
    }

    if (hasChildren) {
        f_children = f.list();
        for (Folder child : f_children)
            collect_folder_names(store, list, child);
    }
}

From source file:org.zilverline.core.IMAPCollection.java

private final boolean indexFolder(IndexWriter writer, Folder thisFolder) throws MessagingException {
    if (stopRequested) {
        log.info("Indexing stops, due to request");
        return false;
    }/*  ww w  .j a va  2  s .  co  m*/
    if ((thisFolder.getType() & Folder.HOLDS_MESSAGES) != 0) {
        thisFolder.open(Folder.READ_ONLY);
        Message[] messages = thisFolder.getMessages(); // get refs to all msgs
        if (messages == null) {
            // dummy
            messages = new Message[0];
        }

        thisFolder.fetch(messages, PROFILE); // fetch headers

        log.debug("FOLDER: " + thisFolder.getFullName() + " messages=" + messages.length);

        for (int i = 0; i < messages.length; i++) {
            try {
                String msgID = null;
                if (messages[i] instanceof MimeMessage) {
                    MimeMessage mm = (MimeMessage) messages[i];
                    msgID = mm.getMessageID();
                }
                if (!md5DocumentCache.contains(msgID)) {
                    log.debug("new message added for message: " + msgID);
                    final Document doc = new Document();
                    doc.add(Field.Keyword(F_FOLDER, thisFolder.getFullName()));
                    doc.add(Field.Keyword("collection", name));
                    // index this message
                    indexMessage(doc, messages[i]);
                    // add it
                    writer.addDocument(doc);
                    md5DocumentCache.add(msgID);
                } else {
                    log.debug("existing message skipped for message: " + msgID);
                }
            } catch (Exception ioe) {
                // can be side effect of hosed up mail headers
                log.warn("Bad Message: " + messages[i], ioe);
                continue;
            }
        }

    }
    // recurse if possible
    if ((thisFolder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        Folder[] far = thisFolder.list();
        if (far != null) {
            for (int i = 0; i < far.length; i++) {
                indexFolder(writer, far[i]);
            }
        }
    }
    if (thisFolder.isOpen()) {
        log.debug("Closing folder: " + thisFolder.getFullName());
        thisFolder.close(false); // false => do not expunge
    }

    return true;
}

From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java

protected void recurseFolders(final Folder folder, final Pattern pattern)
        throws MessagingException, IOException {

    if (folder != null) {

        if (es == null || es.isShutdown() || es.isTerminated() || Thread.currentThread().isInterrupted()) {

            logger.warn("Stop processing of mails due to mail source is closed");
            return;

        }//  ww  w .  j  a v a 2 s .com

        if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {

            if (pattern != null && !pattern.matcher(folder.getFullName()).matches()) {
                logger.info("Pattern {} does not match {}", pattern.pattern(), folder.getFullName());
                return;
            }
            IMAPUtils.open(folder);

            try {
                fetch(folder);
            } finally {
                IMAPUtils.close(folder);
                logger.debug("fetch {} done", folder.getFullName());
            }
        }

        if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
            for (final Folder subfolder : folder.list()) {

                recurseFolders(subfolder, pattern);

            }
        }

    }

}

From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java

protected void recurseFolders(final Folder folder, final Pattern pattern)
        throws MessagingException, IOException {

    if (folder != null) {

        if (es == null || es.isShutdown() || es.isTerminated() || Thread.currentThread().isInterrupted()) {

            logger.warn("Stop processing of mails due to mail source is closed");
            return;

        }/*w  w  w .  j  ava 2  s .c om*/

        if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {

            if (pattern != null && !pattern.matcher(folder.getFullName()).matches()) {
                logger.debug("Pattern {} does not match {}", pattern.pattern(), folder.getFullName());
                return;
            }
            IMAPUtils.open(folder);

            try {
                fetch(folder);
            } finally {
                IMAPUtils.close(folder);
                logger.debug("fetch {} done", folder.getFullName());
            }
        }

        if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
            for (final Folder subfolder : folder.list()) {

                recurseFolders(subfolder, pattern);

            }
        }

    }

}

From source file:com.sonicle.webtop.mail.MailAccount.java

public Folder checkCreateFolder(String foldername) throws MessagingException {
    Folder folder = store.getFolder(foldername);
    if (!folder.exists()) {
        folder.create(Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS);
    }/*from  w  w w .  j av a  2  s . co  m*/
    return folder;
}

From source file:com.liferay.mail.imap.IMAPAccessor.java

protected void getFolders(List<Folder> allJxFolders, Folder[] jxFolders) {
    for (Folder jxFolder : jxFolders) {
        try {/*w w  w  . j av a  2  s.  c om*/
            int folderType = jxFolder.getType();

            if ((folderType & Folder.HOLDS_MESSAGES) != 0) {
                allJxFolders.add(jxFolder);
            }

            if ((folderType & Folder.HOLDS_FOLDERS) != 0) {
                getFolders(allJxFolders, jxFolder.list());
            }
        } catch (MessagingException me) {
            _log.error("Unable to get folder " + jxFolder.getFullName(), me);
        }
    }
}

From source file:org.pentaho.di.job.entries.getpop.MailConnection.java

private HashSet<String> returnSubfolders(Folder folder) throws KettleException {
    HashSet<String> list = new HashSet<String>();
    try {//from  w ww . j  a v  a2s .  c o m
        if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
            Folder[] f = folder.list();
            for (int i = 0; i < f.length; i++) {
                // Search for sub folders
                if ((f[i].getType() & Folder.HOLDS_FOLDERS) != 0) {
                    list.add(f[i].getFullName());
                    list.addAll(returnSubfolders(f[i]));
                }
            }
        }
    } catch (MessagingException m) {
        throw new KettleException(m);
    }
    return list;
}

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

/**
 * Construct the folder subtree for the given folder and append it to
 * xml_parent.// w w w.j a va2s. com
 *
 * N.b. this method does not necessarily create a new XML Folder Element.
 * If called with subscribed_only and the target Folder (and in some
 * cases its descendants) are not subscribed, no Element will be created
 * and 0 will be returned.
 * <P>
 * Pop servers don't support nesting at all, so you'll just get a single
 * level out of this method.
 * <P>
 * There is a critical subscribed_only difference in behavior between
 * Maildir and mbox type mail servers.
 * Maildir folders are all HOLDS_MESSAGES, whether empty or not, and
 * these folders have a subscribed attribute which the user can set,
 * and which we honor.
 * mbox folders, on the other hand, have no subscribed attribute for
 * their !HOLDS_MESSAGE folders, so we must recurse to all of the
 * descendant HOLDS_MESSAGE folders to see if we should show.
 *
 * @param folder the folder where we begin
 * @param xml_parent XML Element where the gathered information will be
 *                   appended
 * @param subscribed_only Only add 'subscribed' folders
 * @param doCount Whether to generate message counts for Elements
 *                corresponding to HOLDS_MESSAGE folders.
 * @returns maximum depth of the folder tree (needed to calculate the
 *     necessary columns in a table).  Returns 0 if no XML elements added.
 */
protected int getFolderTree(Folder folder, Element xml_parent, boolean subscribed_only, boolean doCount) {
    int generatedDepth = 0;
    int folderType;
    Element xml_folder;

    try {
        folderType = folder.getType();
    } catch (MessagingException ex) {
        log.error("Can't get enough info from server to even make Gui node", ex);
        xml_parent.setAttribute("error", "For child '" + folder.getName() + ":  " + ex.getMessage());
        return 0;
    }
    boolean holds_folders = (folderType & Folder.HOLDS_FOLDERS) != 0;
    boolean holds_messages = (folderType & Folder.HOLDS_MESSAGES) != 0;
    // Sanity check:
    if ((!holds_folders) && !holds_messages) {
        log.fatal("Folder can hold neither folders nor messages: " + folder.getFullName());
        throw new RuntimeException("Folder can hold neither folders nor messages: " + folder.getFullName());
    }
    if (subscribed_only && holds_messages && !folder.isSubscribed())
        return generatedDepth; // Return right away and save a LOT OF WORK
    // N.b. we honor folder.isSubscribed() only for holds_message
    // folders.  That means all Maildir server folders, and all
    // mbox server folders except for mbox directories.  In this
    // last case, we must recurse to determine whether to show folder.
    String id = generateFolderHash(folder);
    xml_folder = model.createFolder(id, folder.getName(), holds_folders, holds_messages);
    // XMLUserModel.createFolder() declares no throws.  If any Exceptions
    // are expected from it, move the statement above into the try block.
    // The xml_folder Element here will be orphaned and GC'd if we don't
    // appendChild (in which case we return 0).

    if (doCount && holds_messages)
        try {
            // this folder will definitely be added!
            /* This folder can contain messages */
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if (total_messages == -1 || new_messages == -1 || !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

            messagelist.setAttribute("total", total_messages + "");
            messagelist.setAttribute("new", new_messages + "");
            log.debug("Counted " + new_messages + '/' + total_messages + " for folder " + folder.getFullName());
            xml_folder.appendChild(messagelist);
        } catch (MessagingException ex) {
            log.warn("Failed to count messages in folder '" + folder.getFullName() + "'", ex);
            xml_folder.setAttribute("error", ex.getMessage());
        }

    int descendantDepth = 0;
    if (holds_folders)
        try {
            Set<String> fullNameSet = new HashSet<String>();

            /* Recursively add subfolders to the XML model */
            // DO NOT USE listSubscribed(), because with !HOLDS_MESSAGE
            // folders, that skips non-Message Folders which may contain
            // subscribed descendants!
            for (Folder f : folder.list()) {
                if (!fullNameSet.add(f.getFullName())) {
                    log.warn("Skipping duplicate subfolder returned by mail" + " server:  " + f.getFullName());
                    continue;
                }
                if (subscribed_only && (f.getType() & Folder.HOLDS_MESSAGES) != 0 && !f.isSubscribed())
                    continue;
                /* If we recursed here, the getFolderTree() would
                 * just return 0 and no harm done.
                 * Just helping performance by preventing a recursion
                 * here.
                 * For comment on the logic here, see the same test
                 * towards the top of this method (before recursion).
                 */
                int depth = getFolderTree(f, xml_folder, subscribed_only, doCount);
                if (depth > descendantDepth)
                    descendantDepth = depth;
            }
            generatedDepth += descendantDepth;
        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }

    // We've already validated that if subscribed_only and holds_message
    //  then folder is subcribed.  Also verified either holds_m or holds_f.
    //  Only have to check the !holds_message case.
    if (subscribed_only && (!holds_messages) && descendantDepth < 1) {
        xml_folder = null;
        // Unnecessary, but may encourage GC
        return generatedDepth;
    }

    /* We ALWAYS return only subscribed folders except for these two
     * distinct cases: */
    xml_folder.setAttribute("subscribed",
            ((holds_messages && !folder.isSubscribed()) || ((!holds_messages) && descendantDepth < 1)) ? "false"
                    : "true");
    // N.b. our Element's "subscribed" element does not correspond 1:1
    // to Folder.isSubscribed(), since non-message-holding Folders have
    // no "subscribed" attribute.
    folders.put(id, folder);

    xml_parent.appendChild(xml_folder);
    generatedDepth++; // Add the count for xml_folder
    return generatedDepth;
}

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

public void addFolder(String toid, String name, boolean holds_messages, boolean holds_folders)
        throws MessagingException {
    Folder parent = getFolder(toid);/*from   w  ww  . jav a 2 s.  c  om*/
    Folder folder = parent.getFolder(name);
    if (!folder.exists()) {
        int type = 0;
        if (holds_messages) {
            type += Folder.HOLDS_MESSAGES;
        }
        if (holds_folders) {
            type += Folder.HOLDS_FOLDERS;
        }
        folder.create(type);
    }
    // Should be called from FolderSetup Plugin
    //refreshFolderInformation();
}

From source file:com.sonicle.webtop.core.app.WebTopManager.java

private void createCyrusMailbox(String login, Store store) throws WTCyrusException {
    try {/*from  w  w w.j  a  v a2  s.  c om*/
        char sep = store.getDefaultFolder().getSeparator();
        Folder c = store.getFolder("user" + sep + login);
        if (!c.exists())
            c.create(Folder.HOLDS_FOLDERS);
    } catch (Exception exc) {
        throw new WTCyrusException(exc);
    }
}