Example usage for javax.mail Folder list

List of usage examples for javax.mail Folder list

Introduction

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

Prototype


public Folder[] list() throws MessagingException 

Source Link

Document

Convenience method that returns the list of folders under this Folder.

Usage

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

private void _loadFoldersCache(FolderCache fc) throws MessagingException {
    Folder f = fc.getFolder();
    Folder children[] = f.list();
    for (Folder child : children) {
        String cname = child.getFullName();
        if (ms.isFolderHidden(this, cname))
            continue;
        if (hasDifferentDefaultFolder && cname.equals(fcRoot.getFolderName()))
            continue;
        FolderCache fcc = addFoldersCache(fc, child);
    }//from ww  w. j  a v  a 2s .co  m
    //If shared folders, check for same descriptions and in case add login
    if (isSharedFolder(f.getFullName()) && fc.hasChildren()) {
        HashMap<String, ArrayList<FolderCache>> hm = new HashMap<String, ArrayList<FolderCache>>();
        //map descriptions to list of folders
        for (FolderCache child : fc.getChildren()) {
            String desc = child.getDescription();
            ArrayList<FolderCache> al = hm.get(desc);
            if (al == null) {
                al = new ArrayList<FolderCache>();
                al.add(child);
                hm.put(desc, al);
            } else {
                al.add(child);
            }
        }
        //for folders with list>1 change description to all elements
        for (ArrayList<FolderCache> al : hm.values()) {
            if (al.size() > 1) {
                for (FolderCache fcc : al) {
                    SharedPrincipal sip = fcc.getSharedInboxPrincipal();
                    String user = sip.getUserId();
                    fcc.setWebTopUser(user);
                    fcc.setDescription(fcc.getDescription() + " [" + user + "]");
                }
            }
        }
    }
}

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

protected void getFolders(List<Folder> allJxFolders, Folder[] jxFolders) {
    for (Folder jxFolder : jxFolders) {
        try {//  ww  w . ja  v  a  2  s.c o  m
            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: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;

        }//from  w w  w  . j  av a 2s  . co m

        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;

        }// ww w  .ja  v a2 s . c  o  m

        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: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;/*ww  w  . j a v  a2 s. c om*/
    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;
    }/*from  w  w  w.  j  a  v a  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:com.sonicle.webtop.mail.Service.java

private void cycleMailFolder(MailAccount account, Folder folder, int cut, JarOutputStream jos)
        throws Exception {
    for (Folder child : folder.list()) {
        String fullname = child.getFullName();
        String relname = fullname.substring(cut).replace(folder.getSeparator(), '/');

        jos.putNextEntry(new JarEntry(relname + "/"));
        jos.closeEntry();//  w  w  w. java  2s  .  c o  m

        cycleMailFolder(account, child, cut, jos);

        FolderCache mcache = account.getFolderCache(fullname);
        Message msgs[] = mcache.getAllMessages();
        if (msgs.length > 0)
            outputJarMailFolder(relname, msgs, jos);
    }
}

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

public void processGetImapTree(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {

    String pfoldername = request.getParameter("node");
    MailAccount account = getAccount(request);
    Folder folder = null;
    try {/*from w w  w .java2  s  .  co  m*/
        boolean connected = account.checkStoreConnected();
        if (!connected)
            throw new Exception("Mail account authentication error");

        boolean isroot = pfoldername.equals("/");
        if (isroot)
            folder = account.getDefaultFolder();
        else
            folder = account.getFolder(pfoldername);

        Folder folders[] = folder.list();
        String fprefix = account.getFolderPrefix();
        boolean level1 = (fprefix != null /*&& fprefix.equals("INBOX.")*/ && fprefix.trim().length() > 0);
        ArrayList<JsFolder> jsFolders = new ArrayList<>();
        //out.print("{ data:[");
        if (isroot && account.hasDifferentDefaultFolder()) {
            Folder fcs[] = new Folder[0];
            //check for other shared folders to be added
            Folder rfolders[] = account.getRealDefaultFolder().list();
            ArrayList<Folder> afcs = new ArrayList<Folder>();
            for (String sharedPrefix : account.getSharedPrefixes()) {
                for (Folder rfolder : rfolders) {
                    if (rfolder.getFullName().equals(sharedPrefix))
                        afcs.add(rfolder);
                }
            }
            //don't mind about just the Shared folder with no child (size=1)
            if (afcs.size() > 0)
                fcs = afcs.toArray(fcs);

            Folder xfolders[] = new Folder[1 + folders.length + fcs.length];
            xfolders[0] = folder;
            System.arraycopy(folders, 0, xfolders, 1, folders.length);
            if (fcs.length > 0)
                System.arraycopy(fcs, 0, xfolders, 1 + folders.length, fcs.length);
            folders = xfolders;
        }
        outputFolders(account, folder, folders, level1, false, jsFolders);
        new JsonResult("data", jsFolders).printTo(out, false);
        //out.println("], message: '' }");

    } catch (Exception exc) {
        new JsonResult(exc).printTo(out);
        Service.logger.error("Exception", exc);
    }
}

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

public void processGetArchiveTree(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    String pfoldername = request.getParameter("node");
    MailAccount account = archiveAccount; //getAccount(request);
    Folder folder = null;
    try {/*from   w w  w.  j  ava 2s  .c  o  m*/
        boolean connected = account.checkStoreConnected();
        if (!connected)
            throw new Exception("Mail account authentication error");
        if (!account.hasFolderCache())
            account.loadFoldersCache(account, true);

        boolean isroot = pfoldername.equals("/");
        if (isroot)
            folder = account.getDefaultFolder();
        else
            folder = account.getFolder(pfoldername);

        Folder folders[] = folder.list();
        String fprefix = account.getFolderPrefix();
        boolean level1 = (fprefix != null && fprefix.equals("INBOX."));
        ArrayList<JsFolder> jsFolders = new ArrayList<>();
        //out.print("{ data:[");
        if (isroot && account.hasDifferentDefaultFolder()) {
            Folder fcs[] = new Folder[0];
            //check for other shared folders to be added
            Folder rfolders[] = account.getRealDefaultFolder().list();
            ArrayList<Folder> afcs = new ArrayList<Folder>();
            for (String sharedPrefix : account.getSharedPrefixes()) {
                for (Folder rfolder : rfolders) {
                    if (rfolder.getFullName().equals(sharedPrefix))
                        afcs.add(rfolder);
                }
            }
            if (afcs.size() > 0)
                fcs = afcs.toArray(fcs);

            Folder xfolders[] = new Folder[1 + folders.length + fcs.length];
            xfolders[0] = folder;
            System.arraycopy(folders, 0, xfolders, 1, folders.length);
            if (fcs.length > 0)
                System.arraycopy(fcs, 0, xfolders, 1 + folders.length, fcs.length);
            folders = xfolders;
        }
        outputFolders(account, folder, folders, level1, false, jsFolders);
        new JsonResult("data", jsFolders).printTo(out, false);
        //out.println("], message: '' }");

    } catch (Exception exc) {
        new JsonResult(exc).printTo(out);
        Service.logger.error("Exception", exc);
    }
}

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

private void outputFolders(MailAccount account, Folder parent, Folder folders[], boolean level1,
        boolean favorites, ArrayList<JsFolder> jsFolders) throws Exception {
    boolean hasPrefix = !StringUtils.isBlank(account.getFolderPrefix());
    String prefixMatch = StringUtils.stripEnd(account.getFolderPrefix(), account.getFolderSeparator() + "");
    ArrayList<Folder> postPrefixList = new ArrayList<Folder>();
    ArrayList<Folder> afolders;
    if (!favorites)
        afolders = sortFolders(account, folders);
    else {//from  w w  w.j  a va  2s  . c o m
        afolders = new ArrayList<Folder>();
        for (Folder f : folders) {
            if (f != null) {
                afolders.add(f);
            }
        }
    }
    //If Shared Folders, sort on description
    if (parent != null && account.isSharedFolder(parent.getFullName())) {
        if (!account.hasDifferentDefaultFolder() || !account.isDefaultFolder(parent.getFullName())) {
            String ss = mprofile.getSharedSort();
            if (ss.equals("D")) {
                Collections.sort(afolders, account.getDescriptionFolderComparator());
            } else if (ss.equals("U")) {
                Collections.sort(afolders, account.getWebTopUserFolderComparator());
            }
        }
    }

    //If at level 1, look for the prefix folder in the list
    Folder prefixFolder = null;
    if (level1) {
        for (Folder f : afolders) {
            if (f.getFullName().equals(prefixMatch)) {
                prefixFolder = f;
                break;
            }
        }
        //remove it and use it later
        if (prefixFolder != null)
            afolders.remove(prefixFolder);
    }

    //now scan and output folders
    for (Folder f : afolders) {
        String foldername = f.getFullName();
        //in case of moved root, check not to duplicate root elsewhere
        if (account.hasDifferentDefaultFolder()) {
            if (account.isDovecot()) {
                if (account.isDefaultFolder(foldername))
                    continue;
            } else {
                //skip default folder under shared
                if (account.isDefaultFolder(foldername) && parent != null
                        && !parent.getFullName().equals(foldername))
                    continue;
            }
        }

        //skip hidden
        if (us.isFolderHidden(foldername))
            continue;

        FolderCache mc = account.getFolderCache(foldername);
        if (mc == null && parent != null) {
            //continue;
            //System.out.println("foldername="+foldername+" parentname="+parent.getFullName());
            FolderCache fcparent = account.getFolderCache(parent.getFullName());
            mc = account.addSingleFoldersCache(fcparent, f);
        }
        //String shortfoldername=getShortFolderName(foldername);
        IMAPFolder imapf = (IMAPFolder) f;
        String atts[] = imapf.getAttributes();
        boolean leaf = true;
        boolean noinferiors = false;
        if (account.hasDifferentDefaultFolder() && account.isDefaultFolder(foldername)) {

        } else if (!favorites) {
            for (String att : atts) {
                if (att.equals("\\HasChildren")) {
                    if (!level1 || !foldername.equals(account.getInboxFolderFullName()))
                        leaf = false;
                } else if (att.equals("\\Noinferiors"))
                    noinferiors = true;
            }
            if (noinferiors)
                leaf = true;
        }
        //boolean leaf=isLeaf((IMAPFolder)f);
        //logger.debug("folder {} isleaf={}, level1={}",f.getFullName(),leaf,level1);
        //if (leaf) {
        //   if (!level1 || !foldername.equals("INBOX")) leaf=false;
        //}

        if (!favorites && prefixFolder != null && !foldername.equals("INBOX")
                && !foldername.startsWith(account.getFolderPrefix())) {
            postPrefixList.add(f);
        } else {
            /*            
                        String iconCls = "wtmail-icon-imap-folder-xs";
                        int unread = 0;
                        boolean hasUnread = false;
                        boolean nounread = false;
                        if (mc.isSharedFolder()) {
                           iconCls = "wtmail-icon-shared-folder-xs";
                           nounread = true;
                        } else if (mc.isInbox()) {
                           iconCls = "wtmail-icon-inbox-folder-xs";
                        } else if (mc.isSent()) {
                           iconCls = "wtmail-icon-sent-folder-xs";
                           nounread = true;
                        } else if (mc.isDrafts()) {
                           iconCls = "wtmail-icon-drafts-folder-xs";
                           nounread = true;
                        } else if (mc.isTrash()) {
                           iconCls = "wtmail-icon-trash-folder-xs";
                           nounread = true;
                        } else if (mc.isArchive()) {
                           iconCls = "wtmail-icon-archive-folder-xs";
                           nounread = true;
                        } else if (mc.isSpam()) {
                           iconCls = "wtmail-icon-spam-folder-xs";
                           nounread = true;
                        } else if (mc.isDms()) {
                           iconCls = "wtmail-icon-dms-folder-xs";
                        } else if (mc.isSharedInbox()) {
                           iconCls = "wtmail-icon-inbox-folder-xs";
                        }
                        if (!nounread) {
                           unread = mc.getUnreadMessagesCount();
                           hasUnread = mc.hasUnreadChildren();
                        }
                        String text = mc.getDescription();
                        String group = us.getMessageListGroup(foldername);
                        if (group == null) {
                           group = "";
                        }
                    
                        String ss = "{id:'" + StringEscapeUtils.escapeEcmaScript(foldername)
                              + "',text:'" + StringEscapeUtils.escapeEcmaScript(description)
                              + "',folder:'" + StringEscapeUtils.escapeEcmaScript(text)
                              + "',leaf:" + leaf
                              + ",iconCls: '" + iconCls
                              + "',unread:" + unread
                              + ",hasUnread:" + hasUnread
                              + ",group: '"+group+"'";
                    
                        boolean isSharedToSomeone=false;
                        try {
                           isSharedToSomeone=mc.isSharedToSomeone();
                        } catch(Exception exc) {
                    
                        }
                        if (isSharedToSomeone) ss+=",isSharedToSomeone: true";
                        if (mc.isSharedFolder()) ss+=",isSharedRoot: true";
                        if (account.isUnderSharedFolder(foldername)) ss+=",isUnderShared: true";
                        if (mc.isInbox()) {
                           ss += ",isInbox: true";
                        }
                        if (mc.isSent()) {
                           ss += ",isSent: true";
                        }
                        if (account.isUnderSentFolder(mc.getFolderName())) {
                           ss += ",isUnderSent: true";
                        }
                        if (mc.isDrafts()) {
                           ss += ",isDrafts: true";
                        }
                        if (mc.isTrash()) {
                           ss += ",isTrash: true";
                        }
                        if (mc.isArchive()) {
                           ss += ",isArchive: true";
                        }
                        if (mc.isSpam()) {
                           ss += ",isSpam: true";
                        }
                        if (mc.isScanForcedOff()) {
                           ss += ", scanOff: true";
                        } else if (mc.isScanForcedOn()) {
                           ss += ", scanOn: true";
                        } else if (mc.isScanEnabled()) {
                           ss += ", scanEnabled: true";
                        }
                    
                        boolean canRename=true;
                        if (mc.isInbox() || mc.isSpecial() || mc.isSharedFolder() || (mc.getParent()!=null && mc.getParent().isSharedFolder())) canRename=false;
                        ss += ", canRename: "+canRename;
                    
                        ss += ", account: '"+account.getId()+"'";
                        ss += "},";
                    
                        out.print(ss);
            */
            jsFolders.add(createJsFolder(mc, leaf));
        }
    }

    //if we have a prefix folder output remaining folders
    if (!favorites && prefixFolder != null) {
        for (Folder ff : prefixFolder.list())
            postPrefixList.add(ff);
        ArrayList<Folder> sortedFolders = sortFolders(account,
                postPrefixList.toArray(new Folder[postPrefixList.size()]));
        outputFolders(account, prefixFolder, sortedFolders.toArray(new Folder[sortedFolders.size()]), false,
                false, jsFolders);
    }
}