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.messaging.util;
24  
25  import com.liferay.portal.PortalException;
26  import com.liferay.portal.SystemException;
27  import com.liferay.portal.kernel.util.GetterUtil;
28  import com.liferay.portal.kernel.util.StringPool;
29  import com.liferay.portal.kernel.util.StringUtil;
30  import com.liferay.portal.model.User;
31  import com.liferay.portal.util.PropsUtil;
32  import com.liferay.portal.util.PropsValues;
33  import com.liferay.portal.util.WebKeys;
34  import com.liferay.portlet.chat.model.RosterUpdateListener;
35  import com.liferay.portlet.messaging.model.JabberSession;
36  import com.liferay.portlet.messaging.model.MessageListener;
37  import com.liferay.portlet.messaging.util.comparator.NameComparator;
38  
39  import java.util.ArrayList;
40  import java.util.Collections;
41  import java.util.Iterator;
42  import java.util.List;
43  
44  import javax.servlet.http.HttpSession;
45  
46  import org.jivesoftware.smack.AccountManager;
47  import org.jivesoftware.smack.Chat;
48  import org.jivesoftware.smack.PacketCollector;
49  import org.jivesoftware.smack.Roster;
50  import org.jivesoftware.smack.RosterEntry;
51  import org.jivesoftware.smack.XMPPConnection;
52  import org.jivesoftware.smack.XMPPException;
53  import org.jivesoftware.smack.filter.PacketFilter;
54  import org.jivesoftware.smack.filter.PacketTypeFilter;
55  import org.jivesoftware.smack.packet.Message;
56  import org.jivesoftware.smack.packet.Presence;
57  import org.jivesoftware.smack.packet.RosterPacket;
58  
59  import org.json.JSONArray;
60  import org.json.JSONObject;
61  
62  /**
63   * <a href="MessagingUtil.java.html"><b><i>View Source</i></b></a>
64   *
65   * @author Ming-Gih Lam
66   *
67   */
68  public class MessagingUtil {
69  
70      public static String SERVER_ADDRESS = GetterUtil.getString(
71          PropsUtil.get(PropsUtil.JABBER_XMPP_SERVER_ADDRESS), "localhost");
72  
73      public static int SERVER_PORT = GetterUtil.getInteger(
74          PropsUtil.get(PropsUtil.JABBER_XMPP_SERVER_PORT), 5222);
75  
76      public static String USER_PASSWORD = GetterUtil.getString(
77          PropsUtil.get(PropsUtil.JABBER_XMPP_USER_PASSWORD), "liferayllc");
78  
79      public static JSONObject addRosterEntry(HttpSession ses, User user)
80          throws PortalException, SystemException, XMPPException {
81  
82          JSONObject jo = new JSONObject();
83  
84          Roster roster = getRoster(ses);
85  
86          String smackId = getXmppId(user);
87          String name = user.getFullName();
88  
89          try {
90              XMPPConnection con = new XMPPConnection(
91                  SERVER_ADDRESS, SERVER_PORT);
92  
93              AccountManager accountManager = con.getAccountManager();
94  
95              try {
96                  accountManager.createAccount(
97                      String.valueOf(user.getUserId()), USER_PASSWORD);
98              }
99              catch (XMPPException xmppe) {
100             }
101 
102             con.close();
103         }
104         catch (XMPPException xmppe) {
105         }
106 
107         roster.createEntry(smackId, name, null);
108 
109         jo.put("name", name);
110         jo.put("user", user.getUserId());
111         jo.put("status", "success");
112 
113         return jo;
114     }
115 
116     public static void closeXMPPConnection(HttpSession ses) {
117         if (isJabberEnabled()) {
118             JabberSession jabberSes = (JabberSession)ses.getAttribute(
119                 WebKeys.JABBER_XMPP_SESSION);
120 
121             if (jabberSes != null) {
122                 Roster roster = jabberSes.getRoster();
123 
124                 roster.removeRosterListener(jabberSes.getRosterListener());
125 
126                 XMPPConnection con = jabberSes.getConnection();
127 
128                 con.removePacketListener(jabberSes.getMessageListener());
129 
130                 con.close();
131 
132                 ses.removeAttribute(WebKeys.JABBER_XMPP_SESSION);
133             }
134         }
135     }
136 
137     public static void createXMPPConnection(HttpSession ses, long userId)
138         throws XMPPException {
139 
140         createXMPPConnection(ses, String.valueOf(userId));
141     }
142 
143     public static void createXMPPConnection(HttpSession ses, String userId)
144         throws XMPPException {
145 
146         if (isJabberEnabled()) {
147             XMPPConnection con = null;
148 
149             try {
150                 con = new XMPPConnection(SERVER_ADDRESS, SERVER_PORT);
151             }
152             catch (XMPPException e) {
153                 return;
154             }
155 
156             try {
157                 con.login(userId, USER_PASSWORD, ses.getId());
158             }
159             catch (XMPPException xmppe) {
160                 AccountManager accountManager = con.getAccountManager();
161 
162                 accountManager.createAccount(userId, USER_PASSWORD);
163 
164                 con.close();
165 
166                 con = new XMPPConnection(SERVER_ADDRESS, SERVER_PORT);
167 
168                 con.login(userId, USER_PASSWORD, ses.getId());
169             }
170 
171             PacketFilter filter = new PacketTypeFilter(Message.class);
172 
173             PacketCollector collector = con.createPacketCollector(filter);
174 
175             MessageListener msgListener = new MessageListener(ses);
176 
177             con.addPacketListener(msgListener, filter);
178 
179             Roster roster = con.getRoster();
180 
181             //roster.setSubscriptionMode(Roster.SUBSCRIPTION_ACCEPT_ALL);
182 
183             RosterUpdateListener rosterListener = new RosterUpdateListener(ses);
184 
185             roster.addRosterListener(rosterListener);
186 
187             JabberSession jabberSes = new JabberSession();
188 
189             jabberSes.setConnection(con);
190             jabberSes.setCollector(collector);
191             jabberSes.setMessageListener(msgListener);
192             jabberSes.setRoster(roster);
193             jabberSes.setRosterListener(rosterListener);
194 
195             ses.setAttribute(WebKeys.JABBER_XMPP_SESSION, jabberSes);
196         }
197     }
198 
199     public static void deleteRosterEntries(HttpSession ses, String[] userId)
200         throws XMPPException {
201 
202         Roster roster = getRoster(ses);
203 
204         for (int i = 0; i < userId.length; i++) {
205             RosterEntry entry = roster.getEntry(getXmppId(userId[i]));
206 
207             roster.removeEntry(entry);
208         }
209     }
210 
211     public static JSONObject getChatMessages(HttpSession ses) {
212         JSONArray ja = new JSONArray();
213         JSONObject jo = new JSONObject();
214         PacketCollector collector = getCollector(ses);
215         Message message = getNextMessage(collector);
216         Roster roster = getRoster(ses);
217 
218         while (message != null) {
219             JSONObject jMsg = new JSONObject();
220             String fromId = (String)message.getProperty("fromId");
221 
222             jMsg.put("body", message.getBody());
223             jMsg.put("category", message.getProperty("category"));
224             jMsg.put("toId", message.getProperty("toId"));
225             jMsg.put("toName", message.getProperty("toName"));
226             jMsg.put("fromId", fromId);
227             jMsg.put("fromName", message.getProperty("fromName"));
228             jMsg.put(
229                 "status", getPresence(roster.getPresence(getXmppId(fromId))));
230 
231             ja.put(jMsg);
232 
233             message = getNextMessage(collector);
234         }
235 
236         jo.put("chat", ja);
237         jo.put("status", "success");
238 
239         return jo;
240     }
241 
242     public static PacketCollector getCollector(HttpSession ses) {
243         JabberSession jabberSes = (JabberSession)ses.getAttribute(
244             WebKeys.JABBER_XMPP_SESSION);
245 
246         return jabberSes.getCollector();
247     }
248 
249     public static XMPPConnection getConnection(HttpSession ses) {
250         JabberSession jabberSes = (JabberSession)ses.getAttribute(
251             WebKeys.JABBER_XMPP_SESSION);
252 
253         return jabberSes.getConnection();
254     }
255 
256     public static Message getNextMessage(PacketCollector collector) {
257         Message message = (Message)collector.pollResult();
258 
259         return message;
260     }
261 
262     public static String getPresence(Presence presence) {
263         String status = "unavailable";
264 
265         if (presence != null) {
266             status = presence.getType().toString();
267         }
268 
269         return status;
270     }
271 
272     public static Roster getRoster(HttpSession ses) {
273         JabberSession jabberSes = (JabberSession)ses.getAttribute(
274             WebKeys.JABBER_XMPP_SESSION);
275 
276         return jabberSes.getRoster();
277     }
278 
279     public static JSONObject getRosterEntries(HttpSession ses) {
280         JSONObject jo = new JSONObject();
281         Roster roster = getRoster(ses);
282         List rosterList = new ArrayList();
283 
284         Iterator rosterEntries = roster.getEntries();
285         JSONArray ja = new JSONArray();
286 
287         while (rosterEntries.hasNext()) {
288             RosterEntry entry = (RosterEntry)rosterEntries.next();
289 
290             if (entry.getType() != RosterPacket.ItemType.FROM) {
291                 rosterList.add(entry);
292             }
293         }
294 
295         if (rosterList.size() > 0) {
296             Collections.sort(rosterList, new NameComparator());
297 
298             for (int i = 0; i < rosterList.size(); i++) {
299 
300                 JSONObject jEntry = new JSONObject();
301                 RosterEntry entry = (RosterEntry)rosterList.get(i);
302 
303                 jEntry.put("user", getUserId(entry));
304                 jEntry.put("name", entry.getName());
305                 jEntry.put("status", getPresence(roster
306                     .getPresence(entry.getUser())));
307                 ja.put(jEntry);
308             }
309         }
310 
311         jo.put("roster", ja);
312 
313         return jo;
314     }
315 
316     public static String getUserId(RosterEntry entry) {
317         String userId = entry.getUser();
318 
319         String serverName = GetterUtil.getString(PropsUtil.get(
320             PropsUtil.JABBER_XMPP_SERVER_NAME), "localhost");
321 
322         userId = StringUtil.replace(
323             userId, StringPool.AT + serverName, StringPool.BLANK);
324 
325         return userId;
326     }
327 
328     public static String getXmppId(String userId) {
329         String serverName = GetterUtil.getString(PropsUtil.get(
330             PropsUtil.JABBER_XMPP_SERVER_NAME), "localhost");
331 
332         String xmppId = userId + StringPool.AT + serverName;
333 
334         return xmppId;
335     }
336 
337     public static String getXmppId(User user) {
338         String xmppId = getXmppId(String.valueOf(user.getUserId()));
339 
340         return xmppId;
341     }
342 
343     public static boolean isJabberEnabled() {
344         return PropsValues.JABBER_XMPP_SERVER_ENABLED;
345     }
346 
347     public static void sendMessage(
348             HttpSession ses, String fromId, String fromName, String toId,
349             String toName, String bodyText)
350         throws XMPPException {
351 
352         XMPPConnection con = getConnection(ses);
353 
354         Chat chat = con.createChat(getXmppId(toId));
355 
356         Message message = chat.createMessage();
357 
358         message.setBody(bodyText);
359         message.setProperty("category", "private");
360         message.setProperty("fromId", fromId);
361         message.setProperty("fromName", fromName);
362         message.setProperty("toId", toId);
363         message.setProperty("toName", toName);
364 
365         chat.sendMessage(message);
366     }
367 
368 }