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