1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    *
5    *
6    *
7    * The contents of this file are subject to the terms of the Liferay Enterprise
8    * Subscription License ("License"). You may not use this file except in
9    * compliance with the License. You can obtain a copy of the License by
10   * contacting Liferay, Inc. See the License for the specific language governing
11   * permissions and limitations under the License, including but not limited to
12   * distribution rights 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  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             String storeProtocol = GetterUtil.getString(
116                 session.getProperty("mail.store.protocol"));
117 
118             if (!storeProtocol.equals(Account.PROTOCOL_POPS)) {
119                 storeProtocol = Account.PROTOCOL_POP;
120             }
121 
122             _store = session.getStore(storeProtocol);
123 
124             String prefix = "mail." + storeProtocol + ".";
125 
126             String host = session.getProperty(prefix + "host");
127 
128             String user = session.getProperty(prefix + "user");
129 
130             if (Validator.isNull(user)) {
131                 user = session.getProperty("mail.smtp.user");
132             }
133 
134             String password = session.getProperty(prefix + "password");
135 
136             if (Validator.isNull(password)) {
137                 password = session.getProperty("mail.smtp.password");
138             }
139 
140             _store.connect(host, user, password);
141         }
142     }
143 
144     protected void nostifyListeners(
145             List<MessageListener> listeners, Message message)
146         throws Exception {
147 
148         String from = getEmailAddress(message.getFrom());
149         String recipient = getEmailAddress(
150             message.getRecipients(RecipientType.TO));
151 
152         if (_log.isDebugEnabled()) {
153             _log.debug("From " + from);
154             _log.debug("Recipient " + recipient);
155         }
156 
157         Iterator<MessageListener> itr = listeners.iterator();
158 
159         while (itr.hasNext()) {
160             MessageListener messageListener = itr.next();
161 
162             try {
163                 if (messageListener.accept(from, recipient, message)) {
164                     messageListener.deliver(from, recipient, message);
165                 }
166             }
167             catch (Exception e) {
168                 _log.error(e, e);
169             }
170         }
171     }
172 
173     protected void nostifyListeners(Message[] messages) throws Exception {
174         if (_log.isDebugEnabled()) {
175             _log.debug("Messages " + messages.length);
176         }
177 
178         List<MessageListener> listeners = POPServerUtil.getListeners();
179 
180         for (int i = 0; i < messages.length; i++) {
181             Message message = messages[i];
182 
183             if (_log.isDebugEnabled()) {
184                 _log.debug("Message " + message);
185             }
186 
187             nostifyListeners(listeners, message);
188         }
189     }
190 
191     protected void pollPopServer() throws Exception {
192         initInboxFolder();
193 
194         Message[] messages = _inboxFolder.getMessages();
195 
196         try {
197             nostifyListeners(messages);
198         }
199         finally {
200             if (_log.isDebugEnabled()) {
201                 _log.debug("Deleting messages");
202             }
203 
204             _inboxFolder.setFlags(
205                 messages, new Flags(Flags.Flag.DELETED), true);
206 
207             _inboxFolder.close(true);
208         }
209     }
210 
211     private static Log _log = LogFactoryUtil.getLog(POPNotificationsJob.class);
212 
213     private Store _store;
214     private Folder _inboxFolder;
215 
216 }