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: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;

        }//from w ww . j ava2s .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:com.sonicle.webtop.mail.MailAccount.java

protected synchronized FolderCache addSingleFoldersCache(FolderCache parent, Folder child)
        throws MessagingException {
    String cname = child.getFullName();
    FolderCache fcChild = foldersCache.get(cname);
    if (fcChild == null) {
        fcChild = createFolderCache(child);
        if (parent != null) {
            fcChild.setParent(parent);/*w w w. j a v  a 2s  . co m*/
            parent.addChild(fcChild);
        }
        fcChild.setStartupLeaf(isLeaf((IMAPFolder) child));
    }

    return fcChild;
}

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

private void _loadFoldersCache(FolderCache fc) throws MessagingException {
    Folder f = fc.getFolder();//from w  w  w .java 2s .  c  o  m
    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);
    }
    //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.sonicle.webtop.mail.MailAccount.java

private boolean connect() {
    try {//from ww w .  ja  va  2s  .  c  o  m
        if (store != null && store.isConnected()) {
            disconnecting = true;
            store.close();
        }

        store = session.getStore(storeProtocol);
    } catch (Exception exc) {
        Service.logger.error("Exception", exc);
    }
    boolean sucess = true;
    disconnecting = false;
    try {

        //warning: trace mode shows credentials
        Service.logger.trace("  accessing " + storeProtocol + "://" + mailUsername + ":" + mailPassword + "@"
                + mailHost + ":" + port);
        if (isImpersonated)
            Service.logger.info(" impersonating " + authorizationId);

        if (port > 0) {
            store.connect(mailHost, port, mailUsername, mailPassword);
        } else {
            store.connect(mailHost, mailUsername, mailPassword);
        }
        folderSeparator = getDefaultFolder().getSeparator();
        Folder un[] = store.getUserNamespaces("");
        sharedPrefixes = new String[un.length];
        int ix = 0;
        for (Folder sp : un) {
            String s = sp.getFullName();
            //if (s.endsWith(""+folderSeparator)) s=s.substring(0,s.length()-1);
            sharedPrefixes[ix] = s;
            ++ix;
        }
        hasAnnotations = ((IMAPStore) store).hasCapability("ANNOTATEMORE");
        if (((IMAPStore) store).hasCapability("ID")) {
            Map<String, String> map = ((IMAPStore) store).id(null);
            isDovecot = (map != null && map.containsKey("name") && map.get("name").equalsIgnoreCase("dovecot"));
            //leave hasInboxFolder as it was set in case it's not Dovecot
            if (isDovecot)
                hasInboxFolder = true;
        }

    } catch (MessagingException exc) {
        Service.logger.error("Error connecting to the mail server " + mailHost, exc);
        sucess = false;
    }

    return sucess;

}

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

public void loadFoldersCache(final Object lock, boolean waitLoad) throws MessagingException {
    Folder froot = getDefaultFolder();/*w w w  . j a  v a2 s .co  m*/
    fcRoot = createFolderCache(froot);
    fcRoot.setIsRoot(true);
    Folder children[] = fcRoot.getFolder().list();
    final ArrayList<FolderCache> rootParents = new ArrayList<FolderCache>();
    for (Folder child : children) {
        if (ms.isFolderHidden(this, child.getFullName()))
            continue;
        if (!fcRoot.hasChild(child.getName())) {
            FolderCache fcc = addSingleFoldersCache(fcRoot, child);
            if (!fcc.isStartupLeaf())
                rootParents.add(fcc);
        }
    }

    if (hasDifferentDefaultFolder) {
        //check for other shared folders to be added
        Folder rfolders[] = store.getDefaultFolder().list();
        for (int i = 0; i < sharedPrefixes.length; ++i) {
            for (int j = 0; j < rfolders.length; ++j) {
                if (rfolders[j].getFullName().equals(sharedPrefixes[i])) {
                    FolderCache fcc = addSingleFoldersCache(fcRoot, rfolders[j]);
                    rootParents.add(fcc);
                }
            }
        }
    }

    Thread engine = new Thread(new Runnable() {
        public void run() {
            synchronized (lock) {
                try {
                    for (FolderCache fc : rootParents) {
                        _loadFoldersCache(fc);
                    }
                } catch (MessagingException exc) {
                    Service.logger.error("Exception", exc);
                }
            }
        }
    });
    engine.start();
    try {
        if (waitLoad)
            engine.join();
    } catch (InterruptedException exc) {
        Service.logger.error("Error waiting folder cache load", exc);
    }
}

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;
    }/* w  w  w  . jav  a2s . c om*/
    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.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Move {@link GmailMessage} to a given destination folder.
 *
 * @param destFolder the destination {@link Folder} name.See {@see ImapGmailLabel}
 * @param messageNumber the message number ex:{@code gmailMessage.getMessageNumber()}
 * @throws GmailException if it fails to move {@link GmailMessage} to the
 * destination folder//from  w  ww  .  j  av a  2 s .c o  m
 */
public void moveTo(ImapGmailLabel destFolder, int messageNumber) {
    if (messageNumber <= 0) {
        throw new GmailException("ImapGmailClient invalid GmailMessage number");
    }

    Folder fromFolder = null;
    Folder toFolder = null;

    try {
        final Store store = openGmailStore();
        fromFolder = getFolder(this.srcFolder, store);
        fromFolder.open(Folder.READ_WRITE);
        Message message = fromFolder.getMessage(messageNumber);

        if (message != null) {
            toFolder = getFolder(destFolder.getName(), store);

            if (fromFolder.getURLName().equals(toFolder.getURLName())) {
                throw new GmailException("ImapGmailClient cannot move " + "GmailMessage within same folder "
                        + "(from " + fromFolder.getFullName() + " to " + toFolder.getFullName() + ")");
            }
            // copy from source folder to destination folder
            fromFolder.copyMessages(new Message[] { message }, toFolder);
            // move the copied message to trash folder
            moveToTrash(new GmailMessage[] { new JavaMailGmailMessage(message) });
        }
    } catch (GmailException ge) {
        throw ge;
    } catch (Exception e) {
        throw new GmailException(
                "ImapGmailClient failed moving" + " GmailMessage from " + fromFolder.getFullName(), e);
    } finally {
        closeFolder(fromFolder);
    }
}

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

public void storeEnvelopes(long folderId, boolean allMessages) throws PortalException {

    Folder jxFolder = null;/* www . ja  va2s.  c  o  m*/

    try {
        com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.fetchFolder(folderId);

        if (folder == null) {
            return;
        }

        jxFolder = openFolder(folderId);

        int messageCount = jxFolder.getMessageCount();

        FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(),
                messageCount);

        if (messageCount == 0) {
            return;
        }

        Message oldestJxMessage = getMessage(folderId, jxFolder, true);
        Message newestJxMessage = getMessage(folderId, jxFolder, false);

        Message[] jxMessages = new Message[0];

        if (allMessages) {
            if (_log.isDebugEnabled()) {
                _log.debug("Downloading all messages from folder " + jxFolder.getFullName());
            }

            jxMessages = jxFolder.getMessages();
        } else if ((oldestJxMessage == null) && (newestJxMessage == null)) {
            if (_log.isDebugEnabled()) {
                _log.debug(
                        "Downloading messages from folder " + jxFolder.getFullName() + " for the first time");
            }

            int startingMessageNumber = messageCount - PortletPropsValues.MESSAGES_SYNC_COUNT;

            if (startingMessageNumber < 1) {
                startingMessageNumber = 1;
            }

            jxMessages = jxFolder.getMessages(startingMessageNumber, messageCount);
        } else {
            int oldestMessageNumber = oldestJxMessage.getMessageNumber();
            int newestMessageNumber = newestJxMessage.getMessageNumber();

            if (newestMessageNumber != messageCount) {
                if (_log.isDebugEnabled()) {
                    _log.debug("Downloading new messages from folder " + jxFolder.getFullName());
                }

                jxMessages = jxFolder.getMessages(newestMessageNumber + 1, messageCount);
            } else if (oldestMessageNumber != 1) {
                if (_log.isDebugEnabled()) {
                    _log.debug("Downloading old messages from folder " + jxFolder.getFullName());
                }

                int startingMessageNumber = oldestMessageNumber - PortletPropsValues.MESSAGES_SYNC_COUNT;

                if (startingMessageNumber < 1) {
                    startingMessageNumber = 1;
                }

                jxMessages = jxFolder.getMessages(startingMessageNumber, oldestMessageNumber - 1);
            }
        }

        storeEnvelopes(folderId, jxFolder, jxMessages);
    } catch (MessagingException me) {
        throw new MailException(me);
    } finally {
        closeFolder(jxFolder, false);
    }
}

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

public boolean isDefaultFolder(String foldername) {
    Folder df = null;
    try {/*  w  ww  . j av a  2  s.c  om*/
        df = getDefaultFolder();
    } catch (MessagingException exc) {
        Service.logger.error("Error getting default folder", exc);
    }
    if (df != null)
        return df.getFullName().equals(foldername);
    return false;
}

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

public String[] addFolder(String displayName) throws MailException {
    try {//from   w w w  .j a va2 s.  co m
        String fullName = displayName;

        if (Validator.isNotNull(_account.getFolderPrefix())) {
            Store store = _imapConnection.getStore(true);

            Folder jxFolder = store.getDefaultFolder();

            fullName = _account.getFolderPrefix() + jxFolder.getSeparator() + displayName;
        }

        Folder jxFolder = getFolder(fullName);

        if (jxFolder.exists()) {
            throw new MailException(MailException.FOLDER_ALREADY_EXISTS);
        } else {
            if (jxFolder.create(Folder.HOLDS_MESSAGES)) {
                return new String[] { jxFolder.getFullName(), jxFolder.getName() };
            }

            throw new MailException(MailException.FOLDER_CREATE_FAILED);
        }
    } catch (MessagingException me) {
        throw new MailException(me);
    }
}