Example usage for javax.mail Folder getFullName

List of usage examples for javax.mail Folder getFullName

Introduction

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

Prototype

public abstract String getFullName();

Source Link

Document

Returns the full name of this Folder.

Usage

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

public void processMoveFolder(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String folder = request.getParameter("folder");
    String to = request.getParameter("to");
    String sout = null;/*from w w w  . ja  v a2s  .com*/
    FolderCache mcache = null;
    try {
        account.checkStoreConnected();
        boolean result = true;
        sout = "{\n";
        mcache = account.getFolderCache(folder);
        if (account.isSpecialFolder(folder)) {
            result = false;
        } else {
            FolderCache newfc = account.moveFolder(folder, to);
            Folder newf = newfc.getFolder();
            sout += "oldid: '" + StringEscapeUtils.escapeEcmaScript(folder) + "',\n";
            sout += "newid: '" + StringEscapeUtils.escapeEcmaScript(newf.getFullName()) + "',\n";
            sout += "newname: '" + StringEscapeUtils.escapeEcmaScript(newf.getName()) + "',\n";
            if (to != null) {
                sout += "parent: '" + StringEscapeUtils.escapeEcmaScript(newf.getParent().getFullName())
                        + "',\n";
            }
            result = true;
        }
        sout += "result: " + result + "\n}";
    } catch (MessagingException exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, oldid: '" + StringEscapeUtils.escapeEcmaScript(folder) + "', oldname: '"
                + StringEscapeUtils.escapeEcmaScript(mcache != null ? mcache.getFolder().getName() : "unknown")
                + "', text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
    out.println(sout);
}

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

public void processGetMessagePage(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    String puid = request.getParameter("uid");
    String prowsperpage = request.getParameter("rowsperpage");
    //String psearchfield = request.getParameter("searchfield");
    //String ppattern = request.getParameter("pattern");
    //String pquickfilter=request.getParameter("quickfilter");
    //String prefresh = request.getParameter("refresh");
    //String ptimestamp = request.getParameter("timestamp");
    //if (psearchfield != null && psearchfield.trim().length() == 0) {
    //   psearchfield = null;
    //}//  w ww  . j a  va 2 s.  c  o m
    //if (ppattern != null && ppattern.trim().length() == 0) {
    //   ppattern = null;
    //}
    //if (pquickfilter!=null && pquickfilter.trim().length()==0) pquickfilter=null;
    //boolean refresh = (prefresh != null && prefresh.equals("true"));
    //long timestamp=Long.parseLong(ptimestamp);
    boolean refresh = true;
    long uid = Long.parseLong(puid);
    long rowsperpage = Long.parseLong(prowsperpage);

    String group = us.getMessageListGroup(pfoldername);
    if (group == null) {
        group = "";
    }

    String psortfield = "date";
    String psortdir = "DESC";
    try {
        boolean nogroup = group.equals("");
        if (nogroup) {
            String s = us.getMessageListSort(pfoldername);
            int ix = s.indexOf("|");
            psortfield = s.substring(0, ix);
            psortdir = s.substring(ix + 1);
        } else {
            psortfield = "date";
            psortdir = "DESC";
        }
    } catch (Exception exc) {
        logger.error("Exception", exc);
    }

    SortGroupInfo sgi = getSortGroupInfo(psortfield, psortdir, group);

    Folder folder = null;
    boolean connected = false;
    try {
        connected = account.checkStoreConnected();
        if (!connected)
            throw new Exception("Mail account authentication error");

        if (pfoldername == null) {
            folder = account.getDefaultFolder();
        } else {
            folder = account.getFolder(pfoldername);
        }

        String key = folder.getFullName();
        FolderCache mcache = account.getFolderCache(key);
        if (mcache.toBeRefreshed())
            refresh = true;
        //         if (ppattern != null && psearchfield != null) {
        //            key += "|" + ppattern + "|" + psearchfield;
        //         }
        if (psortfield != null && psortdir != null) {
            key += "|" + psortdir + "|" + psortfield;
        }
        //         if (pquickfilter !=null) {
        //            key +="|" + pquickfilter;
        //         }

        MessagesInfo messagesInfo = listMessages(mcache, key, refresh, sgi, 0, null, false);
        Message xmsgs[] = messagesInfo.messages;
        if (xmsgs != null) {
            boolean found = false;
            int start = 0;
            int startx = 0;
            long tId = 0;
            for (int i = 0, ni = 0; i < xmsgs.length; ++ni, ++i) {
                int ix = start + i;
                int nx = start + ni;
                if (nx >= xmsgs.length)
                    break;

                SonicleIMAPMessage xm = (SonicleIMAPMessage) xmsgs[nx];
                if (xm.isExpunged()) {
                    --i;
                    continue;
                }

                long nuid = mcache.getUID(xm);
                int tIndent = xm.getThreadIndent();

                if (nuid == uid) {
                    found = true;
                    if (tIndent == 0)
                        tId = 0;
                    //else tId contains the last thread root id
                    break;
                }

                if (tIndent == 0)
                    tId = nuid;
                else if (sgi.threaded) {
                    if (!mcache.isThreadOpen(tId)) {
                        --i;
                        continue;
                    }
                }

                ++startx;
            }
            if (found) {
                JsonResult jsr = new JsonResult();
                jsr.set("page", ((int) (startx / rowsperpage) + 1));
                jsr.set("row", startx);
                if (tId > 0)
                    jsr.set("threadid", tId);
                jsr.printTo(out);
            } else
                new JsonResult(false, "Message not found");
        } else
            new JsonResult(false, "No messages");
    } catch (Exception exc) {
        new JsonResult(exc).printTo(out);
    }
}

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

public void processNewFolder(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    MailAccount account = getAccount(request);
    String folder = request.getParameter("folder");
    String name = request.getParameter("name");
    String sout = null;//ww  w  .j  a  v  a  2  s  .c o  m
    FolderCache mcache = null;
    try {
        account.checkStoreConnected();
        Folder newfolder = null;
        boolean result = true;
        sout = "{\n";
        name = account.normalizeName(name);
        if (folder == null || (account.hasDifferentDefaultFolder() && folder.trim().length() == 0))
            mcache = account.getRootFolderCache();
        else
            mcache = account.getFolderCache(folder);

        newfolder = mcache.createFolder(name);
        if (newfolder == null) {
            result = false;
        } else {
            if (!account.isRoot(mcache)) {
                sout += "parent: '" + StringEscapeUtils.escapeEcmaScript(mcache.getFolderName()) + "',\n";
            } else {
                sout += "parent: null,\n";
            }
            sout += "name: '" + StringEscapeUtils.escapeEcmaScript(newfolder.getName()) + "',\n";
            sout += "fullname: '" + StringEscapeUtils.escapeEcmaScript(newfolder.getFullName()) + "',\n";
        }
        sout += "result: " + result + "\n}";
    } catch (MessagingException exc) {
        Service.logger.error("Exception", exc);
        sout = "{\nresult: false, oldid: '" + StringEscapeUtils.escapeEcmaScript(folder) + "', oldname: '"
                + StringEscapeUtils.escapeEcmaScript(mcache != null ? mcache.getFolder().getName() : "unknown")
                + "', text:'" + StringEscapeUtils.escapeEcmaScript(exc.getMessage()) + "'\n}";
    }
    out.println(sout);
}

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 {/* w w w . j av  a2 s.c om*/
        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);
    }
}

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

public void processListMessages(HttpServletRequest request, HttpServletResponse response, PrintWriter out) {
    CoreManager core = WT.getCoreManager();
    UserProfile profile = environment.getProfile();
    Locale locale = profile.getLocale();
    java.util.Calendar cal = java.util.Calendar.getInstance(locale);
    MailAccount account = getAccount(request);
    String pfoldername = request.getParameter("folder");
    //String psortfield = request.getParameter("sort");
    //String psortdir = request.getParameter("dir");
    String pstart = request.getParameter("start");
    String plimit = request.getParameter("limit");
    String ppage = request.getParameter("page");
    String prefresh = request.getParameter("refresh");
    String ptimestamp = request.getParameter("timestamp");
    String pthreaded = request.getParameter("threaded");
    String pthreadaction = request.getParameter("threadaction");
    String pthreadactionuid = request.getParameter("threadactionuid");

    QueryObj queryObj = null;//from   w  w  w.j  a  v  a  2 s . c  o  m
    SearchTerm searchTerm = null;
    try {
        queryObj = ServletUtils.getObjectParameter(request, "query", new QueryObj(), QueryObj.class);
    }

    catch (ParameterException parameterException) {
        logger.error("Exception getting query obejct parameter", parameterException);
    }

    boolean refresh = (prefresh != null && prefresh.equals("true"));
    //boolean threaded=(pthreaded!=null && pthreaded.equals("1"));

    //String threadedSetting="list-threaded-"+pfoldername;
    //if (pthreaded==null || pthreaded.equals("2")) {
    //   threaded=us.isMessageListThreaded(pfoldername);
    //} else {
    //   us.setMessageListThreaded(pfoldername, threaded);
    //}
    //System.out.println("timestamp="+ptimestamp);
    long timestamp = Long.parseLong(ptimestamp);

    if (account.isSpecialFolder(pfoldername) || account.isSharedFolder(pfoldername)) {
        logger.debug("folder is special or shared, refresh forced");
        refresh = true;
    }

    String group = us.getMessageListGroup(pfoldername);
    if (group == null) {
        group = "";
    }

    String psortfield = "date";
    String psortdir = "DESC";
    try {
        boolean nogroup = group.equals("");
        JsSort.List sortList = ServletUtils.getObjectParameter(request, "sort", null, JsSort.List.class);
        if (sortList == null) {
            if (nogroup) {
                String s = us.getMessageListSort(pfoldername);
                int ix = s.indexOf("|");
                psortfield = s.substring(0, ix);
                psortdir = s.substring(ix + 1);
            } else {
                psortfield = "date";
                psortdir = "DESC";
            }
        } else {
            JsSort jsSort = sortList.get(0);
            psortfield = jsSort.property;
            psortdir = jsSort.direction;
            if (!nogroup && !psortfield.equals("date")) {
                group = "";
            }
            us.setMessageListGroup(pfoldername, group);
            us.setMessageListSort(pfoldername, psortfield, psortdir);
        }
    } catch (Exception exc) {
        logger.error("Exception", exc);
    }

    SortGroupInfo sgi = getSortGroupInfo(psortfield, psortdir, group);

    //Save search requests

    int start = Integer.parseInt(pstart);
    int limit = Integer.parseInt(plimit);
    int page = 0;
    if (ppage != null) {
        page = Integer.parseInt(ppage);
        start = (page - 1) * limit;
    }
    /*int start = 0;
    int limit = mprofile.getNumMsgList();
    if (ppage==null) {
       if (pstart != null) {
    start = Integer.parseInt(pstart);
       }   
       if (plimit != null) {
    limit = Integer.parseInt(plimit);
       }
    } else {
       int page=Integer.parseInt(ppage);
       int nxpage=mprofile.getNumMsgList();
       start=(page-1)*nxpage;
       limit=nxpage;
    }*/

    String sout = "{\n";
    Folder folder = null;
    boolean connected = false;
    try {
        connected = account.checkStoreConnected();
        if (!connected)
            throw new Exception("Mail account authentication error");

        int funread = 0;
        if (pfoldername == null) {
            folder = account.getDefaultFolder();
        } else {
            folder = account.getFolder(pfoldername);
        }
        boolean issent = account.isSentFolder(folder.getFullName());
        boolean isundersent = account.isUnderSentFolder(folder.getFullName());
        boolean isdrafts = account.isDraftsFolder(folder.getFullName());
        boolean isundershared = account.isUnderSharedFolder(pfoldername);
        if (!issent) {
            String names[] = folder.getFullName().split("\\" + account.getFolderSeparator());
            for (String pname : names) {
                if (account.isSentFolder(pname)) {
                    issent = true;
                    break;
                }
            }
        }

        String ctn = Thread.currentThread().getName();
        String key = folder.getFullName();

        if (!pfoldername.equals("/")) {

            FolderCache mcache = account.getFolderCache(key);
            if (mcache.toBeRefreshed())
                refresh = true;
            //Message msgs[]=mcache.getMessages(ppattern,psearchfield,sortby,ascending,refresh);
            if (psortfield != null && psortdir != null) {
                key += "|" + psortdir + "|" + psortfield;
            }

            searchTerm = ImapQuery.toSearchTerm(this.allFlagStrings, this.atags, queryObj,
                    profile.getTimeZone());

            boolean hasAttachment = queryObj.conditions.stream()
                    .anyMatch(condition -> condition.value.equals("attachment"));
            if (queryObj != null)
                refresh = true;
            MessagesInfo messagesInfo = listMessages(mcache, key, refresh, sgi, timestamp, searchTerm,
                    hasAttachment);
            Message xmsgs[] = messagesInfo.messages;

            if (pthreadaction != null && pthreadaction.trim().length() > 0) {
                long actuid = Long.parseLong(pthreadactionuid);
                mcache.setThreadOpen(actuid, pthreadaction.equals("open"));
            }

            //if threaded, look for the start considering roots and opened children
            if (xmsgs != null && sgi.threaded && page > 1) {
                int i = 0, ni = 0, np = 1;
                long tId = 0;
                while (np < page && ni < xmsgs.length) {
                    SonicleIMAPMessage xm = (SonicleIMAPMessage) xmsgs[ni];
                    ++ni;
                    if (xm.isExpunged())
                        continue;

                    long nuid = mcache.getUID(xm);

                    int tIndent = xm.getThreadIndent();
                    if (tIndent == 0)
                        tId = nuid;
                    else {
                        if (!mcache.isThreadOpen(tId))
                            continue;
                    }

                    ++i;
                    if ((i % limit) == 0)
                        ++np;
                }
                if (np == page) {
                    start = ni;
                    //System.out.println("page "+np+" start is "+start);
                }
            }

            int max = start + limit;
            if (xmsgs != null && max > xmsgs.length)
                max = xmsgs.length;
            ArrayList<Long> autoeditList = new ArrayList<Long>();
            if (xmsgs != null) {
                int total = 0;
                int expunged = 0;

                //calculate expunged
                //for(Message xmsg: xmsgs) {
                //   if (xmsg.isExpunged()) ++expunged;
                //}

                sout += "messages: [\n";

                /*               if (ppattern==null && !isSpecialFolder(mcache.getFolderName())) {
                 //mcache.fetch(msgs,FolderCache.flagsFP,0,start);
                 for(int i=0;i<start;++i) {
                 try {
                 if (!msgs[i].isSet(Flags.Flag.SEEN)) funread++;
                 } catch(Exception exc) {
                        
                 }
                 }
                 }*/
                total = sgi.threaded ? mcache.getThreadedCount() : xmsgs.length;
                if (start < max) {

                    Folder fsent = account.getFolder(account.getFolderSent());
                    boolean openedsent = false;
                    //Fetch others for these messages
                    mcache.fetch(xmsgs, (isdrafts ? draftsFP : messagesInfo.isPEC() ? pecFP : FP), start, max);
                    long tId = 0;
                    for (int i = 0, ni = 0; i < limit; ++ni, ++i) {
                        int ix = start + i;
                        int nx = start + ni;
                        if (nx >= xmsgs.length)
                            break;
                        if (ix >= max)
                            break;

                        SonicleIMAPMessage xm = (SonicleIMAPMessage) xmsgs[nx];
                        if (xm.isExpunged()) {
                            --i;
                            continue;
                        }

                        /*if (messagesInfo.checkSkipPEC(xm)) {
                           --i; --total;
                           continue;
                        }*/

                        /*String ids[]=null;
                         try {
                         ids=xm.getHeader("Message-ID");
                         } catch(MessagingException exc) {
                         --i;
                         continue;
                         }
                         if (ids==null || ids.length==0) { --i; continue; }
                         String idmessage=ids[0];*/

                        long nuid = mcache.getUID(xm);

                        int tIndent = xm.getThreadIndent();
                        if (tIndent == 0)
                            tId = nuid;
                        else if (sgi.threaded) {
                            if (!mcache.isThreadOpen(tId)) {
                                --i;
                                continue;
                            }
                        }
                        boolean tChildren = false;
                        int tUnseenChildren = 0;
                        if (sgi.threaded) {
                            int cnx = nx + 1;
                            while (cnx < xmsgs.length) {
                                SonicleIMAPMessage cxm = (SonicleIMAPMessage) xmsgs[cnx];
                                if (cxm.isExpunged()) {
                                    cnx++;
                                    continue;
                                }
                                while (cxm.getThreadIndent() > 0) {
                                    tChildren = true;
                                    if (!cxm.isExpunged() && !cxm.isSet(Flags.Flag.SEEN))
                                        ++tUnseenChildren;
                                    ++cnx;
                                    if (cnx >= xmsgs.length)
                                        break;
                                    cxm = (SonicleIMAPMessage) xmsgs[cnx];
                                }
                                break;
                            }
                        }

                        Flags flags = xm.getFlags();

                        //Date
                        java.util.Date d = xm.getSentDate();
                        if (d == null)
                            d = xm.getReceivedDate();
                        if (d == null)
                            d = new java.util.Date(0);
                        cal.setTime(d);
                        int yyyy = cal.get(java.util.Calendar.YEAR);
                        int mm = cal.get(java.util.Calendar.MONTH);
                        int dd = cal.get(java.util.Calendar.DAY_OF_MONTH);
                        int hhh = cal.get(java.util.Calendar.HOUR_OF_DAY);
                        int mmm = cal.get(java.util.Calendar.MINUTE);
                        int sss = cal.get(java.util.Calendar.SECOND);
                        //From
                        String from = "";
                        String fromemail = "";
                        Address ia[] = xm.getFrom();
                        if (ia != null) {
                            InternetAddress iafrom = (InternetAddress) ia[0];
                            from = iafrom.getPersonal();
                            if (from == null)
                                from = iafrom.getAddress();
                            fromemail = iafrom.getAddress();
                        }
                        from = (from == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(from)));
                        fromemail = (fromemail == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(fromemail)));

                        //To
                        String to = "";
                        String toemail = "";
                        ia = xm.getRecipients(Message.RecipientType.TO);
                        //if not sent and not shared, show me first if in TO
                        if (ia != null) {
                            InternetAddress iato = (InternetAddress) ia[0];
                            if (!issent && !isundershared) {
                                for (Address ax : ia) {
                                    InternetAddress iax = (InternetAddress) ax;
                                    if (iax.getAddress().equals(profile.getEmailAddress())) {
                                        iato = iax;
                                        break;
                                    }
                                }
                            }
                            to = iato.getPersonal();
                            if (to == null)
                                to = iato.getAddress();
                            toemail = iato.getAddress();
                        }
                        to = (to == null ? "" : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(to)));
                        toemail = (toemail == null ? ""
                                : StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(toemail)));

                        //Subject
                        String subject = xm.getSubject();
                        if (subject != null) {
                            try {
                                subject = MailUtils.decodeQString(subject);
                            } catch (Exception exc) {

                            }
                        } else
                            subject = "";

                        /*                  if (threaded) {
                                          if (tIndent>0) {
                                             StringBuffer sb=new StringBuffer();
                                             for(int w=0;w<tIndent;++w) sb.append("&nbsp;");
                                             subject=sb+subject;
                                          }
                                       }*/

                        boolean hasAttachments = mcache.hasAttachements(xm);

                        subject = StringEscapeUtils.escapeEcmaScript(MailUtils.htmlescape(subject));

                        //Unread
                        boolean unread = !xm.isSet(Flags.Flag.SEEN);
                        if (queryObj != null && unread)
                            ++funread;
                        //Priority
                        int priority = getPriority(xm);
                        //Status
                        java.util.Date today = new java.util.Date();
                        java.util.Calendar cal1 = java.util.Calendar.getInstance(locale);
                        java.util.Calendar cal2 = java.util.Calendar.getInstance(locale);
                        boolean isToday = false;
                        String gdate = "";
                        String sdate = "";
                        String xdate = "";
                        if (d != null) {
                            java.util.Date gd = sgi.threaded ? xm.getMostRecentThreadDate() : d;

                            cal1.setTime(today);
                            cal2.setTime(gd);

                            gdate = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(gd);
                            sdate = cal2.get(java.util.Calendar.YEAR) + "/"
                                    + String.format("%02d", (cal2.get(java.util.Calendar.MONTH) + 1)) + "/"
                                    + String.format("%02d", cal2.get(java.util.Calendar.DATE));
                            //boolean isGdate=group.equals("gdate");
                            if (cal1.get(java.util.Calendar.MONTH) == cal2.get(java.util.Calendar.MONTH)
                                    && cal1.get(java.util.Calendar.YEAR) == cal2.get(java.util.Calendar.YEAR)) {
                                int dx = cal1.get(java.util.Calendar.DAY_OF_MONTH)
                                        - cal2.get(java.util.Calendar.DAY_OF_MONTH);
                                if (dx == 0) {
                                    isToday = true;
                                    //if (isGdate) {
                                    //   gdate=WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_TODAY)+"  "+gdate;
                                    //}
                                    xdate = WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_TODAY);
                                } else if (dx == 1 /*&& isGdate*/) {
                                    xdate = WT.lookupCoreResource(locale, CoreLocaleKey.WORD_DATE_YESTERDAY);
                                }
                            }
                        }

                        String status = "read";
                        if (flags != null) {
                            if (flags.contains(Flags.Flag.ANSWERED)) {
                                if (flags.contains("$Forwarded"))
                                    status = "repfwd";
                                else
                                    status = "replied";
                            } else if (flags.contains("$Forwarded")) {
                                status = "forwarded";
                            } else if (flags.contains(Flags.Flag.SEEN)) {
                                status = "read";
                            } else if (isToday) {
                                status = "new";
                            } else {
                                status = "unread";
                            }
                            //                    if (flags.contains(Flags.Flag.USER)) flagImage=webtopapp.getUri()+"/images/themes/"+profile.getTheme()+"/mail/flag.gif";
                        }
                        //Size
                        int msgsize = 0;
                        msgsize = (xm.getSize() * 3) / 4;// /1024 + 1;
                        //User flags
                        String cflag = "";
                        for (WebtopFlag webtopFlag : webtopFlags) {
                            String flagstring = webtopFlag.label;
                            //String tbflagstring=webtopFlag.tbLabel;
                            if (!flagstring.equals("complete")) {
                                String oldflagstring = "flag" + flagstring;
                                if (flags.contains(flagstring) || flags.contains(oldflagstring)
                                /*|| (tbflagstring!=null && flags.contains(tbflagstring))*/
                                ) {
                                    cflag = flagstring;
                                }
                            }
                        }
                        boolean flagComplete = flags.contains("complete");
                        if (flagComplete) {
                            if (cflag.length() > 0)
                                cflag += "-complete";
                            else
                                cflag = "complete";
                        }

                        if (cflag.length() == 0 && flags.contains(Flags.Flag.FLAGGED))
                            cflag = "special";

                        boolean hasNote = flags.contains(sflagNote);

                        String svtags = getJSTagsArray(flags);

                        boolean autoedit = false;

                        boolean issched = false;
                        int syyyy = 0;
                        int smm = 0;
                        int sdd = 0;
                        int shhh = 0;
                        int smmm = 0;
                        int ssss = 0;
                        if (isdrafts) {
                            String h = getSingleHeaderValue(xm, "Sonicle-send-scheduled");
                            if (h != null && h.equals("true")) {
                                java.util.Calendar scal = parseScheduleHeader(
                                        getSingleHeaderValue(xm, "Sonicle-send-date"),
                                        getSingleHeaderValue(xm, "Sonicle-send-time"));
                                if (scal != null) {
                                    syyyy = scal.get(java.util.Calendar.YEAR);
                                    smm = scal.get(java.util.Calendar.MONTH);
                                    sdd = scal.get(java.util.Calendar.DAY_OF_MONTH);
                                    shhh = scal.get(java.util.Calendar.HOUR_OF_DAY);
                                    smmm = scal.get(java.util.Calendar.MINUTE);
                                    ssss = scal.get(java.util.Calendar.SECOND);
                                    issched = true;
                                    status = "scheduled";
                                }
                            }

                            h = getSingleHeaderValue(xm, HEADER_SONICLE_FROM_DRAFTER);
                            if (h != null && h.equals("true")) {
                                autoedit = true;
                            }
                        }

                        String xmfoldername = xm.getFolder().getFullName();

                        //idmessage=idmessage.replaceAll("\\\\", "\\\\");
                        //idmessage=Utils.jsEscape(idmessage);
                        if (i > 0)
                            sout += ",\n";
                        boolean archived = false;
                        if (hasDmsDocumentArchiving()) {
                            archived = xm.getHeader("X-WT-Archived") != null;
                            if (!archived) {
                                archived = flags.contains(sflagDmsArchived);
                            }
                        }

                        String msgtext = null;
                        if (us.getShowMessagePreviewOnRow() && isToday && unread) {
                            try {
                                msgtext = MailUtils.peekText(xm);
                                if (msgtext != null) {
                                    msgtext = msgtext.trim();
                                    if (msgtext.length() > 100)
                                        msgtext = msgtext.substring(0, 100);
                                }
                            } catch (MessagingException | IOException ex1) {
                                msgtext = ex1.getMessage();
                            }
                        }

                        String pecstatus = null;
                        if (messagesInfo.isPEC()) {
                            String hdrs[] = xm.getHeader(HDR_PEC_TRASPORTO);
                            if (hdrs != null && hdrs.length > 0
                                    && (hdrs[0].equals("errore") || hdrs[0].equals("posta-certificata")))
                                pecstatus = hdrs[0];
                            else {
                                hdrs = xm.getHeader(HDR_PEC_RICEVUTA);
                                if (hdrs != null && hdrs.length > 0)
                                    pecstatus = hdrs[0];
                            }
                        }

                        sout += "{idmessage:'" + nuid + "'," + "priority:" + priority + "," + "status:'"
                                + status + "'," + "to:'" + to + "'," + "toemail:'" + toemail + "'," + "from:'"
                                + from + "'," + "fromemail:'" + fromemail + "'," + "subject:'" + subject + "',"
                                + (msgtext != null
                                        ? "msgtext: '" + StringEscapeUtils.escapeEcmaScript(msgtext) + "',"
                                        : "")
                                + (sgi.threaded ? "threadId: " + tId + "," : "")
                                + (sgi.threaded ? "threadIndent:" + tIndent + "," : "") + "date: new Date("
                                + yyyy + "," + mm + "," + dd + "," + hhh + "," + mmm + "," + sss + "),"
                                + "gdate: '" + gdate + "'," + "sdate: '" + sdate + "'," + "xdate: '" + xdate
                                + "'," + "unread: " + unread + "," + "size:" + msgsize + ","
                                + (svtags != null ? "tags: " + svtags + "," : "")
                                + (pecstatus != null ? "pecstatus: '" + pecstatus + "'," : "") + "flag:'"
                                + cflag + "'" + (hasNote ? ",note:true" : "") + (archived ? ",arch:true" : "")
                                + (isToday ? ",istoday:true" : "") + (hasAttachments ? ",atts:true" : "")
                                + (issched
                                        ? ",scheddate: new Date(" + syyyy + "," + smm + "," + sdd + "," + shhh
                                                + "," + smmm + "," + ssss + ")"
                                        : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadOpen: " + mcache.isThreadOpen(nuid)
                                        : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadHasChildren: " + tChildren : "")
                                + (sgi.threaded && tIndent == 0 ? ",threadUnseenChildren: " + tUnseenChildren
                                        : "")
                                + (sgi.threaded && xm.hasThreads() && !xm.isMostRecentInThread() ? ",fmtd: true"
                                        : "")
                                + (sgi.threaded && !xmfoldername.equals(folder.getFullName()) ? ",fromfolder: '"
                                        + StringEscapeUtils.escapeEcmaScript(xmfoldername) + "'" : "")
                                + "}";

                        if (autoedit) {
                            autoeditList.add(nuid);
                        }

                        //                sout+="{messageid:'"+m.getMessageID()+"',from:'"+from+"',subject:'"+subject+"',date: new Date("+yyyy+","+mm+","+dd+"),unread: "+unread+"},\n";
                    }

                    if (openedsent)
                        fsent.close(false);
                }
                /*                if (ppattern==null && !isSpecialFolder(mcache.getFolderName())) {
                 //if (max<msgs.length) mcache.fetch(msgs,FolderCache.flagsFP,max,msgs.length);
                 for(int i=max;i<msgs.length;++i) {
                 try {
                 if (!msgs[i].isSet(Flags.Flag.SEEN)) funread++;
                 } catch(Exception exc) {
                        
                 }
                 }
                 } else {
                 funread=mcache.getUnreadMessagesCount();
                 }*/
                if (mcache.isScanForcedOrEnabled()) {
                    //Send message only if first page
                    if (start == 0)
                        mcache.refreshUnreads();
                    funread = mcache.getUnreadMessagesCount();
                } else
                    funread = 0;

                long qlimit = -1;
                long qusage = -1;
                try {
                    Quota quotas[] = account.getQuota("INBOX");
                    if (quotas != null)
                        for (Quota q : quotas) {
                            if ((q.quotaRoot.equals("INBOX") || q.quotaRoot.equals("Quota"))
                                    && q.resources != null) {
                                for (Quota.Resource r : q.resources) {
                                    if (r.name.equals("STORAGE")) {
                                        qlimit = r.limit;
                                        qusage = r.usage;
                                    }
                                }
                            }
                        }
                } catch (MessagingException exc) {
                    logger.debug("Error on QUOTA", exc);
                }

                sout += "\n],\n";
                sout += "total: " + (total - expunged) + ",\n";
                if (qlimit >= 0 && qusage >= 0)
                    sout += "quotaLimit: " + qlimit + ", quotaUsage: " + qusage + ",\n";
                if (messagesInfo.isPEC())
                    sout += "isPEC: true,\n";
                sout += "realTotal: " + (xmsgs.length - expunged) + ",\n";
                sout += "expunged: " + (expunged) + ",\n";
            } else {
                sout += "messages: [],\n" + "total: 0,\n" + "realTotal: 0,\n" + "expunged:0,\n";
            }
            sout += "metaData: {\n" + "  root: 'messages', total: 'total', idProperty: 'idmessage',\n"
                    + "  fields: ['idmessage','priority','status','to','from','subject','date','gdate','unread','size','flag','note','arch','istoday','atts','scheddate','fmtd','fromfolder'],\n"
                    + "  sortInfo: { field: '" + psortfield + "', direction: '" + psortdir + "' },\n"
                    + "  threaded: " + sgi.threaded + ",\n" + "  groupField: '"
                    + (sgi.threaded ? "threadId" : group) + "',\n";

            /*            ColumnVisibilitySetting cvs = us.getColumnVisibilitySetting(pfoldername);
                        ColumnsOrderSetting cos = us.getColumnsOrderSetting();
                        // Apply grid defaults
                        //ColumnVisibilitySetting.applyDefaults(mcache.isSent(), cvs);
                        ColumnVisibilitySetting.applyDefaults(issent||isundersent, cvs);
                    
                        if (autoeditList.size()>0) {
                           sout+="autoedit: [";
                           for(long muid: autoeditList) {
                              sout+=muid+",";
                           }
                           if(StringUtils.right(sout, 1).equals(",")) sout = StringUtils.left(sout, sout.length()-1);
                           sout+="],\n";
                        }
                                
                        // Fills columnsInfo object for client rendering
                        sout += "colsInfo2: [";
                        for (String dataIndex : cvs.keySet()) {
                           sout += "{dataIndex:'" + dataIndex + "',hidden:" + String.valueOf(!cvs.get(dataIndex)) + ",index:"+cos.indexOf(dataIndex)+"},";
                        }
                        if (StringUtils.right(sout, 1).equals(",")) {
                           sout = StringUtils.left(sout, sout.length() - 1);
                        }
                        sout += "]\n";*/

            sout += "},\n";
            sout += "threaded: " + (sgi.threaded ? "1" : "0") + ",\n";
            sout += "unread: " + funread + ", issent: " + issent + ", millis: " + messagesInfo.millis + " }\n";

        } else {
            sout += "total:0,\nstart:0,\nlimit:0,\nmessages: [\n";
            sout += "\n], unread: 0, issent: false }\n";
        }
        out.println(sout);
    } catch (Exception exc) {
        new JsonResult(exc).printTo(out);
        Service.logger.error("Exception", exc);
    }
}

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

/**
 * Construct the folder subtree for the given folder and append it to
 * xml_parent.//  ww w  .j av a2 s .  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

/**
 * Refresh Information about folders./*from ww w.  j  ava2  s. c  o m*/
 * Tries to connect folders that are not yet connected.
 *
 * @doCount display message counts for user
 */
public void refreshFolderInformation(boolean subscribed_only, boolean doCount) {
    /* Right now, doCount corresponds exactly to subscribed_only.
     * When we add a user preference setting or one-time action,
     * to present messages from all folders, we will have
     * subscribed_only false and doCount true. */

    //log.fatal("Invoking refreshFolderInformation(boolean, boolean)",
    //new Throwable("Thread Dump"));  FOR DEBUGGING
    setEnv();
    if (folders == null)
        folders = new Hashtable<String, Folder>();
    Folder rootFolder = null;
    String cur_mh_id = "";
    Enumeration mailhosts = user.mailHosts();
    int max_depth = 0;
    int folderType;

    while (mailhosts.hasMoreElements()) {
        cur_mh_id = (String) mailhosts.nextElement();

        MailHostData mhd = user.getMailHost(cur_mh_id);

        URLName url = new URLName(mhd.getHostURL());

        Element mailhost = model.createMailhost(mhd.getName(), mhd.getID(), url.toString());

        int depth = 0;

        try {
            rootFolder = getRootFolder(cur_mh_id);

            try {
                rootFolder.setSubscribed(true);
            } catch (MessagingException ex) {
                // Only IMAP supports subscription
                log.warn("Folder.setSubscribed failed.  " + "Probably a non-supporting mail service: " + ex);
            }
        } catch (MessagingException ex) {
            mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to connect and get Root folder from (" + url + ')', ex);
            return;
        }

        try {
            depth = getFolderTree(rootFolder.getFolder("INBOX"), mailhost, subscribed_only, doCount);
            log.debug("Loaded INBOX folders below Root to a depth of " + depth);
            String extraFolderPath = ((imapBasedir == null) ? "~" : imapBasedir) + mhd.getLogin();
            //String extraFolderPath = "/home/" + mhd.getLogin();
            Folder nonInboxBase = rootFolder.getFolder(extraFolderPath);
            log.debug("Trying extra base dir " + nonInboxBase.getFullName());
            if (nonInboxBase.exists()) {
                folderType = nonInboxBase.getType();
                if ((folderType & Folder.HOLDS_MESSAGES) != 0) {
                    // Can only Subscribe to Folders which may hold Msgs.
                    nonInboxBase.setSubscribed(true);
                    if (!nonInboxBase.isSubscribed())
                        log.error("A bug in JavaMail or in the server is " + "preventing subscription to '"
                                + nonInboxBase.getFullName() + "' on '" + url
                                + "'.  Folders will not be visible.");
                }
                int extraDepth = extraDepth = getFolderTree(nonInboxBase, mailhost, subscribed_only, doCount);
                if (extraDepth > depth)
                    depth = extraDepth;
                log.debug("Loaded additional folders from below " + nonInboxBase.getFullName()
                        + " with max depth of " + extraDepth);
            }
        } catch (Exception ex) {
            if (!url.getProtocol().startsWith("pop"))
                mailhost.setAttribute("error", ex.getMessage());
            log.warn("Failed to fetch child folders from (" + url + ')', ex);
        }
        if (depth > max_depth)
            max_depth = depth;
        model.addMailhost(mailhost);
    }
    model.setStateVar("max folder depth", (1 + max_depth) + "");
}

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

/**
   Connect to mailhost "name"/*www  .  j  a  v  a 2 s .c  o m*/
*/
public Folder connect(String name) throws MessagingException {
    MailHostData m = user.getMailHost(name);
    URLName url = new URLName(m.getHostURL());

    Store st = connectStore(url.getHost(), url.getProtocol(), m.getLogin(), m.getPassword());

    Folder f = st.getDefaultFolder();
    connections.put(name, f);
    log.info("Mail: Default folder '" + f.getFullName() + "' retrieved from store " + st + '.');
    return f;
}

From source file:org.apache.hupa.server.handler.FetchFoldersHandler.java

/**
 * Create a new IMAPFolder from the given Folder
 * //ww  w  .ja va 2  s.  c o  m
 * @param folder Current folder
 * @return imapFolder Created IMAPFolder
 * @throws ActionException If an error occurs
 * @throws MessagingException If an error occurs
 */
private IMAPFolder createIMAPFolder(Folder folder) throws ActionException {

    String fullName = folder.getFullName();
    String delimiter;
    IMAPFolder iFolder = null;

    try {
        logger.debug("Creating folder: " + fullName + " for user: " + getUser());
        delimiter = String.valueOf(folder.getSeparator());
        iFolder = new IMAPFolder(fullName);
        iFolder.setDelimiter(delimiter);
        if ("[Gmail]".equals(folder.getFullName()))
            return iFolder;
        iFolder.setMessageCount(folder.getMessageCount());
        iFolder.setSubscribed(folder.isSubscribed());
        iFolder.setUnseenMessageCount(folder.getUnreadMessageCount());
    } catch (MessagingException e) {
        logger.error("Unable to construct folder " + folder.getFullName(), e);
    }

    return iFolder;
}

From source file:org.apache.hupa.server.utils.TestUtils.java

public static String dumpStore(IMAPStore store) throws MessagingException {
    String ret = "";
    for (Folder f : store.getDefaultFolder().list()) {
        ret += f.getFullName() + " " + f.getMessageCount() + "\n";
    }//from  w  w w  . j  a v a  2  s.c om
    return ret;
}