List of usage examples for javax.mail Folder getFullName
public abstract String getFullName();
From source file:de.saly.elasticsearch.imap.AbstractIMAPRiverUnitTest.java
protected void renameMailbox(final Properties props, final String folderName, final String user, final String password) throws MessagingException { final Store store = Session.getInstance(props).getStore(); store.connect(user, password);// ww w .j a v a2s . c o m checkStoreForTestConnection(store); final Folder f = store.getFolder(folderName); f.renameTo(store.getFolder("renamed_from_" + folderName)); logger.info("Renamed " + f.getFullName()); store.close(); }
From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java
protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException { logger.debug("fetch() - pattern: {}, folderName: {}", pattern, folderName); final Store store = Session.getInstance(props).getStore(); store.connect(user, password);//w w w . jav a2s .co m try { for (final String fol : mailDestination.getFolderNames()) { if (store.getFolder(fol).exists()) { logger.debug("{} exists", fol); } else { logger.info( "Folder {} does not exist on the server, will remove it (and its content) also locally", fol); final RiverState riverState = stateManager.getRiverState(store.getFolder(fol)); riverState.setExists(false); stateManager.setRiverState(riverState); try { mailDestination.clearDataForFolder(fol); } catch (final Exception e) { stateManager.onError("Unable to clean data for stale folder", store.getFolder(fol), e); } } } } catch (final IndexMissingException ime) { logger.debug(ime.toString()); } catch (final Exception e) { logger.error("Error checking for stale folders", e); } final boolean isRoot = StringUtils.isEmpty(folderName); final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName); try { if (!folder.exists()) { logger.error("Folder {} does not exist on the server", folder.getFullName()); return; } logger.debug("folderName: {} is root: {}", folderName, isRoot); /*if (logger.isDebugEnabled() && store instanceof IMAPStore) { IMAPStore imapStore = (IMAPStore) store; logger.debug("IMAP server capability info"); logger.debug("IMAP4rev1: " + imapStore.hasCapability("IMAP4rev1")); logger.debug("IDLE: " + imapStore.hasCapability("IDLE")); logger.debug("ID: " + imapStore.hasCapability("ID")); logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS")); logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN")); logger.debug("NAMESPACE: " + imapStore.hasCapability("NAMESPACE")); logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY")); logger.debug("CONDSTORE: " + imapStore.hasCapability("CONDSTORE")); logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC")); logger.debug("STATUS: " + imapStore.hasCapability("STATUS")); }*/ if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) { logger.info(folder.getFullName() + " does not match pattern " + pattern.toString()); return; } IMAPUtils.open(folder); recurseFolders(folder, pattern); } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
From source file:com.cubusmail.mail.imap.IMAPMailbox.java
/** * @throws MessagingException/* w w w.jav a 2 s. co m*/ */ private void loadMailFolder() throws MessagingException { logger.debug("loading folder tree..."); long millis = System.currentTimeMillis(); this.mailFolderMap.clear(); this.mailFolderList.clear(); Folder defaultFolder = this.store.getDefaultFolder(); this.folderSeparator = defaultFolder.getSeparator(); // read all folders to a map List<String> topFolderNames = new ArrayList<String>(); Folder[] allFolders = defaultFolder.list("*"); if (allFolders != null && allFolders.length > 0) { for (Folder folder : allFolders) { this.mailFolderMap.put(folder.getFullName(), createMailFolder(folder)); if (SessionManager.get().getPreferences().getInboxFolderName().equals(folder.getFullName())) { topFolderNames.add(0, SessionManager.get().getPreferences().getInboxFolderName()); } else { String folderName = folder.getFullName(); if (!StringUtils.isEmpty(this.personalNameSpace) && folderName.startsWith(this.personalNameSpace)) { folderName = StringUtils.substringAfter(folderName, this.personalNameSpace); } if (StringUtils.countMatches(folderName, String.valueOf(getFolderSeparator())) == 0) { topFolderNames.add(folder.getFullName()); } } } } // build the tree structure for (String folderName : topFolderNames) { IMailFolder mailFolder = this.mailFolderMap.get(folderName); this.mailFolderList.add(mailFolder); if (!SessionManager.get().getPreferences().getInboxFolderName().equals(folderName) && mailFolder.hasChildren()) { mailFolder.setSubfolders(getSubfolders(mailFolder)); } } logger.debug("...finish: " + (System.currentTimeMillis() - millis) + "ms"); }
From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java
protected void fetch(final Pattern pattern, final String folderName) throws MessagingException, IOException { logger.debug("fetch() - pattern: {}, folderName: {}, user: {}", pattern, folderName, user); final Store store = Session.getInstance(props).getStore(); store.connect(user, password);/*from w w w. j a va2 s . co m*/ if (deleteExpungedMessages) { try { for (final String fol : mailDestination.getFolderNames()) { if (store.getFolder(fol).exists()) { logger.debug("{} exists for {}", fol, user); } else { logger.info( "Folder {} does not exist for {} on the server, will remove it (and its content) also locally", user, fol); final State riverState = stateManager.getRiverState(store.getFolder(fol)); riverState.setExists(false); stateManager.setRiverState(riverState); try { mailDestination.clearDataForFolder(store.getFolder(fol)); } catch (final Exception e) { stateManager.onError("Unable to clean data for stale folder for " + user, store.getFolder(fol), e); } } } } /*catch (final IndexMissingException ime) { logger.debug(ime.toString()); //TODO 2.0 check } */ catch (final Exception e) { logger.error("Error checking for stale folders", e); } } final boolean isRoot = StringUtils.isEmpty(folderName); final Folder folder = isRoot ? store.getDefaultFolder() : store.getFolder(folderName); try { if (!folder.exists()) { logger.error("Folder {} does not exist on the server", folder.getFullName()); return; } logger.debug("folderName: {} is root: {}", folderName, isRoot); /*if (logger.isDebugEnabled() && store instanceof IMAPStore) { IMAPStore imapStore = (IMAPStore) store; logger.debug("IMAP server capability info"); logger.debug("IMAP4rev1: " + imapStore.hasCapability("IMAP4rev1")); logger.debug("IDLE: " + imapStore.hasCapability("IDLE")); logger.debug("ID: " + imapStore.hasCapability("ID")); logger.debug("UIDPLUS: " + imapStore.hasCapability("UIDPLUS")); logger.debug("CHILDREN: " + imapStore.hasCapability("CHILDREN")); logger.debug("NAMESPACE: " + imapStore.hasCapability("NAMESPACE")); logger.debug("NOTIFY: " + imapStore.hasCapability("NOTIFY")); logger.debug("CONDSTORE: " + imapStore.hasCapability("CONDSTORE")); logger.debug("QRESYNC: " + imapStore.hasCapability("QRESYNC")); logger.debug("STATUS: " + imapStore.hasCapability("STATUS")); }*/ if (pattern != null && !isRoot && !pattern.matcher(folder.getFullName()).matches()) { logger.debug(folder.getFullName() + " does not match pattern " + pattern.toString()); return; } IMAPUtils.open(folder); recurseFolders(folder, pattern); } finally { IMAPUtils.close(folder); IMAPUtils.close(store); } }
From source file:com.cubusmail.server.mail.imap.IMAPMailbox.java
/** * @throws MessagingException//w ww . j a v a2s .com */ private void loadMailFolder() throws MessagingException { log.debug("loading folder tree..."); long millis = System.currentTimeMillis(); this.mailFolderMap.clear(); this.mailFolderList.clear(); Folder defaultFolder = this.store.getDefaultFolder(); this.folderSeparator = defaultFolder.getSeparator(); // read all folders to a map List<String> topFolderNames = new ArrayList<String>(); Folder[] allFolders = defaultFolder.list("*"); if (allFolders != null && allFolders.length > 0) { for (Folder folder : allFolders) { this.mailFolderMap.put(folder.getFullName(), createMailFolder(folder)); if (SessionManager.get().getPreferences().getInboxFolderName().equals(folder.getFullName())) { topFolderNames.add(0, SessionManager.get().getPreferences().getInboxFolderName()); } else { String folderName = folder.getFullName(); if (!StringUtils.isEmpty(this.personalNameSpace) && folderName.startsWith(this.personalNameSpace)) { folderName = StringUtils.substringAfter(folderName, this.personalNameSpace); } if (StringUtils.countMatches(folderName, String.valueOf(getFolderSeparator())) == 0) { topFolderNames.add(folder.getFullName()); } } } } // build the tree structure for (String folderName : topFolderNames) { IMailFolder mailFolder = this.mailFolderMap.get(folderName); this.mailFolderList.add(mailFolder); if (mailFolder.hasChildren()) { mailFolder.setSubfolders(getSubfolders(mailFolder)); } } log.debug("...finish: " + (System.currentTimeMillis() - millis) + "ms"); }
From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void fetch(final Folder folder) throws MessagingException, IOException { if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) { logger.warn("Folder {} cannot hold messages", folder.getFullName()); return;/*w w w. j a v a 2s.c o m*/ } final int messageCount = folder.getMessageCount(); final UIDFolder uidfolder = (UIDFolder) folder; final long servervalidity = uidfolder.getUIDValidity(); final RiverState riverState = stateManager.getRiverState(folder); final Long localvalidity = riverState.getUidValidity(); logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount); logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity); if (localvalidity == null || localvalidity.longValue() != servervalidity) { logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity); if (localvalidity != null) { mailDestination.clearDataForFolder(folder.getFullName()); } final ProcessResult result = process(messageCount, 1, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { if (messageCount == 0) { logger.debug("Folder {} is empty", folder.getFullName()); } else { if (withFlagSync) { // detect flag change final Message[] flagMessages = folder.getMessages(); folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID); for (final Message message : flagMessages) { try { final long uid = ((UIDFolder) message.getFolder()).getUID(message); final String id = uid + "::" + message.getFolder().getURLName(); final int storedHashcode = mailDestination.getFlaghashcode(id); if (storedHashcode == -1) { // New mail which is not indexed yet continue; } final int flagHashcode = message.getFlags().hashCode(); if (flagHashcode != storedHashcode) { // flags change for this message, must update mailDestination.onMessage(message); if (logger.isDebugEnabled()) { logger.debug("Update " + id + " because of flag change"); } } } catch (final Exception e) { logger.error("Error detecting flagchanges for message " + ((MimeMessage) message).getMessageID(), e); stateManager.onError("Error detecting flagchanges", message, e); } } } final long highestUID = riverState.getLastUid(); // this uid is // already // processed logger.debug("highestUID: {}", highestUID); final Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID); // msgnew.size is always >= 1 if (highestUID > 0 && uidfolder.getUID(msgsnew[0]) <= highestUID) { // msgsnew = (Message[]) ArrayUtils.remove(msgsnew, 0); } if (msgsnew.length > 0) { logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName()); final int start = msgsnew[0].getMessageNumber(); final ProcessResult result = process(messageCount, start, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { logger.debug("no new messages"); } } // check for expunged/deleted messages final Set<Long> serverMailSet = new HashSet<Long>(); final long oldmailUid = riverState.getLastUid(); logger.debug("oldmailuid {}", oldmailUid); final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid); folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID); for (final Message m : msgsold) { try { final long uid = uidfolder.getUID(m); serverMailSet.add(uid); } catch (final Exception e) { stateManager.onError("Unable to handle old message ", m, e); logger.error("Unable to handle old message due to {}", e, e.toString()); IMAPUtils.open(folder); } } final Set localMailSet = new HashSet( mailDestination.getCurrentlyStoredMessageUids(folder.getFullName(), false)); logger.debug("Check now " + localMailSet.size() + " server mails for expunge"); localMailSet.removeAll(serverMailSet); // localMailSet has now the ones that are not on server logger.info( localMailSet.size() + " messages were locally deleted, because they are expunged on server."); mailDestination.onMessageDeletes(localMailSet, folder.getFullName(), false); } }
From source file:de.saly.elasticsearch.importer.imap.mailsource.ParallelPollingIMAPMailSource.java
@SuppressWarnings({ "rawtypes", "unchecked" }) protected void fetch(final Folder folder) throws MessagingException, IOException { if ((folder.getType() & Folder.HOLDS_MESSAGES) == 0) { logger.warn("Folder {} cannot hold messages", folder.getFullName()); return;//from ww w . ja va 2 s .c o m } final int messageCount = folder.getMessageCount(); final UIDFolder uidfolder = (UIDFolder) folder; final long servervalidity = uidfolder.getUIDValidity(); final State riverState = stateManager.getRiverState(folder); final Long localvalidity = riverState.getUidValidity(); logger.info("Fetch mails from folder {} ({})", folder.getURLName().toString(), messageCount); logger.debug("Server uid validity: {}, Local uid validity: {}", servervalidity, localvalidity); if (localvalidity == null || localvalidity.longValue() != servervalidity) { logger.debug("UIDValidity fail, full resync " + localvalidity + "!=" + servervalidity); if (localvalidity != null) { mailDestination.clearDataForFolder(folder); } final ProcessResult result = process(messageCount, 1, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { if (messageCount == 0) { logger.debug("Folder {} is empty", folder.getFullName()); } else { if (withFlagSync) { // detect flag change final Message[] flagMessages = folder.getMessages(); folder.fetch(flagMessages, IMAPUtils.FETCH_PROFILE_FLAGS_UID); for (final Message message : flagMessages) { try { final long uid = ((UIDFolder) message.getFolder()).getUID(message); final String id = uid + "::" + message.getFolder().getURLName(); final int storedHashcode = mailDestination.getFlaghashcode(id); if (storedHashcode == -1) { // New mail which is not indexed yet continue; } final int flagHashcode = message.getFlags().hashCode(); if (flagHashcode != storedHashcode) { // flags change for this message, must update mailDestination.onMessage(message); if (logger.isDebugEnabled()) { logger.debug("Update " + id + " because of flag change"); } } } catch (final Exception e) { logger.error("Error detecting flagchanges for message " + ((MimeMessage) message).getMessageID(), e); stateManager.onError("Error detecting flagchanges", message, e); } } } long highestUID = riverState.getLastUid(); // this uid is // already // processed logger.debug("highestUID: {}", highestUID); if (highestUID < 1) { logger.error("highestUID: {} not valid, set it to 1", highestUID); highestUID = 1; } Message[] msgsnew = uidfolder.getMessagesByUID(highestUID, UIDFolder.LASTUID); if (msgsnew.length > 0) { System.out.println("lastuid: " + uidfolder.getUID(msgsnew[msgsnew.length - 1])); // msgnew.size is always >= 1 if (highestUID > 1 && uidfolder.getUID(msgsnew[msgsnew.length - 1]) <= highestUID) { msgsnew = (Message[]) ArrayUtils.remove(msgsnew, msgsnew.length - 1); } if (msgsnew.length > 0) { logger.info("{} new messages in folder {}", msgsnew.length, folder.getFullName()); final int start = msgsnew[0].getMessageNumber(); final ProcessResult result = process(messageCount, start, folder.getFullName()); riverState.setLastCount(result.getProcessedCount()); if (result.getProcessedCount() > 0) { riverState.setLastIndexed(new Date()); } if (result.getProcessedCount() > 0) { riverState.setLastTook(result.getTook()); } riverState.setLastSchedule(new Date()); if (result.getProcessedCount() > 0 && result.getHighestUid() > 0) { riverState.setLastUid(result.getHighestUid()); } riverState.setUidValidity(servervalidity); stateManager.setRiverState(riverState); logger.info("Not initiailly processed {} mails for folder {}", result.getProcessedCount(), folder.getFullName()); logger.debug("Processed result {}", result.toString()); } else { logger.debug("no new messages"); } } else { logger.debug("no new messages"); } } // check for expunged/deleted messages final Set<Long> serverMailSet = new HashSet<Long>(); final long oldmailUid = riverState.getLastUid(); logger.debug("oldmailuid {}", oldmailUid); final Message[] msgsold = uidfolder.getMessagesByUID(1, oldmailUid); folder.fetch(msgsold, IMAPUtils.FETCH_PROFILE_UID); for (final Message m : msgsold) { try { final long uid = uidfolder.getUID(m); serverMailSet.add(uid); } catch (final Exception e) { stateManager.onError("Unable to handle old message ", m, e); logger.error("Unable to handle old message due to {}", e, e.toString()); IMAPUtils.open(folder); } } if (deleteExpungedMessages) { final Set localMailSet = new HashSet(mailDestination.getCurrentlyStoredMessageUids(folder)); logger.debug("Check now " + localMailSet.size() + " server mails for expunge"); localMailSet.removeAll(serverMailSet); // localMailSet has now the ones that are not on server logger.info(localMailSet.size() + " messages were locally deleted, because they are expunged on server."); mailDestination.onMessageDeletes(localMailSet, folder); } } }
From source file:com.liferay.mail.imap.IMAPAccessor.java
protected Folder getFolder(long folderId) throws MessagingException, PortalException { Store store = _imapConnection.getStore(true); com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId); return store.getFolder(folder.getFullName()); }
From source file:com.liferay.mail.imap.IMAPAccessor.java
public void storeEnvelopes(long folderId, Folder jxFolder, Message[] jxMessages) throws PortalException { StopWatch stopWatch = new StopWatch(); stopWatch.start();//from w ww . jav a 2s . co m try { FetchProfile fetchProfile = new FetchProfile(); fetchProfile.add(UIDFolder.FetchProfileItem.ENVELOPE); fetchProfile.add(UIDFolder.FetchProfileItem.FLAGS); fetchProfile.add(UIDFolder.FetchProfileItem.UID); jxFolder.fetch(jxMessages, fetchProfile); for (Message jxMessage : jxMessages) { String sender = InternetAddressUtil.toString(jxMessage.getFrom()); String to = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.TO)); String cc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.CC)); String bcc = InternetAddressUtil.toString(jxMessage.getRecipients(RecipientType.BCC)); Date sentDate = jxMessage.getSentDate(); String subject = jxMessage.getSubject(); String flags = getFlags(jxMessage); long remoteMessageId = getUID(jxFolder, jxMessage); String contentType = jxMessage.getContentType(); try { MessageLocalServiceUtil.getMessage(folderId, remoteMessageId); } catch (NoSuchMessageException nsme) { MessageLocalServiceUtil.addMessage(_user.getUserId(), folderId, sender, to, cc, bcc, sentDate, subject, StringPool.BLANK, flags, remoteMessageId, contentType); } } com.liferay.mail.model.Folder folder = FolderLocalServiceUtil.getFolder(folderId); FolderLocalServiceUtil.updateFolder(folderId, folder.getFullName(), folder.getDisplayName(), jxFolder.getMessageCount()); } catch (MessagingException me) { throw new MailException(me); } if (_log.isDebugEnabled()) { stopWatch.stop(); _log.debug("Downloaded " + jxMessages.length + " messages from folder " + jxFolder.getFullName() + " completed in " + stopWatch.getTime() + " ms"); } }
From source file:de.saly.elasticsearch.mailsource.ParallelPollingIMAPMailSource.java
protected void recurseFolders(final Folder folder, final Pattern pattern) throws MessagingException, IOException { if (folder != null) { if (es == null || es.isShutdown() || es.isTerminated() || Thread.currentThread().isInterrupted()) { logger.warn("Stop processing of mails due to mail source is closed"); return; }//ww w. j a va 2s . c om if ((folder.getType() & Folder.HOLDS_MESSAGES) != 0) { if (pattern != null && !pattern.matcher(folder.getFullName()).matches()) { logger.info("Pattern {} does not match {}", pattern.pattern(), folder.getFullName()); return; } IMAPUtils.open(folder); try { fetch(folder); } finally { IMAPUtils.close(folder); logger.debug("fetch {} done", folder.getFullName()); } } if ((folder.getType() & Folder.HOLDS_FOLDERS) != 0) { for (final Folder subfolder : folder.list()) { recurseFolders(subfolder, pattern); } } } }