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.pop.MessageListener;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.StringPool;
30  import com.liferay.portal.kernel.util.Time;
31  import com.liferay.portal.util.PropsKeys;
32  import com.liferay.portal.util.PropsUtil;
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          PropsKeys.POP_SERVER_NOTIFICATIONS_INTERVAL)) * Time.MINUTE;
61  
62      public void execute(JobExecutionContext context) {
63          try {
64              if (_log.isDebugEnabled()) {
65                  _log.debug("Executing");
66              }
67  
68              pollPopServer();
69          }
70          catch (Exception e) {
71              _log.error(e, e);
72  
73              _store = null;
74              _inboxFolder = null;
75          }
76      }
77  
78      public long getInterval() {
79          return INTERVAL;
80      }
81  
82      protected String getEmailAddress(Address[] addresses) {
83          if ((addresses == null) || (addresses.length == 0)) {
84              return StringPool.BLANK;
85          }
86  
87          InternetAddress internetAddress = (InternetAddress)addresses[0];
88  
89          return internetAddress.getAddress();
90      }
91  
92      protected void initInboxFolder() throws Exception {
93          if ((_inboxFolder == null) || !_inboxFolder.isOpen()) {
94              initStore();
95  
96              Folder defaultFolder = _store.getDefaultFolder();
97  
98              Folder[] folders = defaultFolder.list();
99  
100             if (folders.length == 0) {
101                 throw new MessagingException("Inbox not found");
102             }
103             else {
104                 _inboxFolder = folders[0];
105 
106                 _inboxFolder.open(Folder.READ_WRITE);
107             }
108         }
109     }
110 
111     protected void initStore() throws Exception {
112         if ((_store == null) || !_store.isConnected()) {
113             Session session = MailEngine.getSession();
114 
115             _store = session.getStore("pop3");
116 
117             String popHost = session.getProperty("mail.pop3.host");
118             String smtpUser = session.getProperty("mail.smtp.user");
119             String smtpPassword = session.getProperty("mail.smtp.password");
120 
121             _store.connect(popHost, smtpUser, smtpPassword);
122         }
123     }
124 
125     protected void nostifyListeners(
126             List<MessageListener> listeners, Message message)
127         throws Exception {
128 
129         String from = getEmailAddress(message.getFrom());
130         String recipient = getEmailAddress(
131             message.getRecipients(RecipientType.TO));
132 
133         if (_log.isDebugEnabled()) {
134             _log.debug("From " + from);
135             _log.debug("Recipient " + recipient);
136         }
137 
138         Iterator<MessageListener> itr = listeners.iterator();
139 
140         while (itr.hasNext()) {
141             MessageListener messageListener = itr.next();
142 
143             try {
144                 if (messageListener.accept(from, recipient)) {
145                     messageListener.deliver(from, recipient, message);
146                 }
147             }
148             catch (Exception e) {
149                 _log.error(e, e);
150             }
151         }
152     }
153 
154     protected void nostifyListeners(Message[] messages) throws Exception {
155         if (_log.isDebugEnabled()) {
156             _log.debug("Messages " + messages.length);
157         }
158 
159         List<MessageListener> listeners = POPServerUtil.getListeners();
160 
161         for (int i = 0; i < messages.length; i++) {
162             Message message = messages[i];
163 
164             if (_log.isDebugEnabled()) {
165                 _log.debug("Message " + message);
166             }
167 
168             nostifyListeners(listeners, message);
169         }
170     }
171 
172     protected void pollPopServer() throws Exception {
173         initInboxFolder();
174 
175         Message[] messages = _inboxFolder.getMessages();
176 
177         try {
178             nostifyListeners(messages);
179         }
180         finally {
181             if (_log.isDebugEnabled()) {
182                 _log.debug("Deleting messages");
183             }
184 
185             _inboxFolder.setFlags(
186                 messages, new Flags(Flags.Flag.DELETED), true);
187 
188             _inboxFolder.close(true);
189         }
190     }
191 
192     private static Log _log = LogFactory.getLog(POPNotificationsJob.class);
193 
194     private Store _store;
195     private Folder _inboxFolder;
196 
197 }