1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * The contents of this file are subject to the terms of the Liferay Enterprise
5    * Subscription License ("License"). You may not use this file except in
6    * compliance with the License. You can obtain a copy of the License by
7    * contacting Liferay, Inc. See the License for the specific language governing
8    * permissions and limitations under the License, including but not limited to
9    * distribution rights of the Software.
10   *
11   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
12   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
13   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
15   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
16   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
17   * SOFTWARE.
18   */
19  
20  package com.liferay.portal.pop;
21  
22  import com.liferay.portal.kernel.job.IntervalJob;
23  import com.liferay.portal.kernel.job.JobExecutionContext;
24  import com.liferay.portal.kernel.log.Log;
25  import com.liferay.portal.kernel.log.LogFactoryUtil;
26  import com.liferay.portal.kernel.pop.MessageListener;
27  import com.liferay.portal.kernel.util.GetterUtil;
28  import com.liferay.portal.kernel.util.StringPool;
29  import com.liferay.portal.kernel.util.Time;
30  import com.liferay.portal.util.PropsKeys;
31  import com.liferay.portal.util.PropsUtil;
32  import com.liferay.util.mail.MailEngine;
33  
34  import java.util.Iterator;
35  import java.util.List;
36  
37  import javax.mail.Address;
38  import javax.mail.Flags;
39  import javax.mail.Folder;
40  import javax.mail.Message.RecipientType;
41  import javax.mail.Message;
42  import javax.mail.MessagingException;
43  import javax.mail.Session;
44  import javax.mail.Store;
45  import javax.mail.internet.InternetAddress;
46  
47  /**
48   * <a href="POPNotificationsJob.java.html"><b><i>View Source</i></b></a>
49   *
50   * @author Brian Wing Shun Chan
51   *
52   */
53  public class POPNotificationsJob implements IntervalJob {
54  
55      public static final long INTERVAL = GetterUtil.getLong(PropsUtil.get(
56          PropsKeys.POP_SERVER_NOTIFICATIONS_INTERVAL)) * Time.MINUTE;
57  
58      public void execute(JobExecutionContext context) {
59          try {
60              if (_log.isDebugEnabled()) {
61                  _log.debug("Executing");
62              }
63  
64              pollPopServer();
65          }
66          catch (Exception e) {
67              _log.error(e, e);
68  
69              _store = null;
70              _inboxFolder = null;
71          }
72      }
73  
74      public long getInterval() {
75          return INTERVAL;
76      }
77  
78      protected String getEmailAddress(Address[] addresses) {
79          if ((addresses == null) || (addresses.length == 0)) {
80              return StringPool.BLANK;
81          }
82  
83          InternetAddress internetAddress = (InternetAddress)addresses[0];
84  
85          return internetAddress.getAddress();
86      }
87  
88      protected void initInboxFolder() throws Exception {
89          if ((_inboxFolder == null) || !_inboxFolder.isOpen()) {
90              initStore();
91  
92              Folder defaultFolder = _store.getDefaultFolder();
93  
94              Folder[] folders = defaultFolder.list();
95  
96              if (folders.length == 0) {
97                  throw new MessagingException("Inbox not found");
98              }
99              else {
100                 _inboxFolder = folders[0];
101 
102                 _inboxFolder.open(Folder.READ_WRITE);
103             }
104         }
105     }
106 
107     protected void initStore() throws Exception {
108         if ((_store == null) || !_store.isConnected()) {
109             Session session = MailEngine.getSession();
110 
111             _store = session.getStore("pop3");
112 
113             String popHost = session.getProperty("mail.pop3.host");
114             String smtpUser = session.getProperty("mail.smtp.user");
115             String smtpPassword = session.getProperty("mail.smtp.password");
116 
117             _store.connect(popHost, smtpUser, smtpPassword);
118         }
119     }
120 
121     protected void nostifyListeners(
122             List<MessageListener> listeners, Message message)
123         throws Exception {
124 
125         String from = getEmailAddress(message.getFrom());
126         String recipient = getEmailAddress(
127             message.getRecipients(RecipientType.TO));
128 
129         if (_log.isDebugEnabled()) {
130             _log.debug("From " + from);
131             _log.debug("Recipient " + recipient);
132         }
133 
134         Iterator<MessageListener> itr = listeners.iterator();
135 
136         while (itr.hasNext()) {
137             MessageListener messageListener = itr.next();
138 
139             try {
140                 if (messageListener.accept(from, recipient, message)) {
141                     messageListener.deliver(from, recipient, message);
142                 }
143             }
144             catch (Exception e) {
145                 _log.error(e, e);
146             }
147         }
148     }
149 
150     protected void nostifyListeners(Message[] messages) throws Exception {
151         if (_log.isDebugEnabled()) {
152             _log.debug("Messages " + messages.length);
153         }
154 
155         List<MessageListener> listeners = POPServerUtil.getListeners();
156 
157         for (int i = 0; i < messages.length; i++) {
158             Message message = messages[i];
159 
160             if (_log.isDebugEnabled()) {
161                 _log.debug("Message " + message);
162             }
163 
164             nostifyListeners(listeners, message);
165         }
166     }
167 
168     protected void pollPopServer() throws Exception {
169         initInboxFolder();
170 
171         Message[] messages = _inboxFolder.getMessages();
172 
173         try {
174             nostifyListeners(messages);
175         }
176         finally {
177             if (_log.isDebugEnabled()) {
178                 _log.debug("Deleting messages");
179             }
180 
181             _inboxFolder.setFlags(
182                 messages, new Flags(Flags.Flag.DELETED), true);
183 
184             _inboxFolder.close(true);
185         }
186     }
187 
188     private static Log _log = LogFactoryUtil.getLog(POPNotificationsJob.class);
189 
190     private Store _store;
191     private Folder _inboxFolder;
192 
193 }