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