Example usage for javax.mail Folder isOpen

List of usage examples for javax.mail Folder isOpen

Introduction

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

Prototype

public abstract boolean isOpen();

Source Link

Document

Indicates whether this Folder is in the 'open' state.

Usage

From source file:org.springframework.integration.mail.MailTransportUtils.java

/**
 * Close the given JavaMail Folder and ignore any thrown exception. This is
 * useful for typical <code>finally</code> blocks in manual JavaMail code.
 *
 * @param folder  the JavaMail Folder to close (may be <code>null</code>)
 * @param expunge whether all deleted messages should be expunged from the folder
 *//*ww w. j a v a 2 s .com*/
public static void closeFolder(Folder folder, boolean expunge) {
    if (folder != null && folder.isOpen()) {
        try {
            folder.close(expunge);
        } catch (MessagingException ex) {
            logger.debug("Could not close JavaMail Folder", ex);
        } catch (NullPointerException ex) {
            // JavaMail prior to 1.4.1 may throw this
            logger.debug("Could not close JavaMail Folder", ex);
        }
    }
}

From source file:org.springframework.ws.transport.mail.support.MailTransportUtils.java

/**
 * Close the given JavaMail Folder and ignore any thrown exception. This is useful for typical <code>finally</code>
 * blocks in manual JavaMail code.// w w  w.  ja va  2 s  .c  om
 *
 * @param folder  the JavaMail Folder to close (may be <code>null</code>)
 * @param expunge whether all deleted messages should be expunged from the folder
 */
public static void closeFolder(Folder folder, boolean expunge) {
    if (folder != null && folder.isOpen()) {
        try {
            folder.close(expunge);
        } catch (MessagingException ex) {
            logger.debug("Could not close JavaMail Folder", ex);
        }
    }
}

From source file:org.apache.hupa.server.preferences.InImapUserPreferencesStorage.java

/**
 * Opens the IMAP folder and read messages until it founds the magic subject,
 * then gets the attachment which contains the data and return the serialized object stored.
 *//*from w w w .ja va2s.  c o m*/
protected static Object readUserPreferencesFromIMAP(Log logger, User user, IMAPStore iStore, String folderName,
        String magicType) throws MessagingException, IOException, ClassNotFoundException {
    Folder folder = iStore.getFolder(folderName);
    if (folder.exists()) {
        if (!folder.isOpen()) {
            folder.open(Folder.READ_WRITE);
        }
        Message message = null;
        Message[] msgs = folder.getMessages();
        for (Message msg : msgs) {
            if (magicType.equals(msg.getSubject())) {
                message = msg;
                break;
            }
        }
        if (message != null) {
            Object con = message.getContent();
            if (con instanceof Multipart) {
                Multipart mp = (Multipart) con;
                for (int i = 0; i < mp.getCount(); i++) {
                    BodyPart part = mp.getBodyPart(i);
                    if (part.getContentType().toLowerCase().startsWith(HUPA_DATA_MIME_TYPE)) {
                        ObjectInputStream ois = new ObjectInputStream(part.getInputStream());
                        Object o = ois.readObject();
                        ois.close();
                        logger.info("Returning user preferences of type " + magicType + " from imap folder + "
                                + folderName + " for user " + user);
                        return o;
                    }
                }
            }
        }
    }
    return null;
}

From source file:org.jevis.emaildatasource.EMailManager.java

/**
 * Get list of messages/*from ww w  .  j  a v  a2s. c  om*/
 *
 * @param folder
 * @param conn
 *
 * @return List of Message
 */
private static List<Message> getMessageList(Folder folder, EMailChannelParameters chanParam) {

    List<Message> messageList = null;

    SearchTerm term = chanParam.getSearchTerms();
    try {
        folder.open(Folder.READ_ONLY);
    } catch (MessagingException ex) {
        Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE,
                "EMail folder is not available to read.", ex);
    }
    Message[] msgs = null;

    Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Folder is open: {0}", folder.isOpen());
    if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.IMAP)) {
        try {
            msgs = folder.search(term);
        } catch (MessagingException ex) {
            Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages", ex);
        }
    } else if (chanParam.getProtocol().equalsIgnoreCase(EMailConstants.Protocol.POP3)) {
        try {
            //                int[] msgnums = new int[1000];
            //                Message[] messages = folder.getMessages(msgnums);
            Message[] messages = folder.getMessages();
            messages = filterPOP3ByDate(messages, chanParam.getLastReadout());
            msgs = folder.search(term, messages);
        } catch (MessagingException ex) {
            Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE,
                    "POP3: failed to receive messages from a folder.", ex);
        }
    } else {
        Logger.getLogger(EMailManager.class.getName()).log(Level.SEVERE, "Unable to search messages");
    }

    messageList = Arrays.asList(msgs);

    Logger.getLogger(EMailManager.class.getName()).log(Level.INFO, "Messages found: {0}", messageList.size());

    return messageList;
}

From source file:org.apache.hupa.server.handler.DeleteFolderHandler.java

@Override
protected GenericResult executeInternal(DeleteFolder action, ExecutionContext context) throws ActionException {
    User user = getUser();/*ww  w  .j  a v  a2s  .c  o m*/
    IMAPFolder folder = action.getFolder();
    try {
        IMAPStore store = cache.get(user);

        Folder f = store.getFolder(folder.getFullName());

        // close the folder if its open
        if (f.isOpen()) {
            f.close(false);
        }

        // recursive delete the folder
        if (f.delete(true)) {
            logger.info("Successfully delete folder " + folder + " for user " + user);
            return new GenericResult();
        } else {
            throw new ActionException("Unable to delete folder " + folder + " for user " + user);
        }
    } catch (Exception e) {
        logger.error("Error while deleting folder " + folder + " for user " + user, e);
        throw new ActionException("Error while deleting folder " + folder + " for user " + user, e);
    }
}

From source file:org.springframework.ws.transport.mail.monitor.AbstractMonitoringStrategy.java

/**
 * Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for
 * all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link
 * javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term
 * is used to {@link Folder#search(SearchTerm) search} for new messages.
 *
 * @param folder the folder to retrieve new messages from
 * @return the new messages// w w  w  .  j a va2s .c o  m
 * @throws MessagingException in case of JavaMail errors
 */
protected Message[] searchForNewMessages(Folder folder) throws MessagingException {
    if (!folder.isOpen()) {
        return new Message[0];
    }
    Flags supportedFlags = folder.getPermanentFlags();
    SearchTerm searchTerm = null;
    if (supportedFlags != null) {
        if (supportedFlags.contains(Flags.Flag.RECENT)) {
            searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
        }
        if (supportedFlags.contains(Flags.Flag.ANSWERED)) {
            FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false);
            if (searchTerm == null) {
                searchTerm = answeredTerm;
            } else {
                searchTerm = new AndTerm(searchTerm, answeredTerm);
            }
        }
        if (supportedFlags.contains(Flags.Flag.DELETED)) {
            FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false);
            if (searchTerm == null) {
                searchTerm = deletedTerm;
            } else {
                searchTerm = new AndTerm(searchTerm, deletedTerm);
            }
        }
    }
    return searchTerm != null ? folder.search(searchTerm) : folder.getMessages();
}

From source file:FolderModel.java

public void setFolder(Folder what) throws MessagingException {
    if (what != null) {

        // opened if needed
        if (!what.isOpen()) {
            what.open(Folder.READ_WRITE);
        }//from  www.  ja v a 2s .  co  m

        // get the messages
        messages = what.getMessages();
        cached = new String[messages.length][];
    } else {
        messages = null;
        cached = null;
    }
    // close previous folder and switch to new folder
    if (folder != null)
        folder.close(true);
    folder = what;
    fireTableDataChanged();
}

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  ww  . ja  va  2 s.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: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;
        }/* ww  w  .  ja v  a  2s  . co 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:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Close any {@link Folder} that contain {@link Message} and are in open state.
 *
 * @param folder {@link Folder} to be closed
 *///w  w  w.  jav  a  2 s  . com
private void closeFolder(Folder folder) {
    if (folder != null) {
        try {
            if (folder.isOpen()) {
                folder.close(true);
            } else {
                LOG.info(folder.getName() + " folder is already open.");
            }
        } catch (Exception e) {
            LOG.warn("Cannot close folder : " + folder.getName(), e);
        }
    }
}