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