Example usage for javax.mail Folder READ_ONLY

List of usage examples for javax.mail Folder READ_ONLY

Introduction

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

Prototype

int READ_ONLY

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

Click Source Link

Document

The Folder is read only.

Usage

From source file:com.googlecode.gmail4j.javamail.ImapGmailClient.java

/**
 * Returns list of unread/read priority {@link GmailMessage} objects 
 * based on the {@code unreadOnly} value
 * //from  w  w w  .j  a va2  s  .c  o m
 * @param unreadOnly {@code true} to unread priority {@link GmailMessage} 
 * objects only, {@code false} to read priority {@link GmailMessage} 
 * objects only
 * @return List of unread/read priority messages
 * @throws GmailException if unable to get unread/read priority messages
 */
public List<GmailMessage> getPriorityMessages(boolean unreadOnly) {
    try {
        final List<GmailMessage> priorityMessages = new ArrayList<GmailMessage>();
        final Store store = openGmailStore();
        Folder folder = getFolder(ImapGmailLabel.IMPORTANT.getName(), store);
        folder.open(Folder.READ_ONLY);
        for (final Message msg : folder.search(new FlagTerm(new Flags(Flags.Flag.SEEN), !unreadOnly))) {
            priorityMessages.add(new JavaMailGmailMessage(msg));
        }

        return priorityMessages;
    } catch (final Exception e) {
        throw new GmailException("Failed getting priority messages", e);
    }
}

From source file:edu.ku.brc.helpers.EMailHelper.java

/**
 * Retrieves all the message from the INBOX.
 * @param store the store to retrieve them from
 * @param msgList the list to add them to
 * @return true if successful, false if their was an exception
 *//*w w w . j  a  va  2  s. c o m*/
public static boolean getMessagesFromInbox(final Store store,
        final java.util.List<javax.mail.Message> msgList) {
    try {
        Folder inbox = store.getDefaultFolder().getFolder("Inbox"); //$NON-NLS-1$
        inbox.open(Folder.READ_ONLY);

        javax.mail.Message[] messages = inbox.getMessages();

        Collections.addAll(msgList, messages);

        MailBoxInfo mbx = instance.new MailBoxInfo(store, inbox);

        instance.mailBoxCache.add(mbx);

        return true;

    } catch (MessagingException mex) {
        edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount();
        edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(EMailHelper.class, mex);
        instance.lastErrorMsg = mex.toString();
    }
    return false;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Fetch a message from a folder.//w  ww.j  a v a 2  s .co  m
 * Will put the messages parameters in the sessions environment
 *
 * @param foldername Name of the folder were the message should be fetched from
 * @param msgnum Number of the message to fetch
 * @param mode there are three different modes: standard, reply and forward. reply and forward will enter the message
 *             into the current work element of the user and set some additional flags on the message if the user
 *             has enabled this option.
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_STANDARD
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_REPLY
 * @see net.wastl.webmail.server.WebMailSession.GETMESSAGE_MODE_FORWARD
 */
public void getMessage(String folderhash, int msgnum, int mode) throws NoSuchFolderException, WebMailException {
    // security reasons:
    // attachments=null;

    try {
        TimeZone tz = TimeZone.getDefault();
        DateFormat df = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.SHORT,
                user.getPreferredLocale());
        df.setTimeZone(tz);
        Folder folder = getFolder(folderhash);
        Element xml_folder = model.getFolder(folderhash);

        if (folder == null) {
            throw new NoSuchFolderException("No such folder: " + folderhash);
        }

        if (folder.isOpen() && folder.getMode() == Folder.READ_WRITE) {
            folder.close(false);
            folder.open(Folder.READ_ONLY);
        } else if (!folder.isOpen()) {
            folder.open(Folder.READ_ONLY);
        }

        MimeMessage m = (MimeMessage) folder.getMessage(msgnum);

        String messageid;
        try {
            StringTokenizer tok = new StringTokenizer(m.getMessageID(), "<>");
            messageid = tok.nextToken();
        } catch (NullPointerException ex) {
            // For mail servers that don't generate a Message-ID (Outlook et al)
            messageid = user.getLogin() + "." + msgnum + ".jwebmail@" + user.getDomain();
        }

        Element xml_current = model.setCurrentMessage(messageid);
        XMLMessage xml_message = model.getMessage(xml_folder, m.getMessageNumber() + "", messageid);

        /* Check whether we already cached this message (not only headers but complete)*/
        boolean cached = xml_message.messageCompletelyCached();
        /* If we cached the message, we don't need to fetch it again */
        if (!cached) {
            //Element xml_header=model.getHeader(xml_message);

            try {
                String from = MimeUtility.decodeText(Helper.joinAddress(m.getFrom()));
                String replyto = MimeUtility.decodeText(Helper.joinAddress(m.getReplyTo()));
                String to = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.TO)));
                String cc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.CC)));
                String bcc = MimeUtility
                        .decodeText(Helper.joinAddress(m.getRecipients(Message.RecipientType.BCC)));
                Date date_orig = m.getSentDate();
                String date = getStringResource("no date");
                if (date_orig != null) {
                    date = df.format(date_orig);
                }
                String subject = "";
                if (m.getSubject() != null) {
                    subject = MimeUtility.decodeText(m.getSubject());
                }
                if (subject == null || subject.equals("")) {
                    subject = getStringResource("no subject");
                }

                try {
                    Flags.Flag[] sf = m.getFlags().getSystemFlags();
                    for (int j = 0; j < sf.length; j++) {
                        if (sf[j] == Flags.Flag.RECENT)
                            xml_message.setAttribute("recent", "true");
                        if (sf[j] == Flags.Flag.SEEN)
                            xml_message.setAttribute("seen", "true");
                        if (sf[j] == Flags.Flag.DELETED)
                            xml_message.setAttribute("deleted", "true");
                        if (sf[j] == Flags.Flag.ANSWERED)
                            xml_message.setAttribute("answered", "true");
                        if (sf[j] == Flags.Flag.DRAFT)
                            xml_message.setAttribute("draft", "true");
                        if (sf[j] == Flags.Flag.FLAGGED)
                            xml_message.setAttribute("flagged", "true");
                        if (sf[j] == Flags.Flag.USER)
                            xml_message.setAttribute("user", "true");
                    }
                } catch (NullPointerException ex) {
                }
                if (m.getContentType().toUpperCase().startsWith("MULTIPART/")) {
                    xml_message.setAttribute("attachment", "true");
                }

                int size = m.getSize();
                size /= 1024;
                xml_message.setAttribute("size", (size > 0 ? size + "" : "<1") + " kB");

                /* Set all of what we found into the DOM */
                xml_message.setHeader("FROM", from);
                xml_message.setHeader("SUBJECT", Fancyfier.apply(subject));
                xml_message.setHeader("TO", to);
                xml_message.setHeader("CC", cc);
                xml_message.setHeader("BCC", bcc);
                xml_message.setHeader("REPLY-TO", replyto);
                xml_message.setHeader("DATE", date);

                /* Decode MIME contents recursively */
                xml_message.removeAllParts();
                parseMIMEContent(m, xml_message, messageid);

            } catch (UnsupportedEncodingException e) {
                log.warn("Unsupported Encoding in parseMIMEContent: " + e.getMessage());
            }
        }
        /* Set seen flag (Maybe make that threaded to improve performance) */
        if (user.wantsSetFlags()) {
            if (folder.isOpen() && folder.getMode() == Folder.READ_ONLY) {
                folder.close(false);
                folder.open(Folder.READ_WRITE);
            } else if (!folder.isOpen()) {
                folder.open(Folder.READ_WRITE);
            }
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.SEEN), true);
            folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.RECENT), false);
            if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                folder.setFlags(msgnum, msgnum, new Flags(Flags.Flag.ANSWERED), true);
            }
        }
        folder.close(false);

        /* In this part we determine whether the message was requested so that it may be used for
           further editing (replying or forwarding). In this case we set the current "work" message to the
           message we just fetched and then modifiy it a little (quote, add a "Re" to the subject, etc). */
        XMLMessage work = null;
        if ((mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY
                || (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
            log.debug("Setting work message!");
            work = model.setWorkMessage(xml_message);

            String newmsgid = WebMailServer.generateMessageID(user.getUserName());

            if (work != null && (mode & GETMESSAGE_MODE_REPLY) == GETMESSAGE_MODE_REPLY) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", from);
                work.prepareReply(getStringResource("reply subject prefix"),
                        getStringResource("reply subject postfix"), getStringResource("reply message prefix"),
                        getStringResource("reply message postfix"));

            } else if (work != null && (mode & GETMESSAGE_MODE_FORWARD) == GETMESSAGE_MODE_FORWARD) {
                String from = work.getHeader("FROM");
                work.setHeader("FROM", user.getDefaultEmail());
                work.setHeader("TO", "");
                work.setHeader("CC", "");
                work.prepareForward(getStringResource("forward subject prefix"),
                        getStringResource("forward subject postfix"),
                        getStringResource("forward message prefix"),
                        getStringResource("forward message postfix"));

                /* Copy all references to MIME parts to the new message id */
                for (String key : getMimeParts(work.getAttribute("msgid"))) {
                    StringTokenizer tok2 = new StringTokenizer(key, "/");
                    tok2.nextToken();
                    String newkey = tok2.nextToken();
                    mime_parts_decoded.put(newmsgid + "/" + newkey, mime_parts_decoded.get(key));
                }
            }

            /* Clear the msgnr and msgid fields at last */
            work.setAttribute("msgnr", "0");
            work.setAttribute("msgid", newmsgid);
            prepareCompose();
        }
    } catch (MessagingException ex) {
        log.error("Failed to get message.  Doing nothing instead.", ex);
    }
}

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

public String renameFolder(String orig, String newname) throws MessagingException {
    FolderCache fc = getFolderCache(orig);
    FolderCache fcparent = fc.getParent();
    Folder oldfolder = fc.getFolder();/*  w  w  w  .j av a 2 s . c  om*/
    destroyFolderCache(fc);
    Folder newfolder = fcparent.getFolder().getFolder(newname);
    boolean done = oldfolder.renameTo(newfolder);
    if (!done) {
        throw new MessagingException("Rename failed");
    }

    //trick for Dovecot on NethServer: under shared folders, create and destroy a fake folder
    //or rename will not work correctly
    if (isUnderSharedFolder(newfolder.getFullName())) {
        Map<String, String> map = ((IMAPStore) store).id(null);
        if (map != null && map.containsKey("name") && map.get("name").equalsIgnoreCase("dovecot")) {
            String trickName = "_________" + System.currentTimeMillis();
            Folder trickFolder = fcparent.getFolder().getFolder(trickName);
            try {
                trickFolder.create(Folder.READ_ONLY);
                trickFolder.delete(true);
            } catch (MessagingException exc) {

            }
        }
    }

    addFoldersCache(fcparent, newfolder);
    return newfolder.getFullName();
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Retrieve mail for user.//from w w w. ja v a2 s .  co  m
 *
 * @param userType = "P" if logged in user is a provider
 *                   "T" if logged in user is a patient
 * @param userId = unique id of logged in user.
 * @param login = email server user name of logged in user.
 * @param pswd  = password of logged in user.
 * @param folderName = 
 * @param displayName = full name
 * @param onlyNew =
 *
 * @return
 * @throws java.lang.Exception
 */
//private  //DBG ONLY - REMOVE COMMENT MARKS
public List<SummaryData> retrieveMail(String userType, String userId, String patientId, String login,
        String pswd, String folderName, String patientName, boolean onlyNew, String mailHost, String mailUrl)
        throws Exception, DatatypeConfigurationException {
    List<SummaryData> dataList = new LinkedList<SummaryData>();
    IMAPSSLStore sslStore = null;
    IMAPFolder currentFolder = null;
    String folderToOpen = folderName;

    System.out.println("===> retrieveMail Incoming params:");
    System.out.println("===>     mailHost=" + mailHost);
    System.out.println("===>      mailUrl=" + mailUrl);
    System.out.println("===>    maillogin=" + login);
    System.out.println("===>   folderName=" + folderName);
    try {
        //Get session
        Session session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);
        //Get the sslStore
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(mailHost, login, pswd);

        folderToOpen = this.mapKmrLocationToImapFolder(folderName, this.host);

        currentFolder = (IMAPFolder) sslStore.getFolder(folderToOpen);
        currentFolder.open(Folder.READ_ONLY);

        Message[] allMessages = currentFolder.getMessages();

        GregorianCalendar cal = new GregorianCalendar();

        System.out.println("====> FILTER PARAMS for Emails:");
        System.out.println("====>     folder = " + folderToOpen);
        System.out.println("====>     User   = " + login);
        //            System.out.println("====>     from   = "+ patientName +"/"+ patientEmail);
        //            System.out.println("====>     ptid   = "+ patientId);
        System.out.println("====> Total Emails found = " + allMessages.length);
        System.out.println();

        // TMN - CHECK SLOW PERFORMANCE ISSUE HERE:

        //Loop through each email and find ONLY the ones required for return.
        for (Message msg : allMessages) {
            if (msg == null) {
                continue;
            }

            // Keep this in case we want to search entire message
            //
            //                OutputStream os = new ByteArrayOutputStream();
            //                msg.writeTo(os);
            //                String msgContent = os.toString();

            SummaryData summaryData = new SummaryData();
            summaryData.setDataSource(DATA_SOURCE);

            String from = "";
            Address[] fromAddr = msg.getFrom();

            if (fromAddr != null && fromAddr.length > 0) {

                String fromFull = fromAddr[0].toString();
                from = getContactIdFromEmail(extractEmailAddressFromSender(fromFull));

                //System.out.println("retrieveMail: FROM=" + fromFull + " ldap.cn=" + from);

            }

            //------------------------------------------------------
            //FILTERING: Check to exclude email if
            //     0) patientId is passed in as a param
            // AND 1) email does NOT contain PATIENTID=<patientId>
            // AND 2) email FROM field <> patientName
            // AND 3) email FROM field <> patientEmail.
            //
            // because must becoming from EMR inbox and looking for emails
            // addressed to userId BUT only ABOUT or FROM patientId.
            //------------------------------------------------------

            summaryData.setFrom(from);
            summaryData.setAuthor(summaryData.getFrom());
            cal.setTime(msg.getReceivedDate());
            summaryData.setDateCreated(DatatypeFactory.newInstance().newXMLGregorianCalendar(cal));

            summaryData.setDescription(msg.getSubject());

            summaryData.setItemId(userType + userId + ITEM_ID_SEPARATER + msg.getFolder().getName()
                    + ITEM_ID_SEPARATER + msg.getHeader("Message-ID")[0]);

            //this.printMsgIdSubject(msg); //DBG printout

            boolean msgRead = msg.isSet(Flags.Flag.SEEN);
            addNameValue(summaryData.getItemValues(), ITEM_READ, String.valueOf(msgRead));

            boolean msgStar = msg.isSet(Flags.Flag.FLAGGED);
            if (msgStar) {
                addNameValue(summaryData.getItemValues(), ITEM_STARRED, "Starred");
            }

            addNameValue(summaryData.getItemValues(), ITEM_REPLIED,
                    String.valueOf(msg.isSet(Flags.Flag.ANSWERED)));
            addNameValue(summaryData.getItemValues(), "MESSAGE_TYPE", msg.getFolder().getName());
            if (onlyNew) {
                if (!msg.isSet(Flags.Flag.SEEN)) {
                    dataList.add(summaryData);
                }
            } else {
                dataList.add(summaryData);
            }
        }

    } catch (MessagingException me) {
        log.error("Error in processing email");
        me.printStackTrace();
    } finally {
        // Close connections

        if (currentFolder != null) {
            try {
                currentFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return dataList;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * Get an array of all messages from an email folder.
 * /*  ww  w  . j a  v a 2 s. com*/
 * @param folderName
 * @param sslStore
 * @return
 * @throws MessagingException
 */
private Message[] getFolderMessages(String folderName, IMAPSSLStore sslStore) throws MessagingException {

    IMAPFolder folder = (IMAPFolder) sslStore.getFolder(folderName);
    folder.open(Folder.READ_ONLY);
    Message[] messageArr = folder.getMessages();

    return messageArr;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 *
 * @param folders//  ww w  .  j  a  va2 s.com
 * @param sslStore
 * @return
 * @throws MessagingException
 */
private Message[] getAllFolderMessages(IMAPFolder[] folders, IMAPSSLStore sslStore) throws MessagingException {
    folders[0] = (IMAPFolder) sslStore.getFolder(this.mapKmrLocationToImapFolder("INBOX", this.host));
    folders[0].open(Folder.READ_ONLY);
    Message[] messageArr = folders[0].getMessages();

    folders[0] = (IMAPFolder) sslStore.getFolder(this.mapKmrLocationToImapFolder("archive", this.host));
    folders[1].open(Folder.READ_ONLY);
    Message[] archMsgArr = folders[1].getMessages();

    folders[0] = (IMAPFolder) sslStore.getFolder(this.mapKmrLocationToImapFolder("Sent", this.host));
    folders[2].open(Folder.READ_ONLY);
    Message[] sentMsgArr = folders[2].getMessages();

    folders[0] = (IMAPFolder) sslStore.getFolder(this.mapKmrLocationToImapFolder("Drafts", this.host));
    folders[3].open(Folder.READ_ONLY);
    Message[] draftMsgArr = folders[3].getMessages();

    Message[] allMessages = new Message[messageArr.length + archMsgArr.length + sentMsgArr.length
            + draftMsgArr.length];

    if (messageArr.length > 0) {
        System.arraycopy(messageArr, 0, allMessages, 0, messageArr.length);
    }
    if (archMsgArr.length > 0) {
        System.arraycopy(archMsgArr, 0, allMessages, messageArr.length, archMsgArr.length);
    }
    if (sentMsgArr.length > 0) {
        System.arraycopy(sentMsgArr, 0, allMessages, messageArr.length + archMsgArr.length, sentMsgArr.length);
    }
    if (draftMsgArr.length > 0) {
        System.arraycopy(draftMsgArr, 0, allMessages, messageArr.length + archMsgArr.length + sentMsgArr.length,
                draftMsgArr.length);
    }

    return allMessages;
}

From source file:org.socraticgrid.displaymaildata.DisplayMailDataHandler.java

/**
 * IN USE/*from w  ww.  j  a v a  2s  . c  o m*/
 * 
 * @param request
 * @return
 * @throws Exception
 */
public GetMessageDetailResponseType getMessageDetail(GetMessageDetailRequestType request) throws Exception {
    System.out.println("===> DMD.getMessageDetail: Looking for msgId=" + request.getMessageId());
    System.out.println("===> DMD.getMessageDetail: request patientId=" + request.getPatientId());
    System.out.println("===> DMD.getMessageDetail: request    userId=" + request.getUserId());

    GetMessageDetailResponseType response = new GetMessageDetailResponseType();

    IMAPFolder msgFolder = null;
    IMAPSSLStore sslStore = null;
    Properties prop = initializeMailProperties();
    Session session = Session.getDefaultInstance(prop);

    //------------------------------------------------------------------
    // When patientId is given, access must be from EMR Inbox.
    //      Get email msgs from Patient's email account.
    // Else
    //      Get email msgs from logged in user's email account.
    //------------------------------------------------------------------
    ContactDTO contact = null;
    String userType = "";
    String[] access = new String[2];

    if (!CommonUtil.strNullorEmpty(request.getPatientId())) {
        contact = contactDAO.findContact("uid=" + request.getPatientId()).get(0);
        userType = ITEM_ID_PATIENT;

    } else {
        contact = contactDAO.findContact("uid=" + request.getUserId()).get(0);
        userType = ITEM_ID_PROVIDER;
    }
    access = retrieveMailAccess(contact.getCommonName(), contact.getUid());

    try {
        session = Session.getInstance(new Properties());
        URLName urlName = new URLName(mailUrl);

        //--------------------------------------------
        //Get the sslStore and connect
        //--------------------------------------------
        sslStore = new IMAPSSLStore(session, urlName);
        sslStore.connect(host, access[0], access[1]);

        //--------------------------------------------
        // Set the originating folder.
        // Default to INBOX if not given.
        // Get and open the IMAP folder
        //--------------------------------------------
        String folderName = null;
        if (CommonUtil.strNullorEmpty(request.getLocation())) {
            folderName = "INBOX";
        } else {
            folderName = mapKmrLocationToImapFolder(request.getLocation(), this.host);
        }

        msgFolder = (IMAPFolder) sslStore.getFolder(folderName);
        msgFolder.open(Folder.READ_ONLY);

        //--------------------------------------------
        // Find the message by the given Message-ID
        //--------------------------------------------
        Message msg = this.findMsgByMessageId(msgFolder, request.getMessageId());

        if (msg == null) {
            String errmsg = "Msg NOT FOUND for Message-ID=" + request.getMessageId();
            System.out.println("===> getMessageDetail: " + errmsg);

            response.setSuccessStatus(false);
            response.setStatusMessage(errmsg);

        } else {
            //this.printMsgIdSubject(msg); //DBG printout
            System.out.println("===> getMessageDetail: Msg FOUND for Message-ID=" + request.getMessageId());

            //---------------------------------------------------
            // Extract "PATIENTID=" from body if present, so that
            // user does not see it.
            //---------------------------------------------------
            String content = fetchMsgContent(msg);

            if (content.startsWith("PATIENTID=")) {
                Scanner scanner = new Scanner(content);
                boolean first = true;
                StringBuilder sb = new StringBuilder();
                while (scanner.hasNextLine()) {
                    if (first) {
                        String[] parts = scanner.nextLine().split("=");
                        response.setPatientId(parts[1]);
                        first = false;
                    } else {
                        sb.append(scanner.nextLine());
                    }

                }
                response.getMessageDetail().add(sb.toString());
            } else {
                response.getMessageDetail().add(content);
            }

            // Adding patientId coming from the message header.
            //            if (msg.getHeader("X-PATIENTID") != null &&
            //                msg.getHeader("X-PATIENTID").length > 0) {
            //
            //                response.setPatientId(msg.getHeader("X-PATIENT_ID")[0]);
            //            }

            if (msg.getRecipients(Message.RecipientType.TO) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.TO)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getSentTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: TO="+ a.toString() +" ldap.cn="+ contactId);
                }
            }

            if (msg.getRecipients(Message.RecipientType.CC) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.CC)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getCCTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: CC="+ a.toString() +" ldap.cn="+ contactId);
                }
            }

            if (msg.getRecipients(Message.RecipientType.BCC) != null) {
                for (Address a : msg.getRecipients(Message.RecipientType.BCC)) {
                    String contactId = getContactIdFromEmail(a.toString());
                    response.getBCCTo().add(contactId);

                    //System.out.println("DisplayMailDataHandler: BCC="+ a.toString() +" ldap.cn="+ contactId);
                }
            }
            response.setSuccessStatus(true);
            response.setStatusMessage("");
        }

    } catch (Exception e) {
        response.setSuccessStatus(false);
        response.setStatusMessage(
                "Error getting message detail for user: " + access[0] + "\n[EXCEPTION] " + e.toString());
        e.printStackTrace();

    } finally {
        if (msgFolder != null) {
            try {
                msgFolder.close(false);
            } catch (Exception e) {
            }
        }

        if (sslStore != null) {
            try {
                sslStore.close();
            } catch (Exception e) {
            }
        }
    }

    return response;
}

From source file:net.wastl.webmail.server.WebMailSession.java

/**
 * Construct the folder subtree for the given folder and append it to
 * xml_parent./*from w w  w .  j  a v  a2  s. c o  m*/
 *
 * N.b. this method does not necessarily create a new XML Folder Element.
 * If called with subscribed_only and the target Folder (and in some
 * cases its descendants) are not subscribed, no Element will be created
 * and 0 will be returned.
 * <P>
 * Pop servers don't support nesting at all, so you'll just get a single
 * level out of this method.
 * <P>
 * There is a critical subscribed_only difference in behavior between
 * Maildir and mbox type mail servers.
 * Maildir folders are all HOLDS_MESSAGES, whether empty or not, and
 * these folders have a subscribed attribute which the user can set,
 * and which we honor.
 * mbox folders, on the other hand, have no subscribed attribute for
 * their !HOLDS_MESSAGE folders, so we must recurse to all of the
 * descendant HOLDS_MESSAGE folders to see if we should show.
 *
 * @param folder the folder where we begin
 * @param xml_parent XML Element where the gathered information will be
 *                   appended
 * @param subscribed_only Only add 'subscribed' folders
 * @param doCount Whether to generate message counts for Elements
 *                corresponding to HOLDS_MESSAGE folders.
 * @returns maximum depth of the folder tree (needed to calculate the
 *     necessary columns in a table).  Returns 0 if no XML elements added.
 */
protected int getFolderTree(Folder folder, Element xml_parent, boolean subscribed_only, boolean doCount) {
    int generatedDepth = 0;
    int folderType;
    Element xml_folder;

    try {
        folderType = folder.getType();
    } catch (MessagingException ex) {
        log.error("Can't get enough info from server to even make Gui node", ex);
        xml_parent.setAttribute("error", "For child '" + folder.getName() + ":  " + ex.getMessage());
        return 0;
    }
    boolean holds_folders = (folderType & Folder.HOLDS_FOLDERS) != 0;
    boolean holds_messages = (folderType & Folder.HOLDS_MESSAGES) != 0;
    // Sanity check:
    if ((!holds_folders) && !holds_messages) {
        log.fatal("Folder can hold neither folders nor messages: " + folder.getFullName());
        throw new RuntimeException("Folder can hold neither folders nor messages: " + folder.getFullName());
    }
    if (subscribed_only && holds_messages && !folder.isSubscribed())
        return generatedDepth; // Return right away and save a LOT OF WORK
    // N.b. we honor folder.isSubscribed() only for holds_message
    // folders.  That means all Maildir server folders, and all
    // mbox server folders except for mbox directories.  In this
    // last case, we must recurse to determine whether to show folder.
    String id = generateFolderHash(folder);
    xml_folder = model.createFolder(id, folder.getName(), holds_folders, holds_messages);
    // XMLUserModel.createFolder() declares no throws.  If any Exceptions
    // are expected from it, move the statement above into the try block.
    // The xml_folder Element here will be orphaned and GC'd if we don't
    // appendChild (in which case we return 0).

    if (doCount && holds_messages)
        try {
            // this folder will definitely be added!
            /* This folder can contain messages */
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if (total_messages == -1 || new_messages == -1 || !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

            messagelist.setAttribute("total", total_messages + "");
            messagelist.setAttribute("new", new_messages + "");
            log.debug("Counted " + new_messages + '/' + total_messages + " for folder " + folder.getFullName());
            xml_folder.appendChild(messagelist);
        } catch (MessagingException ex) {
            log.warn("Failed to count messages in folder '" + folder.getFullName() + "'", ex);
            xml_folder.setAttribute("error", ex.getMessage());
        }

    int descendantDepth = 0;
    if (holds_folders)
        try {
            Set<String> fullNameSet = new HashSet<String>();

            /* Recursively add subfolders to the XML model */
            // DO NOT USE listSubscribed(), because with !HOLDS_MESSAGE
            // folders, that skips non-Message Folders which may contain
            // subscribed descendants!
            for (Folder f : folder.list()) {
                if (!fullNameSet.add(f.getFullName())) {
                    log.warn("Skipping duplicate subfolder returned by mail" + " server:  " + f.getFullName());
                    continue;
                }
                if (subscribed_only && (f.getType() & Folder.HOLDS_MESSAGES) != 0 && !f.isSubscribed())
                    continue;
                /* If we recursed here, the getFolderTree() would
                 * just return 0 and no harm done.
                 * Just helping performance by preventing a recursion
                 * here.
                 * For comment on the logic here, see the same test
                 * towards the top of this method (before recursion).
                 */
                int depth = getFolderTree(f, xml_folder, subscribed_only, doCount);
                if (depth > descendantDepth)
                    descendantDepth = depth;
            }
            generatedDepth += descendantDepth;
        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }

    // We've already validated that if subscribed_only and holds_message
    //  then folder is subcribed.  Also verified either holds_m or holds_f.
    //  Only have to check the !holds_message case.
    if (subscribed_only && (!holds_messages) && descendantDepth < 1) {
        xml_folder = null;
        // Unnecessary, but may encourage GC
        return generatedDepth;
    }

    /* We ALWAYS return only subscribed folders except for these two
     * distinct cases: */
    xml_folder.setAttribute("subscribed",
            ((holds_messages && !folder.isSubscribed()) || ((!holds_messages) && descendantDepth < 1)) ? "false"
                    : "true");
    // N.b. our Element's "subscribed" element does not correspond 1:1
    // to Folder.isSubscribed(), since non-message-holding Folders have
    // no "subscribed" attribute.
    folders.put(id, folder);

    xml_parent.appendChild(xml_folder);
    generatedDepth++; // Add the count for xml_folder
    return generatedDepth;
}

From source file:net.wastl.webmail.server.WebMailSession.java

public void refreshFolderInformation(String folderhash) {
    Folder folder = getFolder(folderhash);
    Element xml_folder = model.getFolder(folderhash);

    if (xml_folder.getAttribute("holds_messages").toLowerCase().equals("true")) {
        try {//from   ww w. ja va 2s.c o m
            Element messagelist = model.createMessageList();

            int total_messages = folder.getMessageCount();
            int new_messages = folder.getNewMessageCount();

            if ((total_messages == -1 || new_messages == -1) && !folder.isOpen()) {
                folder.open(Folder.READ_ONLY);
                total_messages = folder.getMessageCount();
                new_messages = folder.getNewMessageCount();
            }
            if (folder.isOpen())
                folder.close(false);

            messagelist.setAttribute("total", total_messages + "");
            messagelist.setAttribute("new", new_messages + "");

            model.removeMessageList(xml_folder);
            xml_folder.appendChild(messagelist);

        } catch (MessagingException ex) {
            xml_folder.setAttribute("error", ex.getMessage());
        }
    }
}