Example usage for javax.mail Folder HOLDS_FOLDERS

List of usage examples for javax.mail Folder HOLDS_FOLDERS

Introduction

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

Prototype

int HOLDS_FOLDERS

To view the source code for javax.mail Folder HOLDS_FOLDERS.

Click Source Link

Document

This folder can contain other folders

Usage

From source file:folderlist.java

public static void main(String argv[]) throws Exception {
    int optind;/*from  w w  w .jav  a 2  s  .c o  m*/
    for (optind = 0; optind < argv.length; optind++) {
        if (argv[optind].equals("-T")) {
            protocol = argv[++optind];
        } else if (argv[optind].equals("-H")) {
            host = argv[++optind];
        } else if (argv[optind].equals("-U")) {
            user = argv[++optind];
        } else if (argv[optind].equals("-P")) {
            password = argv[++optind];
        } else if (argv[optind].equals("-L")) {
            url = argv[++optind];
        } else if (argv[optind].equals("-R")) {
            root = argv[++optind];
        } else if (argv[optind].equals("-r")) {
            recursive = true;
        } else if (argv[optind].equals("-v")) {
            verbose = true;
        } else if (argv[optind].equals("-D")) {
            debug = true;
        } else if (argv[optind].equals("--")) {
            optind++;
            break;
        } else if (argv[optind].startsWith("-")) {
            System.out.println("Usage: folderlist [-T protocol] [-H host] [-U user] [-P password] [-L url]");
            System.out.println("\t[-R root] [-r] [-v] [-D] [pattern]");
            System.exit(1);
        } else {
            break;
        }
    }
    if (optind < argv.length)
        pattern = argv[optind];

    // Get a Properties object
    Properties props = System.getProperties();

    // Get a Session object
    Session session = Session.getInstance(props, null);
    session.setDebug(debug);

    // Get a Store object
    Store store = null;
    Folder rf = null;
    if (url != null) {
        URLName urln = new URLName(url);
        store = session.getStore(urln);
        store.connect();
    } else {
        if (protocol != null)
            store = session.getStore(protocol);
        else
            store = session.getStore();

        // Connect
        if (host != null || user != null || password != null)
            store.connect(host, user, password);
        else
            store.connect();
    }

    // List namespace
    if (root != null)
        rf = store.getFolder(root);
    else
        rf = store.getDefaultFolder();

    dumpFolder(rf, false, "");
    if ((rf.getType() & Folder.HOLDS_FOLDERS) != 0) {
        Folder[] f = rf.list(pattern);
        for (int i = 0; i < f.length; i++)
            dumpFolder(f[i], recursive, "    ");
    }

    store.close();
}

From source file:FolderTreeNode.java

/**
 * a Folder is a leaf if it cannot contain sub folders
 *//*from  w w  w  .  j a v  a2s  .com*/
public boolean isLeaf() {
    try {
        if ((folder.getType() & Folder.HOLDS_FOLDERS) == 0)
            return true;
    } catch (MessagingException me) {
    }

    // otherwise it does hold folders, and therefore not
    // a leaf
    return false;
}

From source file:br.unicamp.cotuca.dpd.pd12.acinet.vagalmail.servlet.Configuracoes.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");
    request.setCharacterEncoding("UTF-8");

    if (request.getRequestURI().contains("/pasta")) {
        String acao = request.getParameter("acao"), url = request.getParameter("url"),
                novo = request.getParameter("novo");

        JSONObject obj = new JSONObject();
        if (acao == null || url == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }// www.jav  a2 s .  c  o m

        if ((acao.equals("renomear") || acao.equals("nova")) && novo == null) {
            obj.put("erro", "Solicitao invlida");
            obj.writeJSONString(response.getWriter());
            return;
        }

        try {
            Conta conta = (Conta) request.getSession().getAttribute("conta");
            Store store = Logar.getImapStore(conta);

            Folder pasta = null;

            if (!acao.equals("nova")) {
                URLName urln = new URLName(url);
                pasta = store.getFolder(urln);

                if (pasta.isOpen())
                    pasta.close(false);
            }

            switch (acao) {
            case "renomear":
                if (pasta.renameTo(store.getFolder(novo))) {
                    obj.put("sucesso", "Renomeado com sucesso");
                } else {
                    obj.put("erro", "Erro ao renomear a pasta");
                }
                break;
            case "esvaziar":
                pasta.open(Folder.READ_WRITE);
                pasta.setFlags(1, pasta.getMessageCount(), new Flags(Flags.Flag.DELETED), true);
                pasta.expunge();
                obj.put("sucesso", "Esvaziado com sucesso");
                break;
            case "excluir":
                if (pasta.delete(true)) {
                    obj.put("sucesso", "Excludo com sucesso");
                } else {
                    obj.put("erro", "Erro ao excluir a pasta");
                }
                break;
            case "nova":
                pasta = store.getFolder(novo);
                if (!pasta.exists()) {
                    if (pasta.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)) {
                        obj.put("sucesso", "Criado com sucesso");
                    } else {
                        obj.put("erro", "Erro ao criar a pasta");
                    }
                } else {
                    obj.put("erro", "Erro ao criar a pasta");
                }
                break;
            }
        } catch (MessagingException ex) {
            obj.put("erro", "Erro ao processar solicitao");
        }

        obj.writeJSONString(response.getWriter());

        return;
    }

    String metodo = request.getParameter("acao");
    if (metodo == null) {
        return;
    } else if (metodo.equals("nova")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Login usuario = Logar.getLogin(request.getSession());

            Conta conta = new Conta();
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));
            conta.setIdLogin(usuario);

            em.persist(conta);
            em.merge(usuario);

            em.getTransaction().commit();
            em.refresh(conta);
            em.refresh(usuario);

            request.setAttribute("mensagem", "sucesso");
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=nova").forward(request, response);
    } else if (metodo.equals("conta")) {
        EntityManager em = BD.getEntityManager();

        try {
            em.getTransaction().begin();

            Conta conta = (Conta) request.getSession().getAttribute("conta");

            em.refresh(conta);
            conta.setEmail(request.getParameter("email"));
            conta.setImapHost(request.getParameter("imapHost"));
            conta.setImapPort(Integer.parseInt(request.getParameter("imapPort")));
            conta.setImapPassword(request.getParameter("imapPassword"));
            conta.setImapUser(request.getParameter("imapLogin"));
            conta.setSmtpHost(request.getParameter("smtpHost"));
            conta.setSmtpPort(Integer.parseInt(request.getParameter("smtpPort")));
            conta.setSmtpPassword(request.getParameter("smtpPassword"));
            conta.setSmtpUser(request.getParameter("smtpLogin"));

            em.getTransaction().commit();

            request.setAttribute("mensagem", "sucesso");
        } catch (PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=conta").forward(request, response);

    } else if (metodo.equals("senha")) {
        EntityManager em = BD.getEntityManager();

        try {

            Login usuario = Logar.getLogin(request.getSession());

            em.refresh(usuario);

            String senatu = request.getParameter("senAtu"), novasen = request.getParameter("senNova"),
                    novasen2 = request.getParameter("senNova2");

            if (novasen.equals(novasen2) && senatu.equals(usuario.getSenha())) {

                em.getTransaction().begin();

                usuario.setSenha(novasen);

                em.getTransaction().commit();

                request.setAttribute("mensagem", "sucesso");
            } else {
                if (!novasen.equals(novasen2))
                    request.setAttribute("mensagem", "senneq");
                else
                    request.setAttribute("mensagem", "antsen");
            }
        } catch (Logar.NaoAutenticadoException | PersistenceException ex) {
            em.getTransaction().rollback();

            request.setAttribute("mensagem", "erro");
        }

        request.getRequestDispatcher("/conf.jsp?metodo=senha").forward(request, response);

    }
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*from w  w w  .j a v a  2  s  .  c  o  m*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        if (!dst.create(src.getType())) {
            // might not be able to create a folder that holds both
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                // might only be able to create one type (Gmail)
                if (!dst.create(Folder.HOLDS_MESSAGES)) {
                    System.out.println("couldn't create " + dst.getFullName());
                    return;
                }
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:folderlist.java

static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception {
    System.out.println(tab + "Name:      " + folder.getName());
    System.out.println(tab + "Full Name: " + folder.getFullName());
    System.out.println(tab + "URL:       " + folder.getURLName());

    if (verbose) {
        if (!folder.isSubscribed())
            System.out.println(tab + "Not Subscribed");

        if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
            if (folder.hasNewMessages())
                System.out.println(tab + "Has New Messages");
            System.out.println(tab + "Total Messages:  " + folder.getMessageCount());
            System.out.println(tab + "New Messages:    " + folder.getNewMessageCount());
            System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount());
        }/*from   ww  w .j a  va 2 s . com*/
        if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
            System.out.println(tab + "Is Directory");

        /*
         * Demonstrate use of IMAP folder attributes
         * returned by the IMAP LIST response.
         */
        if (folder instanceof IMAPFolder) {
            IMAPFolder f = (IMAPFolder) folder;
            String[] attrs = f.getAttributes();
            if (attrs != null && attrs.length > 0) {
                System.out.println(tab + "IMAP Attributes:");
                for (int i = 0; i < attrs.length; i++)
                    System.out.println(tab + "    " + attrs[i]);
            }
        }
    }

    System.out.println();

    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        if (recurse) {
            Folder[] f = folder.list();
            for (int i = 0; i < f.length; i++)
                dumpFolder(f[i], recurse, tab + "    ");
        }
    }
}

From source file:populate.java

private static void copy(Folder src, Folder dst) throws MessagingException {
    System.out.println("Populating " + dst.getFullName());

    Folder ddst = dst;/*from   w  ww  . j  av a 2s  .c o  m*/
    Folder[] srcFolders = null;
    if ((src.getType() & Folder.HOLDS_FOLDERS) != 0)
        srcFolders = src.list();
    boolean srcHasChildren = srcFolders != null && srcFolders.length > 0;

    if (!dst.exists()) {
        // Create it.
        boolean dstHoldsOnlyFolders = false;
        try {
            if (!dst.create(src.getType())) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
        } catch (MessagingException mex) {
            // might not be able to create a folder that holds both
            if (src.getType() != (Folder.HOLDS_MESSAGES | Folder.HOLDS_FOLDERS))
                throw mex;
            if (!dst.create(srcHasChildren ? Folder.HOLDS_FOLDERS : Folder.HOLDS_MESSAGES)) {
                System.out.println("couldn't create " + dst.getFullName());
                return;
            }
            dstHoldsOnlyFolders = srcHasChildren;
        }

        // Copy over any messges from src to dst
        if ((src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            if (dstHoldsOnlyFolders) {
                if (src.getMessageCount() > 0) {
                    System.out.println("Unable to copy messages from " + src.getFullName() + " to "
                            + dst.getFullName() + " because destination holds only folders");
                }
            } else
                copyMessages(src, dst);
            src.close(false);
        }
    } else {
        System.out.println(dst.getFullName() + " already exists");
        // Copy over any messges from src to dst
        if (force && (src.getType() & Folder.HOLDS_MESSAGES) != 0) {
            src.open(Folder.READ_ONLY);
            copyMessages(src, dst);
            src.close(false);
        }
    }

    // Copy over subfolders
    if (srcHasChildren) {
        for (int i = 0; i < srcFolders.length; i++) {
            // skip special directories?
            if (skipSpecial) {
                if (srcFolders[i].getName().equals("SCCS") || srcFolders[i].getName().equals("Drafts")
                        || srcFolders[i].getName().equals("Trash")
                        || srcFolders[i].getName().equals("Shared Folders"))
                    continue;
            }
            copy(srcFolders[i], dst.getFolder(srcFolders[i].getName()));
        }
    }
}

From source file:MainClass.java

static void dumpFolder(Folder folder, boolean recurse, String tab) throws Exception {
    System.out.println(tab + "Name:      " + folder.getName());
    System.out.println(tab + "Full Name: " + folder.getFullName());
    System.out.println(tab + "URL:       " + folder.getURLName());

    if (verbose) {
        if (!folder.isSubscribed())
            System.out.println(tab + "Not Subscribed");

        if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
            if (folder.hasNewMessages())
                System.out.println(tab + "Has New Messages");
            System.out.println(tab + "Total Messages:  " + folder.getMessageCount());
            System.out.println(tab + "New Messages:    " + folder.getNewMessageCount());
            System.out.println(tab + "Unread Messages: " + folder.getUnreadMessageCount());
        }//from  www  . j a v  a2  s. c  om
        if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
            System.out.println(tab + "Is Directory");

        /*
         * Demonstrate use of IMAP folder attributes returned by the IMAP LIST
         * response.
         */
        if (folder instanceof IMAPFolder) {
            IMAPFolder f = (IMAPFolder) folder;
            String[] attrs = f.getAttributes();
            if (attrs != null && attrs.length > 0) {
                System.out.println(tab + "IMAP Attributes:");
                for (int i = 0; i < attrs.length; i++)
                    System.out.println(tab + "    " + attrs[i]);
            }
        }
    }

    System.out.println();

    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        if (recurse) {
            Folder[] f = folder.list();
            for (int i = 0; i < f.length; i++)
                dumpFolder(f[i], recurse, tab + "    ");
        }
    }
}

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

protected void readFolder(Folder folder) throws MessagingException, IOException, SearchLibException {
    if (folder == null)
        return;// w  ww.  j a v  a2s  .c o  m
    if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0)
        readMessagesFolder(folder);
    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0)
        readHoldsFolder(folder);
}

From source file:com.jaeksoft.searchlib.crawler.mailbox.crawler.MailboxAbstractCrawler.java

protected void checkFolder(Folder folder, PrintWriter pw)
        throws MessagingException, IOException, SearchLibException {
    if (folder == null)
        return;//from  w w  w  .j a va2 s  .  co m
    if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) {
        folder.open(Folder.READ_ONLY);
        try {
            pw.print("Folder ");
            pw.print(folder.getName());
            pw.print(": ");
            pw.print(folder.getMessageCount());
            pw.println(" msgs(s).");
        } finally {
            folder.close(false);
        }
    }
    if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) {
        Folder[] folders = folder.list();
        if (folders != null)
            for (Folder f : folders)
                checkFolder(f, pw);
    }
}

From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java

protected void createInitialIMAPTestdata(final Properties props, final String user, final String password,
        final int count, final boolean deleteall) throws MessagingException {
    final Session session = Session.getInstance(props);
    final Store store = session.getStore();
    store.connect(user, password);//ww  w .j a va  2 s.  c om
    checkStoreForTestConnection(store);
    final Folder root = store.getDefaultFolder();
    final Folder testroot = root.getFolder("ES-IMAP-RIVER-TESTS");
    final Folder testrootl2 = testroot.getFolder("Level(2!");

    if (deleteall) {

        deleteMailsFromUserMailbox(props, "INBOX", 0, -1, user, password);

        if (testroot.exists()) {
            testroot.delete(true);
        }

        final Folder testrootenamed = root.getFolder("renamed_from_ES-IMAP-RIVER-TESTS");
        if (testrootenamed.exists()) {
            testrootenamed.delete(true);
        }

    }

    if (!testroot.exists()) {

        testroot.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testroot.open(Folder.READ_WRITE);

        testrootl2.create(Folder.HOLDS_FOLDERS & Folder.HOLDS_MESSAGES);
        testrootl2.open(Folder.READ_WRITE);

    }

    final Folder inbox = root.getFolder("INBOX");
    inbox.open(Folder.READ_WRITE);

    final Message[] msgs = new Message[count];

    for (int i = 0; i < count; i++) {
        final MimeMessage message = new MimeMessage(session);
        message.setFrom(new InternetAddress(EMAIL_TO));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(EMAIL_USER_ADDRESS));
        message.setSubject(EMAIL_SUBJECT + "::" + i);
        message.setText(EMAIL_TEXT + "::" + SID++);
        message.setSentDate(new Date());
        msgs[i] = message;

    }

    inbox.appendMessages(msgs);
    testroot.appendMessages(msgs);
    testrootl2.appendMessages(msgs);

    IMAPUtils.close(inbox);
    IMAPUtils.close(testrootl2);
    IMAPUtils.close(testroot);
    IMAPUtils.close(store);

}