List of usage examples for javax.mail Folder HOLDS_MESSAGES
int HOLDS_MESSAGES
To view the source code for javax.mail Folder HOLDS_MESSAGES.
Click Source Link
From source file:edu.hawaii.soest.hioos.storx.StorXDispatcher.java
/** * A method that executes the reading of data from the email account to the * RBNB server after all configuration of settings, connections to hosts, * and thread initiatizing occurs. This method contains the detailed code * for reading the data and interpreting the data files. *///from ww w .j av a 2s . co m protected boolean execute() { logger.debug("StorXDispatcher.execute() called."); boolean failed = true; // indicates overall success of execute() boolean messageProcessed = false; // indicates per message success // declare the account properties that will be pulled from the // email.account.properties.xml file String accountName = ""; String server = ""; String username = ""; String password = ""; String protocol = ""; String dataMailbox = ""; String processedMailbox = ""; String prefetch = ""; // fetch data from each sensor in the account list List accountList = this.xmlConfiguration.getList("account.accountName"); for (Iterator aIterator = accountList.iterator(); aIterator.hasNext();) { int aIndex = accountList.indexOf(aIterator.next()); // populate the email connection variables from the xml properties // file accountName = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").accountName"); server = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").server"); username = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").username"); password = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").password"); protocol = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").protocol"); dataMailbox = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").dataMailbox"); processedMailbox = (String) this.xmlConfiguration .getProperty("account(" + aIndex + ").processedMailbox"); prefetch = (String) this.xmlConfiguration.getProperty("account(" + aIndex + ").prefetch"); logger.debug("\n\nACCOUNT DETAILS: \n" + "accountName : " + accountName + "\n" + "server : " + server + "\n" + "username : " + username + "\n" + "password : " + password + "\n" + "protocol : " + protocol + "\n" + "dataMailbox : " + dataMailbox + "\n" + "processedMailbox: " + processedMailbox + "\n" + "prefetch : " + prefetch + "\n"); // get a connection to the mail server Properties props = System.getProperties(); props.setProperty("mail.store.protocol", protocol); props.setProperty("mail.imaps.partialfetch", prefetch); try { // create the imaps mail session this.mailSession = Session.getDefaultInstance(props, null); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe) { try { // pause for 10 seconds logger.debug( "There was a problem connecting to the IMAP server. " + "Waiting 10 seconds to retry."); Thread.sleep(10000L); this.mailStore = mailSession.getStore(protocol); } catch (NoSuchProviderException nspe2) { logger.debug("There was an error connecting to the mail server. The " + "message was: " + nspe2.getMessage()); nspe2.printStackTrace(); failed = true; return !failed; } catch (InterruptedException ie) { logger.debug("The thread was interrupted: " + ie.getMessage()); failed = true; return !failed; } } try { this.mailStore.connect(server, username, password); // get folder references for the inbox and processed data box Folder inbox = mailStore.getFolder(dataMailbox); inbox.open(Folder.READ_WRITE); Folder processed = this.mailStore.getFolder(processedMailbox); processed.open(Folder.READ_WRITE); Message[] msgs; while (!inbox.isOpen()) { inbox.open(Folder.READ_WRITE); } msgs = inbox.getMessages(); List<Message> messages = new ArrayList<Message>(); Collections.addAll(messages, msgs); // sort the messages found in the inbox by date sent Collections.sort(messages, new Comparator<Message>() { public int compare(Message message1, Message message2) { int value = 0; try { value = message1.getSentDate().compareTo(message2.getSentDate()); } catch (MessagingException e) { e.printStackTrace(); } return value; } }); logger.debug("Number of messages: " + messages.size()); for (Message message : messages) { // Copy the message to ensure we have the full attachment MimeMessage mimeMessage = (MimeMessage) message; MimeMessage copiedMessage = new MimeMessage(mimeMessage); // determine the sensor serial number for this message String messageSubject = copiedMessage.getSubject(); Date sentDate = copiedMessage.getSentDate(); SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM"); // The subfolder of the processed mail folder (e.g. 2016-12); String destinationFolder = formatter.format(sentDate); logger.debug("Message date: " + sentDate + "\tNumber: " + copiedMessage.getMessageNumber()); String[] subjectParts = messageSubject.split("\\s"); String loggerSerialNumber = "SerialNumber"; if (subjectParts.length > 1) { loggerSerialNumber = subjectParts[2]; } // Do we have a data attachment? If not, there's no data to // process if (copiedMessage.isMimeType("multipart/mixed")) { logger.debug("Message size: " + copiedMessage.getSize()); MimeMessageParser parser = new MimeMessageParser(copiedMessage); try { parser.parse(); } catch (Exception e) { logger.error("Failed to parse the MIME message: " + e.getMessage()); continue; } ByteBuffer messageAttachment = ByteBuffer.allocate(256); // init only logger.debug("Has attachments: " + parser.hasAttachments()); for (DataSource dataSource : parser.getAttachmentList()) { if (StringUtils.isNotBlank(dataSource.getName())) { logger.debug( "Attachment: " + dataSource.getName() + ", " + dataSource.getContentType()); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); IOUtils.copy(dataSource.getInputStream(), outputStream); messageAttachment = ByteBuffer.wrap(outputStream.toByteArray()); } } // We now have the attachment and serial number. Parse the attachment // for the data components, look up the storXSource based on the serial // number, and push the data to the DataTurbine // parse the binary attachment StorXParser storXParser = new StorXParser(messageAttachment); // iterate through the parsed framesMap and handle each // frame // based on its instrument type BasicHierarchicalMap framesMap = (BasicHierarchicalMap) storXParser.getFramesMap(); Collection frameCollection = framesMap.getAll("/frames/frame"); Iterator framesIterator = frameCollection.iterator(); while (framesIterator.hasNext()) { BasicHierarchicalMap frameMap = (BasicHierarchicalMap) framesIterator.next(); // logger.debug(frameMap.toXMLString(1000)); String frameType = (String) frameMap.get("type"); String sensorSerialNumber = (String) frameMap.get("serialNumber"); // handle each instrument type if (frameType.equals("HDR")) { logger.debug("This is a header frame. Skipping it."); } else if (frameType.equals("STX")) { try { // handle StorXSource StorXSource source = (StorXSource) sourceMap.get(sensorSerialNumber); // process the data using the StorXSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("SBE")) { try { // handle CTDSource CTDSource source = (CTDSource) sourceMap.get(sensorSerialNumber); // process the data using the CTDSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NLB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else if (frameType.equals("NDB")) { try { // handle ISUSSource ISUSSource source = (ISUSSource) sourceMap.get(sensorSerialNumber); // process the data using the ISUSSource // driver messageProcessed = source.process(this.xmlConfiguration, frameMap); } catch (ClassCastException cce) { } } else { logger.debug("The frame type " + frameType + " is not recognized. Skipping it."); } } // end while() if (this.sourceMap.get(loggerSerialNumber) != null) { // Note: Use message (not copiedMessage) when setting flags if (!messageProcessed) { logger.info("Failed to process message: " + "Message Number: " + message.getMessageNumber() + " " + "Logger Serial:" + loggerSerialNumber); // leave it in the inbox, flagged as seen (read) message.setFlag(Flags.Flag.SEEN, true); logger.debug("Saw message " + message.getMessageNumber()); } else { // message processed successfully. Create a by-month sub folder if it doesn't exist // Copy the message and flag it deleted Folder destination = processed.getFolder(destinationFolder); boolean created = destination.create(Folder.HOLDS_MESSAGES); inbox.copyMessages(new Message[] { message }, destination); message.setFlag(Flags.Flag.DELETED, true); logger.debug("Deleted message " + message.getMessageNumber()); } // end if() } else { logger.debug("There is no configuration information for " + "the logger serial number " + loggerSerialNumber + ". Please add the configuration to the " + "email.account.properties.xml configuration file."); } // end if() } else { logger.debug("This is not a data email since there is no " + "attachment. Skipping it. Subject: " + messageSubject); } // end if() } // end for() // expunge messages and close the mail server store once we're // done inbox.expunge(); this.mailStore.close(); } catch (MessagingException me) { try { this.mailStore.close(); } catch (MessagingException me2) { failed = true; return !failed; } logger.info( "There was an error reading the mail message. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IOException me) { try { this.mailStore.close(); } catch (MessagingException me3) { failed = true; return !failed; } logger.info("There was an I/O error reading the message part. The " + "message was: " + me.getMessage()); me.printStackTrace(); failed = true; return !failed; } catch (IllegalStateException ese) { try { this.mailStore.close(); } catch (MessagingException me4) { failed = true; return !failed; } logger.info("There was an error reading messages from the folder. The " + "message was: " + ese.getMessage()); failed = true; return !failed; } finally { try { this.mailStore.close(); } catch (MessagingException me2) { logger.debug("Couldn't close the mail store: " + me2.getMessage()); } } } return !failed; }
From source file:com.liferay.mail.imap.IMAPAccessor.java
protected void getFolders(List<Folder> allJxFolders, Folder[] jxFolders) { for (Folder jxFolder : jxFolders) { try {/*from w w w. j av a2 s. c om*/ int folderType = jxFolder.getType(); if ((folderType & Folder.HOLDS_MESSAGES) != 0) { allJxFolders.add(jxFolder); } if ((folderType & Folder.HOLDS_FOLDERS) != 0) { getFolders(allJxFolders, jxFolder.list()); } } catch (MessagingException me) { _log.error("Unable to get folder " + jxFolder.getFullName(), me); } } }
From source file:org.pentaho.di.job.entries.getpop.MailConnection.java
/** * Set destination folder/* w w w .j a v a2s. co m*/ * * @param foldername * destination foldername * @param createFolder * flag create folder if needed * @throws KettleException */ public void setDestinationFolder(String foldername, boolean createFolder) throws KettleException { try { String[] folderparts = foldername.split("/"); Folder f = this.getStore().getDefaultFolder(); // Open destination folder for (int i = 0; i < folderparts.length; i++) { f = f.getFolder(folderparts[i]); if (!f.exists()) { if (createFolder) { // Create folder f.create(Folder.HOLDS_MESSAGES); } else { throw new KettleException( BaseMessages.getString(PKG, "MailConnection.Error.FolderNotFound", foldername)); } } } this.destinationIMAPFolder = f; } catch (Exception e) { throw new KettleException(e); } }
From source file:net.wastl.webmail.server.WebMailSession.java
/** * Construct the folder subtree for the given folder and append it to * xml_parent.//from ww w. ja va 2s . 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
/** * Refresh Information about folders.//from w w w.ja va 2 s .c om * Tries to connect folders that are not yet connected. * * @doCount display message counts for user */ public void refreshFolderInformation(boolean subscribed_only, boolean doCount) { /* Right now, doCount corresponds exactly to subscribed_only. * When we add a user preference setting or one-time action, * to present messages from all folders, we will have * subscribed_only false and doCount true. */ //log.fatal("Invoking refreshFolderInformation(boolean, boolean)", //new Throwable("Thread Dump")); FOR DEBUGGING setEnv(); if (folders == null) folders = new Hashtable<String, Folder>(); Folder rootFolder = null; String cur_mh_id = ""; Enumeration mailhosts = user.mailHosts(); int max_depth = 0; int folderType; while (mailhosts.hasMoreElements()) { cur_mh_id = (String) mailhosts.nextElement(); MailHostData mhd = user.getMailHost(cur_mh_id); URLName url = new URLName(mhd.getHostURL()); Element mailhost = model.createMailhost(mhd.getName(), mhd.getID(), url.toString()); int depth = 0; try { rootFolder = getRootFolder(cur_mh_id); try { rootFolder.setSubscribed(true); } catch (MessagingException ex) { // Only IMAP supports subscription log.warn("Folder.setSubscribed failed. " + "Probably a non-supporting mail service: " + ex); } } catch (MessagingException ex) { mailhost.setAttribute("error", ex.getMessage()); log.warn("Failed to connect and get Root folder from (" + url + ')', ex); return; } try { depth = getFolderTree(rootFolder.getFolder("INBOX"), mailhost, subscribed_only, doCount); log.debug("Loaded INBOX folders below Root to a depth of " + depth); String extraFolderPath = ((imapBasedir == null) ? "~" : imapBasedir) + mhd.getLogin(); //String extraFolderPath = "/home/" + mhd.getLogin(); Folder nonInboxBase = rootFolder.getFolder(extraFolderPath); log.debug("Trying extra base dir " + nonInboxBase.getFullName()); if (nonInboxBase.exists()) { folderType = nonInboxBase.getType(); if ((folderType & Folder.HOLDS_MESSAGES) != 0) { // Can only Subscribe to Folders which may hold Msgs. nonInboxBase.setSubscribed(true); if (!nonInboxBase.isSubscribed()) log.error("A bug in JavaMail or in the server is " + "preventing subscription to '" + nonInboxBase.getFullName() + "' on '" + url + "'. Folders will not be visible."); } int extraDepth = extraDepth = getFolderTree(nonInboxBase, mailhost, subscribed_only, doCount); if (extraDepth > depth) depth = extraDepth; log.debug("Loaded additional folders from below " + nonInboxBase.getFullName() + " with max depth of " + extraDepth); } } catch (Exception ex) { if (!url.getProtocol().startsWith("pop")) mailhost.setAttribute("error", ex.getMessage()); log.warn("Failed to fetch child folders from (" + url + ')', ex); } if (depth > max_depth) max_depth = depth; model.addMailhost(mailhost); } model.setStateVar("max folder depth", (1 + max_depth) + ""); }
From source file:net.wastl.webmail.server.WebMailSession.java
public void addFolder(String toid, String name, boolean holds_messages, boolean holds_folders) throws MessagingException { Folder parent = getFolder(toid);//ww w . java 2 s . c om Folder folder = parent.getFolder(name); if (!folder.exists()) { int type = 0; if (holds_messages) { type += Folder.HOLDS_MESSAGES; } if (holds_folders) { type += Folder.HOLDS_FOLDERS; } folder.create(type); } // Should be called from FolderSetup Plugin //refreshFolderInformation(); }