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.mail.Account;
30  import com.liferay.portal.kernel.pop.MessageListener;
31  import com.liferay.portal.kernel.util.GetterUtil;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.Time;
34  import com.liferay.portal.kernel.util.Validator;
35  import com.liferay.portal.util.PropsKeys;
36  import com.liferay.portal.util.PropsUtil;
37  import com.liferay.util.mail.MailEngine;
38  
39  import java.util.Iterator;
40  import java.util.List;
41  
42  import javax.mail.Address;
43  import javax.mail.Flags;
44  import javax.mail.Folder;
45  import javax.mail.Message.RecipientType;
46  import javax.mail.Message;
47  import javax.mail.MessagingException;
48  import javax.mail.Session;
49  import javax.mail.Store;
50  import javax.mail.internet.InternetAddress;
51  
52  /**
53   * <a href="POPNotificationsJob.java.html"><b><i>View Source</i></b></a>
54   *
55   * @author Brian Wing Shun Chan
56   *
57   */
58  public class POPNotificationsJob implements IntervalJob {
59  
60      public static final long INTERVAL = GetterUtil.getLong(PropsUtil.get(
61          PropsKeys.POP_SERVER_NOTIFICATIONS_INTERVAL)) * Time.MINUTE;
62  
63      public void execute(JobExecutionContext context) {
64          try {
65              if (_log.isDebugEnabled()) {
66                  _log.debug("Executing");
67              }
68  
69              pollPopServer();
70          }
71          catch (Exception e) {
72              _log.error(e, e);
73  
74              _store = null;
75              _inboxFolder = null;
76          }
77      }
78  
79      public long getInterval() {
80          return INTERVAL;
81      }
82  
83      protected String getEmailAddress(Address[] addresses) {
84          if ((addresses == null) || (addresses.length == 0)) {
85              return StringPool.BLANK;
86          }
87  
88          InternetAddress internetAddress = (InternetAddress)addresses[0];
89  
90          return internetAddress.getAddress();
91      }
92  
93      protected void initInboxFolder() throws Exception {
94          if ((_inboxFolder == null) || !_inboxFolder.isOpen()) {
95              initStore();
96  
97              Folder defaultFolder = _store.getDefaultFolder();
98  
99              Folder[] folders = defaultFolder.list();
100 
101             if (folders.length == 0) {
102                 throw new MessagingException("Inbox not found");
103             }
104             else {
105                 _inboxFolder = folders[0];
106 
107                 _inboxFolder.open(Folder.READ_WRITE);
108             }
109         }
110     }
111 
112     protected void initStore() throws Exception {
113         if ((_store == null) || !_store.isConnected()) {
114             Session session = MailEngine.getSession();
115 
116             String storeProtocol = GetterUtil.getString(
117                 session.getProperty("mail.store.protocol"));
118 
119             if (!storeProtocol.equals(Account.PROTOCOL_POPS)) {
120                 storeProtocol = Account.PROTOCOL_POP;
121             }
122 
123             _store = session.getStore(storeProtocol);
124 
125             String prefix = "mail." + storeProtocol + ".";
126 
127             String host = session.getProperty(prefix + "host");
128 
129             String user = session.getProperty(prefix + "user");
130 
131             if (Validator.isNull(user)) {
132                 user = session.getProperty("mail.smtp.user");
133             }
134 
135             String password = session.getProperty(prefix + "password");
136 
137             if (Validator.isNull(password)) {
138                 password = session.getProperty("mail.smtp.password");
139             }
140 
141             _store.connect(host, user, password);
142         }
143     }
144 
145     protected void nostifyListeners(
146             List<MessageListener> listeners, Message message)
147         throws Exception {
148 
149         String from = getEmailAddress(message.getFrom());
150         String recipient = getEmailAddress(
151             message.getRecipients(RecipientType.TO));
152 
153         if (_log.isDebugEnabled()) {
154             _log.debug("From " + from);
155             _log.debug("Recipient " + recipient);
156         }
157 
158         Iterator<MessageListener> itr = listeners.iterator();
159 
160         while (itr.hasNext()) {
161             MessageListener messageListener = itr.next();
162 
163             try {
164                 if (messageListener.accept(from, recipient, message)) {
165                     messageListener.deliver(from, recipient, message);
166                 }
167             }
168             catch (Exception e) {
169                 _log.error(e, e);
170             }
171         }
172     }
173 
174     protected void nostifyListeners(Message[] messages) throws Exception {
175         if (_log.isDebugEnabled()) {
176             _log.debug("Messages " + messages.length);
177         }
178 
179         List<MessageListener> listeners = POPServerUtil.getListeners();
180 
181         for (int i = 0; i < messages.length; i++) {
182             Message message = messages[i];
183 
184             if (_log.isDebugEnabled()) {
185                 _log.debug("Message " + message);
186             }
187 
188             nostifyListeners(listeners, message);
189         }
190     }
191 
192     protected void pollPopServer() throws Exception {
193         initInboxFolder();
194 
195         Message[] messages = _inboxFolder.getMessages();
196 
197         try {
198             nostifyListeners(messages);
199         }
200         finally {
201             if (_log.isDebugEnabled()) {
202                 _log.debug("Deleting messages");
203             }
204 
205             _inboxFolder.setFlags(
206                 messages, new Flags(Flags.Flag.DELETED), true);
207 
208             _inboxFolder.close(true);
209         }
210     }
211 
212     private static Log _log = LogFactoryUtil.getLog(POPNotificationsJob.class);
213 
214     private Store _store;
215     private Folder _inboxFolder;
216 
217 }