1   /**
2    * Copyright (c) 2000-2010 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   *
12   *
13   */
14  
15  package com.liferay.portal.pop;
16  
17  import com.liferay.portal.kernel.job.IntervalJob;
18  import com.liferay.portal.kernel.job.JobExecutionContext;
19  import com.liferay.portal.kernel.log.Log;
20  import com.liferay.portal.kernel.log.LogFactoryUtil;
21  import com.liferay.portal.kernel.mail.Account;
22  import com.liferay.portal.kernel.pop.MessageListener;
23  import com.liferay.portal.kernel.util.GetterUtil;
24  import com.liferay.portal.kernel.util.PropsKeys;
25  import com.liferay.portal.kernel.util.StringPool;
26  import com.liferay.portal.kernel.util.Time;
27  import com.liferay.portal.kernel.util.Validator;
28  import com.liferay.portal.util.PropsUtil;
29  import com.liferay.util.mail.MailEngine;
30  
31  import java.util.Iterator;
32  import java.util.List;
33  
34  import javax.mail.Address;
35  import javax.mail.Flags;
36  import javax.mail.Folder;
37  import javax.mail.Message.RecipientType;
38  import javax.mail.Message;
39  import javax.mail.MessagingException;
40  import javax.mail.Session;
41  import javax.mail.Store;
42  import javax.mail.internet.InternetAddress;
43  
44  /**
45   * <a href="POPNotificationsJob.java.html"><b><i>View Source</i></b></a>
46   *
47   * @author Brian Wing Shun Chan
48   */
49  public class POPNotificationsJob implements IntervalJob {
50  
51      public static final long INTERVAL = GetterUtil.getLong(PropsUtil.get(
52          PropsKeys.POP_SERVER_NOTIFICATIONS_INTERVAL)) * Time.MINUTE;
53  
54      public void execute(JobExecutionContext context) {
55          try {
56              if (_log.isDebugEnabled()) {
57                  _log.debug("Executing");
58              }
59  
60              pollPopServer();
61          }
62          catch (Exception e) {
63              _log.error(e, e);
64  
65              _store = null;
66              _inboxFolder = null;
67          }
68      }
69  
70      public long getInterval() {
71          return INTERVAL;
72      }
73  
74      protected String getEmailAddress(Address[] addresses) {
75          if ((addresses == null) || (addresses.length == 0)) {
76              return StringPool.BLANK;
77          }
78  
79          InternetAddress internetAddress = (InternetAddress)addresses[0];
80  
81          return internetAddress.getAddress();
82      }
83  
84      protected void initInboxFolder() throws Exception {
85          if ((_inboxFolder == null) || !_inboxFolder.isOpen()) {
86              initStore();
87  
88              Folder defaultFolder = _store.getDefaultFolder();
89  
90              Folder[] folders = defaultFolder.list();
91  
92              if (folders.length == 0) {
93                  throw new MessagingException("Inbox not found");
94              }
95              else {
96                  _inboxFolder = folders[0];
97  
98                  _inboxFolder.open(Folder.READ_WRITE);
99              }
100         }
101     }
102 
103     protected void initStore() throws Exception {
104         if ((_store == null) || !_store.isConnected()) {
105             Session session = MailEngine.getSession();
106 
107             String storeProtocol = GetterUtil.getString(
108                 session.getProperty("mail.store.protocol"));
109 
110             if (!storeProtocol.equals(Account.PROTOCOL_POPS)) {
111                 storeProtocol = Account.PROTOCOL_POP;
112             }
113 
114             _store = session.getStore(storeProtocol);
115 
116             String prefix = "mail." + storeProtocol + ".";
117 
118             String host = session.getProperty(prefix + "host");
119 
120             String user = session.getProperty(prefix + "user");
121 
122             if (Validator.isNull(user)) {
123                 user = session.getProperty("mail.smtp.user");
124             }
125 
126             String password = session.getProperty(prefix + "password");
127 
128             if (Validator.isNull(password)) {
129                 password = session.getProperty("mail.smtp.password");
130             }
131 
132             _store.connect(host, user, password);
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, message)) {
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 = LogFactoryUtil.getLog(POPNotificationsJob.class);
204 
205     private Store _store;
206     private Folder _inboxFolder;
207 
208 }