001/**
002 *
003 * Copyright 2003-2007 Jive Software.
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017package org.jivesoftware.smackx.xroster;
018
019import java.lang.ref.WeakReference;
020import java.util.Collections;
021import java.util.HashSet;
022import java.util.Iterator;
023import java.util.Map;
024import java.util.Set;
025import java.util.WeakHashMap;
026
027import org.jivesoftware.smack.StanzaListener;
028import org.jivesoftware.smack.SmackException.NotConnectedException;
029import org.jivesoftware.smack.XMPPConnection;
030import org.jivesoftware.smack.filter.StanzaExtensionFilter;
031import org.jivesoftware.smack.filter.StanzaFilter;
032import org.jivesoftware.smack.packet.Message;
033import org.jivesoftware.smack.packet.Stanza;
034import org.jivesoftware.smack.roster.Roster;
035import org.jivesoftware.smack.roster.RosterEntry;
036import org.jivesoftware.smack.roster.RosterGroup;
037import org.jivesoftware.smackx.xroster.packet.RosterExchange;
038
039/**
040 *
041 * Manages Roster exchanges. A RosterExchangeManager provides a high level access to send 
042 * rosters, roster groups and roster entries to XMPP clients. It also provides an easy way
043 * to hook up custom logic when entries are received from another XMPP client through 
044 * RosterExchangeListeners.
045 *
046 * @author Gaston Dombiak
047 */
048public class RosterExchangeManager {
049
050    public final static String NAMESPACE = "jabber:x:roster";
051    public final static String ELEMENT = "x";
052
053    private final static Map<XMPPConnection, RosterExchangeManager> INSTANCES = new WeakHashMap<>();
054
055    private final static StanzaFilter PACKET_FILTER = new StanzaExtensionFilter(ELEMENT, NAMESPACE);
056
057    private final Set<RosterExchangeListener> rosterExchangeListeners = Collections.synchronizedSet(new HashSet<RosterExchangeListener>());
058
059    private final WeakReference<XMPPConnection> weakRefConnection;
060    private final StanzaListener packetListener;
061
062    public synchronized static RosterExchangeManager getInstanceFor(XMPPConnection connection) {
063        RosterExchangeManager rosterExchangeManager = INSTANCES.get(connection);
064        if (rosterExchangeManager == null) {
065            rosterExchangeManager = new RosterExchangeManager(connection);
066            INSTANCES.put(connection, rosterExchangeManager);
067        }
068        return rosterExchangeManager;
069    }
070
071    /**
072     * Creates a new roster exchange manager.
073     *
074     * @param connection an XMPPConnection which is used to send and receive messages.
075     */
076    public RosterExchangeManager(XMPPConnection connection) {
077        weakRefConnection = new WeakReference<XMPPConnection>(connection);
078        // Listens for all roster exchange packets and fire the roster exchange listeners.
079        packetListener = new StanzaListener() {
080            public void processPacket(Stanza packet) {
081                Message message = (Message) packet;
082                RosterExchange rosterExchange =
083                    (RosterExchange) message.getExtension(ELEMENT, NAMESPACE);
084                // Fire event for roster exchange listeners
085                fireRosterExchangeListeners(message.getFrom(), rosterExchange.getRosterEntries());
086            }
087        };
088        connection.addAsyncStanzaListener(packetListener, PACKET_FILTER);
089    }
090
091    /**
092     * Adds a listener to roster exchanges. The listener will be fired anytime roster entries
093     * are received from remote XMPP clients.
094     *
095     * @param rosterExchangeListener a roster exchange listener.
096     */
097    public void addRosterListener(RosterExchangeListener rosterExchangeListener) {
098        rosterExchangeListeners.add(rosterExchangeListener);
099    }
100
101    /**
102     * Removes a listener from roster exchanges. The listener will be fired anytime roster 
103     * entries are received from remote XMPP clients.
104     *
105     * @param rosterExchangeListener a roster exchange listener..
106     */
107    public void removeRosterListener(RosterExchangeListener rosterExchangeListener) {
108        rosterExchangeListeners.remove(rosterExchangeListener);
109    }
110
111    /**
112     * Sends a roster to userID. All the entries of the roster will be sent to the
113     * target user.
114     * 
115     * @param roster the roster to send
116     * @param targetUserID the user that will receive the roster entries
117     * @throws NotConnectedException 
118     */
119    public void send(Roster roster, String targetUserID) throws NotConnectedException {
120        // Create a new message to send the roster
121        Message msg = new Message(targetUserID);
122        // Create a RosterExchange Package and add it to the message
123        RosterExchange rosterExchange = new RosterExchange(roster);
124        msg.addExtension(rosterExchange);
125
126        XMPPConnection connection = weakRefConnection.get();
127        // Send the message that contains the roster
128        connection.sendStanza(msg);
129    }
130
131    /**
132     * Sends a roster entry to userID.
133     * 
134     * @param rosterEntry the roster entry to send
135     * @param targetUserID the user that will receive the roster entries
136     * @throws NotConnectedException 
137     */
138    public void send(RosterEntry rosterEntry, String targetUserID) throws NotConnectedException {
139        // Create a new message to send the roster
140        Message msg = new Message(targetUserID);
141        // Create a RosterExchange Package and add it to the message
142        RosterExchange rosterExchange = new RosterExchange();
143        rosterExchange.addRosterEntry(rosterEntry);
144        msg.addExtension(rosterExchange);
145
146        XMPPConnection connection = weakRefConnection.get();
147        // Send the message that contains the roster
148        connection.sendStanza(msg);
149    }
150
151    /**
152     * Sends a roster group to userID. All the entries of the group will be sent to the 
153     * target user.
154     * 
155     * @param rosterGroup the roster group to send
156     * @param targetUserID the user that will receive the roster entries
157     * @throws NotConnectedException 
158     */
159    public void send(RosterGroup rosterGroup, String targetUserID) throws NotConnectedException {
160        // Create a new message to send the roster
161        Message msg = new Message(targetUserID);
162        // Create a RosterExchange Package and add it to the message
163        RosterExchange rosterExchange = new RosterExchange();
164        for (RosterEntry entry : rosterGroup.getEntries()) {
165            rosterExchange.addRosterEntry(entry);
166        }
167        msg.addExtension(rosterExchange);
168
169        XMPPConnection connection = weakRefConnection.get();
170        // Send the message that contains the roster
171        connection.sendStanza(msg);
172    }
173
174    /**
175     * Fires roster exchange listeners.
176     */
177    private void fireRosterExchangeListeners(String from, Iterator<RemoteRosterEntry> remoteRosterEntries) {
178        RosterExchangeListener[] listeners = null;
179        synchronized (rosterExchangeListeners) {
180            listeners = new RosterExchangeListener[rosterExchangeListeners.size()];
181            rosterExchangeListeners.toArray(listeners);
182        }
183        for (int i = 0; i < listeners.length; i++) {
184            listeners[i].entriesReceived(from, remoteRosterEntries);
185        }
186    }
187}