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.portlet.wiki.service.jms;
24  
25  import com.liferay.mail.service.MailServiceUtil;
26  import com.liferay.portal.NoSuchUserException;
27  import com.liferay.portal.kernel.mail.MailMessage;
28  import com.liferay.portal.kernel.util.GetterUtil;
29  import com.liferay.portal.kernel.util.StringUtil;
30  import com.liferay.portal.model.Subscription;
31  import com.liferay.portal.model.User;
32  import com.liferay.portal.service.SubscriptionLocalServiceUtil;
33  import com.liferay.portal.service.UserLocalServiceUtil;
34  import com.liferay.portlet.wiki.model.WikiNode;
35  import com.liferay.portlet.wiki.model.WikiPage;
36  
37  import java.util.HashSet;
38  import java.util.List;
39  import java.util.Set;
40  
41  import javax.jms.Message;
42  import javax.jms.MessageListener;
43  import javax.jms.ObjectMessage;
44  import javax.jms.Queue;
45  import javax.jms.QueueConnection;
46  import javax.jms.QueueConnectionFactory;
47  import javax.jms.QueueReceiver;
48  import javax.jms.QueueSession;
49  import javax.jms.Session;
50  
51  import javax.mail.internet.InternetAddress;
52  
53  import org.apache.commons.logging.Log;
54  import org.apache.commons.logging.LogFactory;
55  
56  /**
57   * <a href="WikiPageConsumer.java.html"><b><i>View Source</i></b></a>
58   *
59   * @author Bruno Farache
60   *
61   */
62  public class WikiPageConsumer implements MessageListener {
63  
64      public void consume() {
65          try {
66              QueueConnectionFactory qcf = WikiPageQCFUtil.getQCF();
67              QueueConnection con = qcf.createQueueConnection();
68  
69              QueueSession session = con.createQueueSession(
70                  false, Session.AUTO_ACKNOWLEDGE);
71              Queue queue = WikiPageQueueUtil.getQueue();
72  
73              QueueReceiver subscriber = session.createReceiver(queue);
74  
75              subscriber.setMessageListener(this);
76  
77              con.start();
78          }
79          catch (Exception e) {
80              _log.error(e);
81          }
82      }
83  
84      public void onMessage(Message msg) {
85          try {
86              ObjectMessage objMsg = (ObjectMessage)msg;
87  
88              String[] array = (String[])objMsg.getObject();
89  
90              _onMessage(array);
91          }
92          catch (Exception e) {
93              _log.error("Error sending wiki notifications", e);
94          }
95      }
96  
97      private void _onMessage(String[] array) throws Exception {
98          long companyId = GetterUtil.getLong(array[0]);
99          long userId = GetterUtil.getLong(array[1]);
100         long nodeId = GetterUtil.getLong(array[2]);
101         long pageResourcePrimKey = GetterUtil.getLong(array[3]);
102         String fromName = array[4];
103         String fromAddress = array[5];
104         String subject = array[6];
105         String body = array[7];
106         String replyToAddress = array[8];
107         String mailId = array[9];
108 
109         Set<Long> sent = new HashSet<Long>();
110 
111         if (_log.isInfoEnabled()) {
112             _log.info(
113                 "Sending notifications for {mailId=" + mailId +
114                     ", pageResourcePrimKey=" + pageResourcePrimKey +
115                         ", nodeId=" + nodeId + "}");
116         }
117 
118         // Pages
119 
120         List<Subscription> subscriptions =
121             SubscriptionLocalServiceUtil.getSubscriptions(
122                 companyId, WikiPage.class.getName(), pageResourcePrimKey);
123 
124         _sendEmail(
125             userId, fromName, fromAddress, subject, body, subscriptions, sent,
126             replyToAddress, mailId);
127 
128         // Nodes
129 
130         subscriptions = SubscriptionLocalServiceUtil.getSubscriptions(
131             companyId, WikiNode.class.getName(), nodeId);
132 
133         _sendEmail(
134             userId, fromName, fromAddress, subject, body, subscriptions, sent,
135             replyToAddress, mailId);
136 
137         if (_log.isInfoEnabled()) {
138             _log.info("Finished sending notifications");
139         }
140     }
141 
142     private void _sendEmail(
143             long userId, String fromName, String fromAddress, String subject,
144             String body, List<Subscription> subscriptions, Set<Long> sent,
145             String replyToAddress, String mailId)
146         throws Exception {
147 
148         for (Subscription subscription : subscriptions) {
149             long subscribedUserId = subscription.getUserId();
150 
151             if (sent.contains(subscribedUserId)) {
152                 if (_log.isDebugEnabled()) {
153                     _log.debug(
154                         "Do not send a duplicate email to user " +
155                             subscribedUserId);
156                 }
157 
158                 continue;
159             }
160             else {
161                 if (_log.isDebugEnabled()) {
162                     _log.debug(
163                         "Add user " + subscribedUserId +
164                             " to the list of users who have received an email");
165                 }
166 
167                 sent.add(subscribedUserId);
168             }
169 
170             User user = null;
171 
172             try {
173                 user = UserLocalServiceUtil.getUserById(
174                     subscription.getUserId());
175             }
176             catch (NoSuchUserException nsue) {
177                 if (_log.isInfoEnabled()) {
178                     _log.info(
179                         "Subscription " + subscription.getSubscriptionId() +
180                             " is stale and will be deleted");
181                 }
182 
183                 SubscriptionLocalServiceUtil.deleteSubscription(
184                     subscription.getSubscriptionId());
185 
186                 continue;
187             }
188 
189             try {
190                 InternetAddress from = new InternetAddress(
191                     fromAddress, fromName);
192 
193                 InternetAddress to = new InternetAddress(
194                     user.getEmailAddress(), user.getFullName());
195 
196                 String curSubject = StringUtil.replace(
197                     subject,
198                     new String[] {
199                         "[$TO_ADDRESS$]",
200                         "[$TO_NAME$]"
201                     },
202                     new String[] {
203                         user.getFullName(),
204                         user.getEmailAddress()
205                     });
206 
207                 String curBody = StringUtil.replace(
208                     body,
209                     new String[] {
210                         "[$TO_ADDRESS$]",
211                         "[$TO_NAME$]"
212                     },
213                     new String[] {
214                         user.getFullName(),
215                         user.getEmailAddress()
216                     });
217 
218                 InternetAddress replyTo = new InternetAddress(
219                     replyToAddress, replyToAddress);
220 
221                 MailMessage message = new MailMessage(
222                     from, to, curSubject, curBody, false);
223 
224                 message.setReplyTo(new InternetAddress[] {replyTo});
225                 message.setMessageId(mailId);
226 
227                 MailServiceUtil.sendEmail(message);
228             }
229             catch (Exception e) {
230                 _log.error(e);
231             }
232         }
233     }
234 
235     private static Log _log = LogFactory.getLog(WikiPageConsumer.class);
236 
237 }