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