Example usage for javax.mail Folder getName

List of usage examples for javax.mail Folder getName

Introduction

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

Prototype

public abstract String getName();

Source Link

Document

Returns the name of this Folder.

Usage

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

public String getInternationalFolderName(FolderCache fc) {
    Folder folder = fc.getFolder();
    String desc = folder.getName();
    String fullname = folder.getFullName();
    //WebTopApp webtopapp=environment.getWebTopApp();
    Locale locale = environment.getProfile().getLocale();
    if (fc.isInbox()) {
        desc = lookupResource(MailLocaleKey.FOLDERS_INBOX);
    } else if (fc.isSharedFolder()) {
        desc = lookupResource(MailLocaleKey.FOLDERS_SHARED);
    } else if (fc.isDrafts()) {
        desc = lookupResource(MailLocaleKey.FOLDERS_DRAFTS);
    } else if (fc.isTrash()) {
        desc = lookupResource(MailLocaleKey.FOLDERS_TRASH);
    } else if (fc.isArchive()) {
        desc = lookupResource(MailLocaleKey.FOLDERS_ARCHIVE);
    } else if (fc.isSent()) {
        desc = lookupResource(MailLocaleKey.FOLDERS_SENT);
    } else if (fc.isSpam()) {
        desc = lookupResource(MailLocaleKey.FOLDERS_SPAM);
    }//from www.  j  a  v a  2s  .  c o m
    return desc;
}

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 ww w .ja  va 2  s  .  co m
    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

private String getSharedFolderName(MailAccount account, String mailUser, String folder)
        throws MessagingException {
    FolderCache folderCache = null;/*  ww  w.  j av a2s  . c  om*/
    String sharedFolderName = null;
    String folderName = null;

    // Clear mailUser removing any domain info (ldap auth contains 
    // domain suffix), we don't want it!
    String user = StringUtils.split(mailUser, "@")[0];
    // INBOX is a fake name, it's equals to user's direct folder
    boolean isInbox = folder.equals("INBOX");

    FolderCache[] sharedCache = account.getSharedFoldersCache();
    for (FolderCache sharedFolder : sharedCache) {
        sharedFolderName = sharedFolder.getFolderName();
        folderCache = account.getFolderCache(sharedFolderName);
        for (Folder fo : folderCache.getFolder().list()) {
            folderName = fo.getFullName();
            char sep = fo.getSeparator();
            //if is a shared mailbox, and it contains an @, match it with mail user (NS7)
            //or just user instead (XStream and NS6)
            String name = isInbox ? (fo.getName().indexOf('@') > 0 ? mailUser : user) : folder;
            if (folderName.equals(sharedFolderName + sep + name))
                return folderName;
        }
    }
    return null;
}

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;//from  w ww.ja  va 2  s  . c om
    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:net.wastl.webmail.server.WebMailSession.java

/**
 * Construct the folder subtree for the given folder and append it to
 * xml_parent.// w  ww.j  a v  a 2  s .c  o  m
 *
 * 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:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Attempts to close the supplied folder. If expunge is true then all messages
 * marked for deletion will be expunged from the folder.
 *
 * @throws MessagingException if there was a problem
 *///from   w  w  w  .j  a v a2s  .  c om
public void closeFolder(Folder fldr, boolean expunge) throws MessagingException {
    if (fldr == null || !fldr.isOpen())
        return;

    fldr.close(expunge);
    log.debug("Folder [" + fldr.getName() + "] closed. " + "Deleted messages will " + (expunge ? "not " : "")
            + "be expunged");
}

From source file:org.openadaptor.auxil.connector.mail.MailConnection.java

/**
 * Copies the supplied message to the destination folder as defined in the
 * properties file// w w w  . ja v  a2  s. c  om
 *
 * @throws MessagingException if the destination folder cannot be found
 */
public void copyMsgToFolder(Message msg, String folder, boolean create) throws MessagingException {
    Folder dest = openFolder(folder, create);
    Folder source = msg.getFolder();

    source.copyMessages(new Message[] { msg }, dest);
    log.debug("Copied message to [" + dest.getName() + "]");

    // as we are moving the message to another folder, we can assume that we
    // do not want to delete it so we don't need to expunge the folder
    closeFolder(dest, false);
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

public SetMessageResponseType archiveMessage(SetMessageRequestType request) {
    SetMessageResponseType response = new SetMessageResponseType();

    IMAPSSLStore sslStore = null;/*w  w  w . j  a  v a  2 s. co  m*/
    Folder folder = null;
    Folder destinationFolder = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    // INPUT:  request.getUserId()
    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDAO contactDAO = LdapService.getContactDAO();
    ContactDTO foundContact = new ContactDTO();
    List<ContactDTO> contacts = contactDAO.findAllContacts();
    for (ContactDTO contact : contacts) {
        if (contact.getUid() != null && contact.getUid().equals(request.getUserId())) {
            foundContact = contact;
            break;
        }
    }

    String userType = "";
    String[] access = new String[2];
    String userCName = foundContact.getCommonName();
    if (contacts.isEmpty()) {
        log.error("Contact record not found for user: " + userCName);
        response.setMessage("Contact record not found for user: " + userCName);
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(userCName, foundContact.getUid()); //TMN

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    //PROCESSING the action.
    // folder --> the current folder the msg being processed is in.
    // destinationFolder --> the destination folder where the msg will be moved.
    try {

        //----------------------------------
        // Determine/Set destination folder
        //----------------------------------
        if (request.getAction().equals("Archive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "Archives");
        } else if (request.getAction().equals("Unarchive")) {
            destinationFolder = getImapFolder(session, sslStore, access, "INBOX");
        }
        destinationFolder.open(Folder.READ_WRITE);

        //----------------------------------
        // Set originating folder
        //----------------------------------
        folder = getImapFolder(session, sslStore, access,
                this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
        folder.open(Folder.READ_WRITE);

        System.out.println(
                "===> DMD.archiveMessage: " + request.getAction() + "-ing for msgId=" + request.getMessageId()
                        + "\n===> from " + folder.getName() + " to folder=" + destinationFolder.getName());

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

        //--------------------------------------------
        // Process the message
        //--------------------------------------------
        if (imapMessage != null) {
            Message[] messages = new Message[] { imapMessage };
            folder.copyMessages(messages, destinationFolder);
            imapMessage.setFlag(Flags.Flag.DELETED, true);
            folder.expunge();

            System.out.println("===> DMD.archiveMessage: Done " + request.getAction() + " for msgId="
                    + request.getMessageId());

            response.setSuccessStatus(true);

        } else {
            String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
            System.out.println("===> " + statMsg);

            response.setSuccessStatus(false);
            response.setMessage(statMsg);
        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage(
                "Error " + request.getAction() + " mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        e.printStackTrace();
        return response;

    } finally {
        try {
            if ((folder != null) && folder.isOpen())
                folder.close(false);
            if ((destinationFolder != null) && destinationFolder.isOpen())
                destinationFolder.close(false);
        } catch (MessagingException me) {
            me.printStackTrace();
        }
    }

    return response;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 *
 * @param request//www .j  av a  2s. co  m
 *        where request.action = [ "Send" , "Update" ,"Read" , "Save" ]
 * @return
 */
private SetMessageResponseType sendImapSSLMail(SetMessageRequestType request) {

    //System.out.println("===> sendImapSSLMail: Action= " + request.getAction());

    SetMessageResponseType response = new SetMessageResponseType();
    IMAPSSLStore sslStore = null;
    Folder folder = null; //the email server folder the msg is CURRENTLY in.

    String userType = "";
    String[] access = new String[2];

    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //Get email address and password from LDAP
    String userId = request.getUserId();
    ContactDTO foundContact = null;
    try {
        foundContact = findContactByUserId(userId);
    } catch (Exception e) {
        log.error("Contact record not found for userid: " + request.getUserId());
        response.setMessage("Contact record not found for userid: " + request.getUserId());
        response.setSuccessStatus(false);
        return response;
    }

    access = retrieveMailAccess(foundContact.getCommonName(), foundContact.getUid());

    if ((access[0] == null) || access[0].isEmpty()) {
        log.error("Contact record not found for user: " + userId);
        response.setMessage("Contact record not found for user: " + userId);
        response.setSuccessStatus(false);
        return response;
    }

    // Use the sslStore to send/change the message
    try {
        //action = Save
        if (request.getAction().equalsIgnoreCase("Save")) {
            response = saveDraft(request, access, sslStore,
                    this.mapKmrLocationToImapFolder("Drafts", this.host), session);
            response.setSuccessStatus(true);
            //return response;
        }
        //action = Send
        else if (request.getAction().equalsIgnoreCase("Send")) {
            // create and send msg to recipient(s).
            Message[] msgArr = createMessage(session, access[0], request);
            sendMessagesTOCCBCC(msgArr, request, session);

            // Store a copy to sender's Sent folder
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder("Sent", this.host));
            folder.appendMessages(msgArr);

            response.setSuccessStatus(true);
        }
        //action = ..any other..
        else {
            folder = getImapFolder(session, sslStore, access,
                    this.mapKmrLocationToImapFolder(request.getLocation(), this.host));
            folder.open(Folder.READ_WRITE);

            //--------------------------------------------
            // Find the message by the given Message-ID
            //--------------------------------------------
            IMAPMessage imapMessage = (IMAPMessage) findMsgByMessageId(folder, request.getMessageId());

            //--------------------------------------------
            // Process the message
            //--------------------------------------------
            if (imapMessage != null) {
                System.out.println("===> sendImapSSLMail:Updating:   action=" + request.getAction());
                System.out.println("===> sendImapSSLMail:Updating:   folder=" + folder.getName());
                System.out.println("===> sendImapSSLMail:Updating:ImapMsgID=" + imapMessage.getMessageID());

                updateImapSSLMail(request, folder, imapMessage);

                System.out.println("===> sendImapSSLMail: Done Setting " + request.getAction() + " for msgId="
                        + request.getMessageId());

                response.setSuccessStatus(true);

            } else {
                String statMsg = "Msg NOT found for Message-ID=" + request.getMessageId();
                System.out.println("===> sendImapSSLMail: " + statMsg);

                response.setSuccessStatus(false);
                response.setMessage(statMsg);
            }

        }

    } catch (Exception e) {
        log.error(e.getMessage());
        response.setMessage("Error sending mail with Zimbra mail server: " + e.getMessage());
        response.setSuccessStatus(false);
        return response;
    } finally {
        if (folder != null && folder.isOpen()) {
            try {
                folder.close(false);
            } catch (MessagingException me) {
                log.error("Error closing folder");
            }
        }
        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (MessagingException me) {
                log.error("Error closing SSLStore");
            }
        }
    }

    return response;

}

From source file:org.xwiki.contrib.mail.internal.AbstractMailStore.java

@Override
public ArrayList<FolderItem> getFolderTree() throws MessagingException {
    getLogger().debug("getFolderTree");

    assert (getMailSource() != null);

    ArrayList<FolderItem> folderItems = new ArrayList<FolderItem>();

    Store store = getJavamailStore();//from  w  w w .j ava  2 s .c  om
    store.connect();
    Folder defaultFolder = store.getDefaultFolder();
    FolderItem item = new FolderItem();
    item.setIndex(0);
    item.setLevel(0);
    item.setName(defaultFolder.getName());
    item.setFullName(defaultFolder.getFullName());
    if ((defaultFolder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
        item.setMessageCount(defaultFolder.getMessageCount());
        item.setUnreadMessageCount(defaultFolder.getUnreadMessageCount());
        item.setNewMessageCount(defaultFolder.getNewMessageCount());
    }
    Folder[] folders = defaultFolder.list("*");
    if (ArrayUtils.isEmpty(folders)) {
        folders = defaultFolder.list();
    }

    getLogger().debug("Found folders {}", ArrayUtils.toString(folders));
    int index = 1;
    int level = 1;
    // TODO not really managing folders here, just listing them
    for (Folder folder : folders) {

        item = new FolderItem();
        item.setIndex(index);
        item.setLevel(level);
        item.setName(folder.getName());
        item.setFullName(folder.getFullName());
        if ((folder.getType() & javax.mail.Folder.HOLDS_MESSAGES) != 0) {
            item.setMessageCount(folder.getMessageCount());
            item.setUnreadMessageCount(folder.getUnreadMessageCount());
            item.setNewMessageCount(folder.getNewMessageCount());
            folderItems.add(item);
        }
    }

    store.close();

    return folderItems;

}