View Javadoc

1   /*
2    * Copyright 2007 the original author or authors.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *      http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package org.springframework.ws.transport.mail.monitor;
18  
19  import javax.mail.FetchProfile;
20  import javax.mail.Flags;
21  import javax.mail.Folder;
22  import javax.mail.Message;
23  import javax.mail.MessagingException;
24  import javax.mail.search.AndTerm;
25  import javax.mail.search.FlagTerm;
26  import javax.mail.search.SearchTerm;
27  
28  import org.apache.commons.logging.Log;
29  import org.apache.commons.logging.LogFactory;
30  
31  /**
32   * Abstract base class for the {@link MonitoringStrategy} interface. Exposes a {@link #setDeleteMessages(boolean)
33   * deleteMessages} property, and includes a basic workflow for message monitoring.
34   *
35   * @author Arjen Poutsma
36   * @since 1.5.0
37   */
38  public abstract class AbstractMonitoringStrategy implements MonitoringStrategy {
39  
40      /** Logger available to subclasses. */
41      protected final Log logger = LogFactory.getLog(getClass());
42  
43      private boolean deleteMessages = true;
44  
45      /**
46       * Sets whether messages should be marked as {@link javax.mail.Flags.Flag#DELETED DELETED} after they have been
47       * read. Default is <code>true</code>.
48       */
49      public void setDeleteMessages(boolean deleteMessages) {
50          this.deleteMessages = deleteMessages;
51      }
52  
53      public int getFolderOpenMode() {
54          return deleteMessages ? Folder.READ_WRITE : Folder.READ_ONLY;
55      }
56  
57      /**
58       * Monitors the given folder, and returns any new messages when they arrive. This implementation calls {@link
59       * #waitForNewMessages(Folder)}, then searches for new messages using {@link #searchForNewMessages(Folder)}, fetches
60       * the messages using {@link #fetchMessages(Folder, Message[])}, and finally {@link #setDeleteMessages(boolean)
61       * deletes} the messages, if {@link #setDeleteMessages(boolean) deleteMessages} is <code>true</code>.
62       *
63       * @param folder the folder to monitor
64       * @return the new messages
65       * @throws MessagingException   in case of JavaMail errors
66       * @throws InterruptedException when a thread is interrupted
67       */
68      public final Message[] monitor(Folder folder) throws MessagingException, InterruptedException {
69          waitForNewMessages(folder);
70          Message[] messages = searchForNewMessages(folder);
71          if (logger.isDebugEnabled()) {
72              logger.debug("Found " + messages.length + " new messages");
73          }
74          if (messages.length > 0) {
75              fetchMessages(folder, messages);
76          }
77          if (deleteMessages) {
78              deleteMessages(folder, messages);
79          }
80          return messages;
81      }
82  
83      /**
84       * Template method that blocks until new messages arrive in the given folder. Typical implementations use {@link
85       * Thread#sleep(long)} or the IMAP IDLE command.
86       *
87       * @param folder the folder to monitor
88       * @throws MessagingException   in case of JavaMail errors
89       * @throws InterruptedException when a thread is interrupted
90       */
91      protected abstract void waitForNewMessages(Folder folder) throws MessagingException, InterruptedException;
92  
93      /**
94       * Retrieves new messages from the given folder. This implementation creates a {@link SearchTerm} that searches for
95       * all messages in the folder that are {@link javax.mail.Flags.Flag#RECENT RECENT}, not {@link
96       * javax.mail.Flags.Flag#ANSWERED ANSWERED}, and not {@link javax.mail.Flags.Flag#DELETED DELETED}. The search term
97       * is used to {@link Folder#search(SearchTerm) search} for new messages.
98       *
99       * @param folder the folder to retrieve new messages from
100      * @return the new messages
101      * @throws MessagingException in case of JavaMail errors
102      */
103     protected Message[] searchForNewMessages(Folder folder) throws MessagingException {
104         if (!folder.isOpen()) {
105             return new Message[0];
106         }
107         Flags supportedFlags = folder.getPermanentFlags();
108         SearchTerm searchTerm = null;
109         if (supportedFlags != null) {
110             if (supportedFlags.contains(Flags.Flag.RECENT)) {
111                 searchTerm = new FlagTerm(new Flags(Flags.Flag.RECENT), true);
112             }
113             if (supportedFlags.contains(Flags.Flag.ANSWERED)) {
114                 FlagTerm answeredTerm = new FlagTerm(new Flags(Flags.Flag.ANSWERED), false);
115                 if (searchTerm == null) {
116                     searchTerm = answeredTerm;
117                 }
118                 else {
119                     searchTerm = new AndTerm(searchTerm, answeredTerm);
120                 }
121             }
122             if (supportedFlags.contains(Flags.Flag.DELETED)) {
123                 FlagTerm deletedTerm = new FlagTerm(new Flags(Flags.Flag.DELETED), false);
124                 if (searchTerm == null) {
125                     searchTerm = deletedTerm;
126                 }
127                 else {
128                     searchTerm = new AndTerm(searchTerm, deletedTerm);
129                 }
130             }
131         }
132         return searchTerm != null ? folder.search(searchTerm) : folder.getMessages();
133     }
134 
135     /**
136      * Fetches the specified messages from the specified folder. Default implementation {@link Folder#fetch(Message[],
137      * FetchProfile) fetches} every {@link javax.mail.FetchProfile.Item}.
138      *
139      * @param folder   the folder to fetch messages from
140      * @param messages the messages to fetch
141      * @throws MessagingException in case of JavMail errors
142      */
143     protected void fetchMessages(Folder folder, Message[] messages) throws MessagingException {
144         FetchProfile contentsProfile = new FetchProfile();
145         contentsProfile.add(FetchProfile.Item.ENVELOPE);
146         contentsProfile.add(FetchProfile.Item.CONTENT_INFO);
147         contentsProfile.add(FetchProfile.Item.FLAGS);
148         folder.fetch(messages, contentsProfile);
149     }
150 
151     /**
152      * Deletes the given messages from the given folder. Only invoked when {@link #setDeleteMessages(boolean)} is
153      * <code>true</code>.
154      *
155      * @param folder   the folder to delete messages from
156      * @param messages the messages to delete
157      * @throws MessagingException in case of JavaMail errors
158      */
159     protected void deleteMessages(Folder folder, Message[] messages) throws MessagingException {
160         for (int i = 0; i < messages.length; i++) {
161             messages[i].setFlag(Flags.Flag.DELETED, true);
162         }
163     }
164 }