Example usage for javax.mail Folder getMessageCount

List of usage examples for javax.mail Folder getMessageCount

Introduction

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

Prototype

public abstract int getMessageCount() throws MessagingException;

Source Link

Document

Get total number of messages in this Folder.

Usage

From source file:org.webguitoolkit.messagebox.mail.MailChannel.java

/**
 * //from  w w  w  . j  a v  a  2s. co m
 */
@Override
public List<IMessage> receive(boolean clear) {
    List<IMessage> result = new ArrayList<IMessage>();

    try {
        String user = properties.getProperty("pop3.login.user");
        String password = properties.getProperty("pop3.login.password");

        String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";

        Properties pop3Props = new Properties();

        pop3Props.setProperty("mail.pop3.socketFactory.class", SSL_FACTORY);
        pop3Props.setProperty("mail.pop3.socketFactory.fallback", "false");
        pop3Props.setProperty("mail.pop3.port", properties.getProperty("pop3.port"));
        pop3Props.setProperty("mail.pop3.socketFactory.port", properties.getProperty("pop3.port"));

        URLName url = new URLName("pop3", properties.getProperty("pop3.host"),
                Integer.valueOf(properties.getProperty("pop3.port")), "", user, password);

        Session session = Session.getInstance(pop3Props, null);
        Store store = new POP3SSLStore(session, url);
        store.connect();

        // Open the Folder
        Folder folder = store.getDefaultFolder();
        folder = folder.getFolder("INBOX");

        if (folder == null) {
            throw new RuntimeException("Invalid folder INBOX");
        }

        // try to open read/write and if that fails try read-only
        try {
            folder.open(Folder.READ_WRITE);
        } catch (MessagingException ex) {
            folder.open(Folder.READ_ONLY);
        }

        int count = folder.getMessageCount();
        // Message numbers start at 1
        for (int i = 1; i <= count; i++) {
            // Get a message by its sequence number
            Message m = folder.getMessage(i);
            Address[] from = m.getFrom();
            String type = from[0].getType();

            IMessage message = new MailMessage(from[0].toString(), this, m.getSubject(), getContent(m));

            result.add(message);

            // delete message ?
            if (clear)
                m.setFlag(Flags.Flag.DELETED, true);
        }

        // "true" actually deletes flagged messages from folder
        folder.close(clear);
        store.close();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return result;
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private List<EmailMessage> getEmailMessages(Folder mailFolder, int pageStart, int messageCount, Session session)
        throws MessagingException, IOException, ScanException, PolicyException {

    int totalMessageCount = mailFolder.getMessageCount();
    int start = Math.max(1, totalMessageCount - pageStart - (messageCount - 1));
    int end = Math.max(totalMessageCount - pageStart, 1);

    Message[] messages = totalMessageCount != 0 ? mailFolder.getMessages(start, end) : new Message[0];

    long startTime = System.currentTimeMillis();

    // Fetch only necessary headers for each message
    FetchProfile profile = new FetchProfile();
    profile.add(FetchProfile.Item.ENVELOPE);
    profile.add(FetchProfile.Item.FLAGS);
    profile.add(FetchProfile.Item.CONTENT_INFO);
    if (mailFolder instanceof UIDFolder) {
        profile.add(UIDFolder.FetchProfileItem.UID);
    }//from  w w w.ja  v a  2 s  .c  o  m
    mailFolder.fetch(messages, profile);

    if (log.isDebugEnabled()) {
        log.debug("Time elapsed while fetching message headers; {}ms", System.currentTimeMillis() - startTime);
    }

    List<EmailMessage> emails = new LinkedList<EmailMessage>();
    for (Message currentMessage : messages) {
        EmailMessage emailMessage = wrapMessage(currentMessage, false, session);
        emails.add(emailMessage);
    }

    Collections.reverse(emails);
    return emails;
}

From source file:org.jasig.portlet.emailpreview.dao.javamail.JavamailAccountDaoImpl.java

private EmailQuota getQuota(Folder folder) {
    if (!(folder instanceof IMAPFolder)) {
        return null;
    }/*www . jav  a 2  s.  c  o  m*/
    try {
        // Make sure the account is activated and contains messages
        if (folder.exists() && folder.getMessageCount() > 0) {
            Quota[] quotas = ((IMAPFolder) folder).getQuota();

            for (Quota quota : quotas) {
                for (Quota.Resource resource : quota.resources) {
                    if (resource.name.equals("STORAGE")) {
                        return new EmailQuota(resource.limit, resource.usage);
                    }
                }
            }
        }
    } catch (MessagingException e) {
        log.error("Failed to connect or get quota for mail user ");
    }
    return null;
}

From source file:org.apache.jmeter.protocol.mail.sampler.MailReaderSampler.java

/**
 * {@inheritDoc}/* w ww  .j  a  v  a 2s  .  co m*/
 */
@Override
public SampleResult sample(Entry e) {
    SampleResult parent = new SampleResult();
    boolean isOK = false; // Did sample succeed?
    final boolean deleteMessages = getDeleteMessages();
    final String serverProtocol = getServerType();

    parent.setSampleLabel(getName());

    String samplerString = toString();
    parent.setSamplerData(samplerString);

    /*
     * Perform the sampling
     */
    parent.sampleStart(); // Start timing
    try {
        // Create empty properties
        Properties props = new Properties();

        if (isUseStartTLS()) {
            props.setProperty(mailProp(serverProtocol, "starttls.enable"), TRUE); // $NON-NLS-1$
            if (isEnforceStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.setProperty(mailProp(serverProtocol, "starttls.require"), TRUE); // $NON-NLS-1$
            }
        }

        if (isTrustAllCerts()) {
            if (isUseSSL()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.class"),
                        TRUST_ALL_SOCKET_FACTORY); // $NON-NLS-1$
                props.setProperty(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        } else if (isUseLocalTrustStore()) {
            File truststore = new File(getTrustStoreToUse());
            log.info("load local truststore - try to load truststore from: " + truststore.getAbsolutePath());
            if (!truststore.exists()) {
                log.info("load local truststore -Failed to load truststore from: "
                        + truststore.getAbsolutePath());
                truststore = new File(FileServer.getFileServer().getBaseDir(), getTrustStoreToUse());
                log.info("load local truststore -Attempting to read truststore from:  "
                        + truststore.getAbsolutePath());
                if (!truststore.exists()) {
                    log.info("load local truststore -Failed to load truststore from: "
                            + truststore.getAbsolutePath()
                            + ". Local truststore not available, aborting execution.");
                    throw new IOException("Local truststore file not found. Also not available under : "
                            + truststore.getAbsolutePath());
                }
            }
            if (isUseSSL()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$ 
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            } else if (isUseStartTLS()) {
                // Requires JavaMail 1.4.2+
                props.put(mailProp(serverProtocol, "ssl.socketFactory"), // $NON-NLS-1$
                        new LocalTrustStoreSSLSocketFactory(truststore));
                props.put(mailProp(serverProtocol, "ssl.socketFactory.fallback"), FALSE); // $NON-NLS-1$
            }
        }

        // Get session
        Session session = Session.getInstance(props, null);

        // Get the store
        Store store = session.getStore(serverProtocol);
        store.connect(getServer(), getPortAsInt(), getUserName(), getPassword());

        // Get folder
        Folder folder = store.getFolder(getFolder());
        if (deleteMessages) {
            folder.open(Folder.READ_WRITE);
        } else {
            folder.open(Folder.READ_ONLY);
        }

        final int messageTotal = folder.getMessageCount();
        int n = getNumMessages();
        if (n == ALL_MESSAGES || n > messageTotal) {
            n = messageTotal;
        }

        // Get directory
        Message[] messages = folder.getMessages(1, n);
        StringBuilder pdata = new StringBuilder();
        pdata.append(messages.length);
        pdata.append(" messages found\n");
        parent.setResponseData(pdata.toString(), null);
        parent.setDataType(SampleResult.TEXT);
        parent.setContentType("text/plain"); // $NON-NLS-1$

        final boolean headerOnly = getHeaderOnly();
        busy = true;
        for (Message message : messages) {
            StringBuilder cdata = new StringBuilder();
            SampleResult child = new SampleResult();
            child.sampleStart();

            cdata.append("Message "); // $NON-NLS-1$
            cdata.append(message.getMessageNumber());
            child.setSampleLabel(cdata.toString());
            child.setSamplerData(cdata.toString());
            cdata.setLength(0);

            final String contentType = message.getContentType();
            child.setContentType(contentType);// Store the content-type
            child.setDataEncoding(RFC_822_DEFAULT_ENCODING); // RFC 822 uses ascii per default
            child.setEncodingAndType(contentType);// Parse the content-type

            if (isStoreMimeMessage()) {
                // Don't save headers - they are already in the raw message
                ByteArrayOutputStream bout = new ByteArrayOutputStream();
                message.writeTo(bout);
                child.setResponseData(bout.toByteArray()); // Save raw message
                child.setDataType(SampleResult.TEXT);
            } else {
                @SuppressWarnings("unchecked") // Javadoc for the API says this is OK
                Enumeration<Header> hdrs = message.getAllHeaders();
                while (hdrs.hasMoreElements()) {
                    Header hdr = hdrs.nextElement();
                    String value = hdr.getValue();
                    try {
                        value = MimeUtility.decodeText(value);
                    } catch (UnsupportedEncodingException uce) {
                        // ignored
                    }
                    cdata.append(hdr.getName()).append(": ").append(value).append("\n");
                }
                child.setResponseHeaders(cdata.toString());
                cdata.setLength(0);
                if (!headerOnly) {
                    appendMessageData(child, message);
                }
            }

            if (deleteMessages) {
                message.setFlag(Flags.Flag.DELETED, true);
            }
            child.setResponseOK();
            if (child.getEndTime() == 0) {// Avoid double-call if addSubResult was called.
                child.sampleEnd();
            }
            parent.addSubResult(child);
        }

        // Close connection
        folder.close(true);
        store.close();

        parent.setResponseCodeOK();
        parent.setResponseMessageOK();
        isOK = true;
    } catch (NoClassDefFoundError | IOException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString());
    } catch (MessagingException ex) {
        log.debug("", ex);// No need to log normally, as we set the status
        parent.setResponseCode("500"); // $NON-NLS-1$
        parent.setResponseMessage(ex.toString() + "\n" + samplerString); // $NON-NLS-1$
    } finally {
        busy = false;
    }

    if (parent.getEndTime() == 0) {// not been set by any child samples
        parent.sampleEnd();
    }
    parent.setSuccessful(isOK);
    return parent;
}

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

public boolean hasNewMessages(long folderId) throws PortalException {
    Folder jxFolder = null;

    try {//www  .  j  av  a 2  s  .c  o  m
        jxFolder = openFolder(folderId);

        int messageCount = jxFolder.getMessageCount();

        Message jxMessage = getMessage(folderId, jxFolder, false);

        if (jxMessage == null) {
            if (messageCount <= 0) {
                return false;
            }

            return true;
        }

        if (messageCount == jxMessage.getMessageNumber()) {
            return false;
        }

        return true;
    } catch (MessagingException me) {
        throw new MailException(me);
    } finally {
        closeFolder(jxFolder, false);
    }
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void fetch(final Folder folder) throws MessagingException, IOException {

    if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) {
        logger.warn("Folder {} cannot hold messages", folder.getFullName());
        return;//w w w  . j  a  va  2s . c  om

    }

    final int messageCount = folder.getMessageCount();

    final UIDFolder uidfolder = (UIDFolder) folder;
    final long servervalidity = uidfolder.getUIDValidity();
    final RiverState riverState = stateManager.getRiverState(folder);
    final Long localvalidity = riverState.getUidValidity();

    logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount);

    logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity);

    if (localvalidity == null || localvalidity.longValue() != servervalidity) {

        logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity);

        if (localvalidity != null) {
            mailDestination.clearDataForFolder(folder.getFullName());
        }

        final ProcessResult result = process(messageCount, 1, folder.getFullName());

        riverState.setLastCount(result.getProcessedCount());

        if (result.getProcessedCount() > 0) {
            riverState.setLastIndexed(new Date());
        }

        if (result.getProcessedCount() > 0) {
            riverState.setLastTook(result.getTook());
        }

        riverState.setLastSchedule(new Date());

        if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
            riverState.setLastUid(result.getHighestUid());
        }

        riverState.setUidValidity(servervalidity);
        stateManager.setRiverState(riverState);

        logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(),
                folder.getFullName());
        logger.debug("Processed result {}", result.toString());

    } else {

        if (messageCount == 0) {
            logger.debug("Folder {} is empty", folder.getFullName());
        } else {

            if (withFlagSync) {
                // detect flag change
                final Message[] flagMessages = folder.getMessages();
                folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID);

                for (final Message message : flagMessages) {
                    try {

                        final long uid = ((UIDFolder) message.getFolder()).getUID(message);

                        final String id = uid + "::" + message.getFolder().getURLName();

                        final int storedHashcode = mailDestination.getFlaghashcode(id);

                        if (storedHashcode == -1) {
                            // New mail which is not indexed yet
                            continue;
                        }

                        final int flagHashcode = message.getFlags().hashCode();

                        if (flagHashcode != storedHashcode) {
                            // flags change for this message, must update
                            mailDestination.onMessage(message);

                            if (logger.isDebugEnabled()) {
                                logger.debug("Update " + id + " because of flag change");
                            }
                        }
                    } catch (final Exception e) {
                        logger.error("Error detecting flagchanges for message "
                                + ((MimeMessage) message).getMessageID(), e);
                        stateManager.onError("Error detecting flagchanges", message, e);
                    }
                }
            }

            final long highestUID = riverState.getLastUid(); // this uid is
                                                             // already
                                                             // processed

            logger.debug("highestUID: {}", highestUID);

            final Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID);

            // msgnew.size is always >= 1
            if (highestUID > 0 && uidfolder.getUID(msgsnew[0]) <= highestUID) {
                // msgsnew = (Message[]) ArrayUtils.remove(msgsnew, 0);
            }

            if (msgsnew.length > 0) {

                logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName());

                final int start = msgsnew[0].getMessageNumber();

                final ProcessResult result = process(messageCount, start, folder.getFullName());

                riverState.setLastCount(result.getProcessedCount());

                if (result.getProcessedCount() > 0) {
                    riverState.setLastIndexed(new Date());
                }

                if (result.getProcessedCount() > 0) {
                    riverState.setLastTook(result.getTook());
                }

                riverState.setLastSchedule(new Date());

                if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
                    riverState.setLastUid(result.getHighestUid());
                }

                riverState.setUidValidity(servervalidity);
                stateManager.setRiverState(riverState);

                logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(),
                        folder.getFullName());
                logger.debug("Processed result {}", result.toString());
            } else {
                logger.debug("no new messages");
            }

        }
        // check for expunged/deleted messages

        final Set<Long> serverMailSet = new HashSet<Long>();

        final long oldmailUid = riverState.getLastUid();
        logger.debug("oldmailuid {}", oldmailUid);

        final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid);

        folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID);

        for (final Message m : msgsold) {
            try {
                final long uid = uidfolder.getUID(m);
                serverMailSet.add(uid);

            } catch (final Exception e) {
                stateManager.onError("Unable to handle old message ", m, e);
                logger.error("Unable to handle old message due to {}", e, e.toString());

                IMAPUtils.open(folder);
            }
        }

        final Set localMailSet = new HashSet(
                mailDestination.getCurrentlyStoredMessageUids(folder.getFullName(), false));

        logger.debug("Check now " + localMailSet.size() + " server mails for expunge");

        localMailSet.removeAll(serverMailSet);
        // localMailSet has now the ones that are not on server

        logger.info(
                localMailSet.size() + " messages were locally deleted, because they are expunged on server.");

        mailDestination.onMessageDeletes(localMailSet, folder.getFullName(), false);

    }

}

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

public long[] getMessageUIDs(long folderId, int pageNumber, int messagesPerPage) throws PortalException {

    Folder jxFolder = null;

    try {//from  w  w w .j a v  a  2 s. c  o  m
        jxFolder = openFolder(folderId);

        int[] messageIndexes = getMessageIndexes(jxFolder.getMessageCount(), pageNumber, messagesPerPage);

        if (messageIndexes[0] == 0) {
            return new long[0];
        }

        Message[] jxMessages = jxFolder.getMessages(messageIndexes[0], messageIndexes[1]);

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

From source file:com.robin.utilities.Utilities.java

/**
 * A utility that waits for a gmail mailbox to receive a new message with
 * according to a given SearchTerm. Only "Not seen" messages are searched,
 * and all match is set as SEEN, but just the first occurrence of the
 * matching message is returned./* ww  w .  j  a va2  s  . com*/
 * @param username the mailbox owner's user name (no @gmail.com required).
 * @param pass the user password protecting this mailbox
 * @param st the SearchTerm built to filter messages
 * @param timeoutMessage the message to show when no such mail found within
 *            timeout
 * @param timeout The maximum amount of time to wait in milliseconds.
 * @return a last from the new messages thats match the st conditions
 */
public EMail waitForMailWithSearchTerm(final String username, final String pass, final SearchTerm st,
        final String timeoutMessage, final long timeout) {
    String host = "imap.gmail.com";
    final long retryTime = 1000;

    Properties props = System.getProperties();
    props.setProperty("mail.store.protocol", "imaps");
    props.put("mail.imaps.ssl.trust", "*");
    EMail email = null;
    Session session = Session.getDefaultInstance(props, null);
    try {
        Store store = session.getStore("imaps");
        store.connect(host, username, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_WRITE);
        FluentWait<Folder> waitForMail = new FluentWait<Folder>(inbox)
                .withTimeout(timeout, TimeUnit.MILLISECONDS).pollingEvery(retryTime, TimeUnit.MILLISECONDS)
                .withMessage(timeoutMessage);
        email = waitForMail.until(new Function<Folder, EMail>() {
            @Override
            public EMail apply(final Folder inbox) {
                EMail email = null;
                FlagTerm ft = new FlagTerm(new Flags(Flags.Flag.SEEN), false);
                SearchTerm sst = new AndTerm(ft, st);
                try {
                    inbox.getMessageCount();
                    Message[] messages = inbox.search(sst);
                    for (Message message : messages) {
                        message.setFlag(Flag.SEEN, true);
                    }
                    if (messages.length > 0) {
                        return new EMail(messages[0]);
                    }
                } catch (MessagingException e) {
                    Assert.fail(e.getMessage());
                }
                return email;
            }
        });
        inbox.close(false);
        store.close();
    } catch (MessagingException e) {
        Assert.fail(e.getMessage());
    }
    return email;
}

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

@SuppressWarnings({ "rawtypes", "unchecked" })
protected void fetch(final Folder folder) throws MessagingException, IOException {

    if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) {
        logger.warn("Folder {} cannot hold messages", folder.getFullName());
        return;//from w w  w . j ava  2  s  . c  o  m

    }

    final int messageCount = folder.getMessageCount();

    final UIDFolder uidfolder = (UIDFolder) folder;
    final long servervalidity = uidfolder.getUIDValidity();
    final State riverState = stateManager.getRiverState(folder);
    final Long localvalidity = riverState.getUidValidity();

    logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount);

    logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity);

    if (localvalidity == null || localvalidity.longValue() != servervalidity) {
        logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity);

        if (localvalidity != null) {
            mailDestination.clearDataForFolder(folder);
        }

        final ProcessResult result = process(messageCount, 1, folder.getFullName());

        riverState.setLastCount(result.getProcessedCount());

        if (result.getProcessedCount() > 0) {
            riverState.setLastIndexed(new Date());
        }

        if (result.getProcessedCount() > 0) {
            riverState.setLastTook(result.getTook());
        }

        riverState.setLastSchedule(new Date());

        if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
            riverState.setLastUid(result.getHighestUid());
        }

        riverState.setUidValidity(servervalidity);
        stateManager.setRiverState(riverState);

        logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(),
                folder.getFullName());
        logger.debug("Processed result {}", result.toString());

    } else {

        if (messageCount == 0) {
            logger.debug("Folder {} is empty", folder.getFullName());
        } else {

            if (withFlagSync) {
                // detect flag change
                final Message[] flagMessages = folder.getMessages();
                folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID);

                for (final Message message : flagMessages) {
                    try {

                        final long uid = ((UIDFolder) message.getFolder()).getUID(message);

                        final String id = uid + "::" + message.getFolder().getURLName();

                        final int storedHashcode = mailDestination.getFlaghashcode(id);

                        if (storedHashcode == -1) {
                            // New mail which is not indexed yet
                            continue;
                        }

                        final int flagHashcode = message.getFlags().hashCode();

                        if (flagHashcode != storedHashcode) {
                            // flags change for this message, must update
                            mailDestination.onMessage(message);

                            if (logger.isDebugEnabled()) {
                                logger.debug("Update " + id + " because of flag change");
                            }
                        }
                    } catch (final Exception e) {
                        logger.error("Error detecting flagchanges for message "
                                + ((MimeMessage) message).getMessageID(), e);
                        stateManager.onError("Error detecting flagchanges", message, e);
                    }
                }
            }

            long highestUID = riverState.getLastUid(); // this uid is
                                                       // already
                                                       // processed

            logger.debug("highestUID: {}", highestUID);

            if (highestUID < 1) {
                logger.error("highestUID: {} not valid, set it to 1", highestUID);
                highestUID = 1;
            }

            Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID);

            if (msgsnew.length > 0) {

                System.out.println("lastuid: " + uidfolder.getUID(msgsnew[msgsnew.length - 1]));

                // msgnew.size is always >= 1
                if (highestUID > 1 && uidfolder.getUID(msgsnew[msgsnew.length - 1]) <= highestUID) {
                    msgsnew = (Message[]) ArrayUtils.remove(msgsnew, msgsnew.length - 1);
                }

                if (msgsnew.length > 0) {

                    logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName());

                    final int start = msgsnew[0].getMessageNumber();

                    final ProcessResult result = process(messageCount, start, folder.getFullName());

                    riverState.setLastCount(result.getProcessedCount());

                    if (result.getProcessedCount() > 0) {
                        riverState.setLastIndexed(new Date());
                    }

                    if (result.getProcessedCount() > 0) {
                        riverState.setLastTook(result.getTook());
                    }

                    riverState.setLastSchedule(new Date());

                    if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) {
                        riverState.setLastUid(result.getHighestUid());
                    }

                    riverState.setUidValidity(servervalidity);
                    stateManager.setRiverState(riverState);

                    logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(),
                            folder.getFullName());
                    logger.debug("Processed result {}", result.toString());
                } else {
                    logger.debug("no new messages");
                }
            } else {
                logger.debug("no new messages");
            }

        }
        // check for expunged/deleted messages
        final Set<Long> serverMailSet = new HashSet<Long>();

        final long oldmailUid = riverState.getLastUid();
        logger.debug("oldmailuid {}", oldmailUid);

        final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid);

        folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID);

        for (final Message m : msgsold) {
            try {
                final long uid = uidfolder.getUID(m);
                serverMailSet.add(uid);

            } catch (final Exception e) {
                stateManager.onError("Unable to handle old message ", m, e);
                logger.error("Unable to handle old message due to {}", e, e.toString());

                IMAPUtils.open(folder);
            }
        }

        if (deleteExpungedMessages) {

            final Set localMailSet = new HashSet(mailDestination.getCurrentlyStoredMessageUids(folder));

            logger.debug("Check now " + localMailSet.size() + " server mails for expunge");

            localMailSet.removeAll(serverMailSet);
            // localMailSet has now the ones that are not on server             

            logger.info(localMailSet.size()
                    + " messages were locally deleted, because they are expunged on server.");

            mailDestination.onMessageDeletes(localMailSet, folder);

        }

    }

}

From source file:com.naryx.tagfusion.cfm.mail.cfPOP3.java

private void readMessages(cfSession _Session, Folder popFolder, cfQueryResultData popData, int _start, int _max,
        boolean GetAll, File attachmentDir) throws cfmRunTimeException {
    try {//w w w .jav a2s.c o  m
        int maxRows = _max;
        int startRow = _start;
        String messageNumber = getDynamic(_Session, "MESSAGENUMBER").getString();
        boolean containsUID = containsAttribute("UID");
        boolean usingMessageNumber = messageNumber.length() > 0;
        int msgCount = popFolder.getMessageCount();

        // if MAXROWS is not specified, or UID or MESSAGENUMBER is, then we want to get all the messages
        if (_max == -1 || containsUID || usingMessageNumber) {
            maxRows = msgCount;
        }
        if (containsUID || usingMessageNumber) {
            startRow = 1;
        }

        if (msgCount != 0 && startRow > msgCount) {
            throw newRunTimeException(
                    "The value of STARTROW must not be greater than the total number of messages in the folder, "
                            + popFolder.getMessageCount() + ".");
        }

        Message[] listOfMessages;
        if (!usingMessageNumber) {
            listOfMessages = popFolder.getMessages();
        } else {
            listOfMessages = popFolder.getMessages(getMessageList(messageNumber));
        }

        FetchProfile fProfile = new FetchProfile();
        fProfile.add(FetchProfile.Item.ENVELOPE);
        fProfile.add(UIDFolder.FetchProfileItem.UID);
        popFolder.fetch(listOfMessages, fProfile);

        if (containsUID) {
            String[] messageUIDList = getMessageUIDList(getDynamic(_Session, "UID").getString());

            for (int x = 0; x < listOfMessages.length; x++) {
                if (messageUIDList.length == 0
                        || messageUIDValid(messageUIDList, getMessageUID(popFolder, listOfMessages[x]))) {
                    populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
                }
            }
        } else {
            popFolder.fetch(listOfMessages, fProfile);
            int end = startRow - 1 + maxRows;
            if (end > listOfMessages.length) {
                end = listOfMessages.length;
            }
            for (int x = startRow - 1; x < end; x++) {
                populateMessage(_Session, listOfMessages[x], popData, GetAll, attachmentDir, popFolder);
            }
        }
    } catch (Exception E) {
        if (E.getMessage() != null)
            throw newRunTimeException(E.getMessage());
        else
            throw newRunTimeException(E.toString());
    }

}