Example usage for javax.mail Folder getStore

List of usage examples for javax.mail Folder getStore

Introduction

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

Prototype

public Store getStore() 

Source Link

Document

Returns the Store that owns this Folder object.

Usage

From source file:populate.java

public static void main(String argv[]) {
    String srcURL = null;//from w w  w.  j  av a2s .c o  m
    String dstURL = null;
    boolean debug = false;

    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-s")) {
            srcURL = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            dstURL = argv[++optind];
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            force = true;
        } else if (argv[optind].equals("-S")) {
            skipSpecial = true;
        } else if (argv[optind].equals("-c")) {
            clear = true;
        } else if (argv[optind].equals("-P")) {
            dontPreserveFlags = true;
        } else if (argv[optind].equals("-W")) {
            warn = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            printUsage();
            System.exit(1);
        } else {
            break;
        }
    }

    try {

        if (srcURL == null || dstURL == null) {
            printUsage();
            System.exit(1);
        }

        Session session = Session.getInstance(System.getProperties(), null);
        session.setDebug(debug);

        // Get source folder
        URLName srcURLName = new URLName(srcURL);
        Folder srcFolder;
        // Check if the source URL has a folder specified. If
        // not, we use the default folder
        if (srcURLName.getFile() == null) {
            Store s = session.getStore(srcURLName);
            s.connect();
            srcFolder = s.getDefaultFolder();
        } else {
            srcFolder = session.getFolder(new URLName(srcURL));
            if (!srcFolder.exists()) {
                System.out.println("source folder does not exist");
                srcFolder.getStore().close();
                System.exit(1);
            }
        }

        // Set up destination folder
        URLName dstURLName = new URLName(dstURL);
        Folder dstFolder;
        // Check if the destination URL has a folder specified. If
        // not, we use the source folder name
        if (dstURLName.getFile() == null) {
            Store s = session.getStore(dstURLName);
            s.connect();
            dstFolder = s.getFolder(srcFolder.getName());
        } else
            dstFolder = session.getFolder(dstURLName);

        if (clear && dstFolder.exists()) {
            if (!dstFolder.delete(true)) {
                System.out.println("couldn't delete " + dstFolder.getFullName());
                return;
            }
        }
        copy(srcFolder, dstFolder);

        // Close the respective stores.
        srcFolder.getStore().close();
        dstFolder.getStore().close();

    } catch (MessagingException mex) {
        System.out.println(mex.getMessage());
        mex.printStackTrace();
    }
}

From source file:populate.java

public static void main(String argv[]) {
    String srcURL = null;/*from  ww w.  j a va2s  . c  o m*/
    String dstURL = null;
    boolean debug = false;

    int optind;

    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-s")) {
            srcURL = argv[++optind];
        } else if (argv[optind].equals("-d")) {
            dstURL = argv[++optind];
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("-f")) {
            force = true;
        } else if (argv[optind].equals("-S")) {
            skipSpecial = true;
        } else if (argv[optind].equals("-c")) {
            clear = true;
        } else if (argv[optind].equals("-P")) {
            dontPreserveFlags = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            printUsage();
            System.exit(1);
        } else {
            break;
        }
    }

    try {

        if (srcURL == null || dstURL == null) {
            printUsage();
            System.exit(1);
        }

        Session session = Session.getInstance(System.getProperties(), null);
        session.setDebug(debug);

        // Get source folder
        URLName srcURLName = new URLName(srcURL);
        Folder srcFolder;
        // Check if the source URL has a folder specified. If
        // not, we use the default folder
        if (srcURLName.getFile() == null) {
            Store s = session.getStore(srcURLName);
            s.connect();
            srcFolder = s.getDefaultFolder();
        } else {
            srcFolder = session.getFolder(new URLName(srcURL));
            if (!srcFolder.exists()) {
                System.out.println("source folder does not exist");
                srcFolder.getStore().close();
                System.exit(1);
            }
        }

        // Set up destination folder
        URLName dstURLName = new URLName(dstURL);
        Folder dstFolder;
        // Check if the destination URL has a folder specified. If
        // not, we use the source folder name
        if (dstURLName.getFile() == null) {
            Store s = session.getStore(dstURLName);
            s.connect();
            dstFolder = s.getFolder(srcFolder.getName());
        } else
            dstFolder = session.getFolder(dstURLName);

        if (clear && dstFolder.exists()) {
            if (!dstFolder.delete(true)) {
                System.out.println("couldn't delete " + dstFolder.getFullName());
                return;
            }
        }
        copy(srcFolder, dstFolder);

        // Close the respective stores.
        srcFolder.getStore().close();
        dstFolder.getStore().close();

    } catch (MessagingException mex) {
        System.out.println(mex.getMessage());
        mex.printStackTrace();
    }
}

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

@Override
public boolean deleteMessages(MailStoreConfiguration config, String[] uuids) {
    Authenticator auth = credentialsProvider.getAuthenticator();
    Folder inbox = null;
    try {/* www.j  a  v a 2  s .c om*/

        // Retrieve user's inbox
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, config.getInboxFolderName());

        // Verify that we can even perform this operation
        if (!(inbox instanceof UIDFolder)) {
            String msg = "Delete feature is supported only for UIDFolder instances";
            throw new UnsupportedOperationException(msg);
        }

        inbox.open(Folder.READ_WRITE);

        Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids));
        inbox.setFlags(msgs, new Flags(Flag.DELETED), true);

        return true; // Indicate success

    } catch (MessagingException e) {
        log.error("Messaging exception while deleting messages", e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }

    return false; // We failed if we reached this point
}

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

@Override
public boolean setMessageReadStatus(MailStoreConfiguration config, String[] uuids, boolean read) {
    Authenticator auth = credentialsProvider.getAuthenticator();
    Folder inbox = null;
    try {/* w  w w .  jav a 2 s . co m*/
        // Retrieve user's inbox
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, config.getInboxFolderName());

        // Verify that we can even perform this operation log info if it isn't capable of operation
        if (!(inbox instanceof UIDFolder)) {
            String msg = "Toggle unread feature is supported only for UIDFolder instances";
            log.info(msg);
            return false;
        }

        inbox.open(Folder.READ_WRITE);

        Message[] msgs = ((UIDFolder) inbox).getMessagesByUID(getMessageUidsAsLong(uuids));
        inbox.setFlags(msgs, new Flags(Flag.SEEN), read);

        return true; // Indicate success

    } catch (MessagingException e) {
        log.error("Messaging exception while deleting messages", e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }

    return false; // We failed if we reached this point
}

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

@Override
public EmailMessage getMessage(MailStoreConfiguration config, String messageId) {
    Authenticator auth = credentialsProvider.getAuthenticator();
    Folder inbox = null;
    try {/*from ww  w  .j a v a2  s.  c  o  m*/
        int mode = config.getMarkMessagesAsRead() ? Folder.READ_WRITE : Folder.READ_ONLY;

        // Retrieve user's inbox
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, config.getInboxFolderName());
        inbox.open(mode);

        Message message;
        if (inbox instanceof UIDFolder) {
            message = ((UIDFolder) inbox).getMessageByUID(Long.parseLong(messageId));
        } else {
            message = inbox.getMessage(Integer.parseInt(messageId));
        }
        boolean unread = !message.isSet(Flags.Flag.SEEN);
        if (config.getMarkMessagesAsRead()) {
            message.setFlag(Flag.SEEN, true);
        }
        EmailMessage emailMessage = wrapMessage(message, true, session);
        if (!config.getMarkMessagesAsRead()) {
            // NOTE:  This is more than a little bit annoying.  Apparently
            // the mere act of accessing the body content of a message in
            // Javamail flags the in-memory representation of that message
            // as SEEN.  It does *nothing* to the mail server (the message
            // is still unread in the SOR), but it wreaks havoc on local
            // functions that key off that value and expect it to be
            // accurate.  We're obligated, therefore, to restore the value
            // to what it was before the call to wrapMessage().
            emailMessage.setUnread(unread);
        }

        return emailMessage;
    } catch (MessagingException e) {
        log.error("Messaging exception while retrieving individual message", e);
    } catch (IOException e) {
        log.error("IO exception while retrieving individual message", e);
    } catch (ScanException e) {
        log.error("AntiSamy scanning exception while retrieving individual message", e);
    } catch (PolicyException e) {
        log.error("AntiSamy policy exception while retrieving individual message", e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }

    return null;
}

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

@Override
public AccountSummary fetchAccountSummaryFromStore(MailStoreConfiguration config, String username,
        String mailAccount, String folder, int start, int max) {

    Authenticator auth = credentialsProvider.getAuthenticator();

    AccountSummary summary;/*from   w w w  .  ja v a  2 s.c o  m*/
    Folder inbox = null;
    try {

        // Retrieve user's folder
        Session session = openMailSession(config, auth);
        inbox = getUserInbox(session, folder);
        inbox.open(Folder.READ_ONLY);
        long startTime = System.currentTimeMillis();
        List<EmailMessage> messages = getEmailMessages(inbox, start, max, session);

        if (log.isDebugEnabled()) {
            long elapsedTime = System.currentTimeMillis() - startTime;
            int messagesToDisplayCount = messages.size();
            log.debug("Finished looking up email messages. Inbox size: " + inbox.getMessageCount()
                    + " Unread message count: " + inbox.getUnreadMessageCount() + " Total elapsed time: "
                    + elapsedTime + "ms " + " Time per message in inbox: "
                    + (inbox.getMessageCount() == 0 ? 0 : (elapsedTime / inbox.getMessageCount())) + "ms"
                    + " Time per displayed message: "
                    + (messagesToDisplayCount == 0 ? 0 : (elapsedTime / messagesToDisplayCount)) + "ms");
        }

        IEmailLinkService linkService = linkServiceRegistry.getEmailLinkService(config.getLinkServiceKey());
        String inboxUrl = null;
        if (linkService != null) {
            inboxUrl = linkService.getInboxUrl(config);
        }

        // Initialize account information with information retrieved from inbox
        summary = new AccountSummary(inboxUrl, messages, inbox.getUnreadMessageCount(), inbox.getMessageCount(),
                start, max, isDeleteSupported(inbox), getQuota(inbox));

        if (log.isDebugEnabled()) {
            log.debug("Successfully retrieved email AccountSummary");
        }

        return summary;

    } catch (MailAuthenticationException mae) {
        // We used just to allow this exception to percolate up the chain,
        // but we learned that the entire stack trace gets written to
        // Catalina.out (by 3rd party code).  Since this is a common
        // occurrence, it causes space issues.
        return new AccountSummary(mae);
    } catch (MessagingException me) {
        log.error("Exception encountered while retrieving account info", me);
        throw new EmailPreviewException(me);
    } catch (IOException e) {
        log.error("Exception encountered while retrieving account info", e);
        throw new EmailPreviewException(e);
    } catch (ScanException e) {
        log.error("Exception encountered while retrieving account info", e);
        throw new EmailPreviewException(e);
    } catch (PolicyException e) {
        log.error("Exception encountered while retrieving account info", e);
        throw new EmailPreviewException(e);
    } finally {
        if (inbox != null) {
            try {
                inbox.close(false);
            } catch (Exception e) {
                log.warn("Can't close correctly javamail inbox connection");
            }
            try {
                inbox.getStore().close();
            } catch (Exception e) {
                log.warn("Can't close correctly javamail store connection");
            }
        }
    }
}