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.PacketListener;
028import org.jivesoftware.smack.Roster;
029import org.jivesoftware.smack.RosterEntry;
030import org.jivesoftware.smack.RosterGroup;
031import org.jivesoftware.smack.SmackException.NotConnectedException;
032import org.jivesoftware.smack.XMPPConnection;
033import org.jivesoftware.smack.filter.PacketExtensionFilter;
034import org.jivesoftware.smack.filter.PacketFilter;
035import org.jivesoftware.smack.packet.Message;
036import org.jivesoftware.smack.packet.Packet;
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 =
054                    Collections.synchronizedMap(new WeakHashMap<XMPPConnection, RosterExchangeManager>());
055
056    private final static PacketFilter PACKET_FILTER = new PacketExtensionFilter(ELEMENT, NAMESPACE);
057
058    private final Set<RosterExchangeListener> rosterExchangeListeners = Collections.synchronizedSet(new HashSet<RosterExchangeListener>());
059
060    private final WeakReference<XMPPConnection> weakRefConnection;
061    private final PacketListener packetListener;
062
063    public synchronized static RosterExchangeManager getInstanceFor(XMPPConnection connection) {
064        RosterExchangeManager rosterExchangeManager = INSTANCES.get(connection);
065        if (rosterExchangeManager == null) {
066            rosterExchangeManager = new RosterExchangeManager(connection);
067        }
068        return rosterExchangeManager;
069    }
070
071    /**
072     * Creates a new roster exchange manager.
073     *
074     * @param connection a 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 PacketListener() {
080            public void processPacket(Packet 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        };
089        connection.addPacketListener(packetListener, PACKET_FILTER);
090    }
091
092    /**
093     * Adds a listener to roster exchanges. The listener will be fired anytime roster entries
094     * are received from remote XMPP clients.
095     *
096     * @param rosterExchangeListener a roster exchange listener.
097     */
098    public void addRosterListener(RosterExchangeListener rosterExchangeListener) {
099        rosterExchangeListeners.add(rosterExchangeListener);
100    }
101
102    /**
103     * Removes a listener from roster exchanges. The listener will be fired anytime roster 
104     * entries are received from remote XMPP clients.
105     *
106     * @param rosterExchangeListener a roster exchange listener..
107     */
108    public void removeRosterListener(RosterExchangeListener rosterExchangeListener) {
109        rosterExchangeListeners.remove(rosterExchangeListener);
110    }
111
112    /**
113     * Sends a roster to userID. All the entries of the roster will be sent to the
114     * target user.
115     * 
116     * @param roster the roster to send
117     * @param targetUserID the user that will receive the roster entries
118     * @throws NotConnectedException 
119     */
120    public void send(Roster roster, String targetUserID) throws NotConnectedException {
121        // Create a new message to send the roster
122        Message msg = new Message(targetUserID);
123        // Create a RosterExchange Package and add it to the message
124        RosterExchange rosterExchange = new RosterExchange(roster);
125        msg.addExtension(rosterExchange);
126
127        XMPPConnection connection = weakRefConnection.get();
128        // Send the message that contains the roster
129        connection.sendPacket(msg);
130    }
131
132    /**
133     * Sends a roster entry to userID.
134     * 
135     * @param rosterEntry the roster entry to send
136     * @param targetUserID the user that will receive the roster entries
137     * @throws NotConnectedException 
138     */
139    public void send(RosterEntry rosterEntry, String targetUserID) throws NotConnectedException {
140        // Create a new message to send the roster
141        Message msg = new Message(targetUserID);
142        // Create a RosterExchange Package and add it to the message
143        RosterExchange rosterExchange = new RosterExchange();
144        rosterExchange.addRosterEntry(rosterEntry);
145        msg.addExtension(rosterExchange);
146
147        XMPPConnection connection = weakRefConnection.get();
148        // Send the message that contains the roster
149        connection.sendPacket(msg);
150    }
151
152    /**
153     * Sends a roster group to userID. All the entries of the group will be sent to the 
154     * target user.
155     * 
156     * @param rosterGroup the roster group to send
157     * @param targetUserID the user that will receive the roster entries
158     * @throws NotConnectedException 
159     */
160    public void send(RosterGroup rosterGroup, String targetUserID) throws NotConnectedException {
161        // Create a new message to send the roster
162        Message msg = new Message(targetUserID);
163        // Create a RosterExchange Package and add it to the message
164        RosterExchange rosterExchange = new RosterExchange();
165        for (RosterEntry entry : rosterGroup.getEntries()) {
166            rosterExchange.addRosterEntry(entry);
167        }
168        msg.addExtension(rosterExchange);
169
170        XMPPConnection connection = weakRefConnection.get();
171        // Send the message that contains the roster
172        connection.sendPacket(msg);
173    }
174
175    /**
176     * Fires roster exchange listeners.
177     */
178    private void fireRosterExchangeListeners(String from, Iterator<RemoteRosterEntry> remoteRosterEntries) {
179        RosterExchangeListener[] listeners = null;
180        synchronized (rosterExchangeListeners) {
181            listeners = new RosterExchangeListener[rosterExchangeListeners.size()];
182            rosterExchangeListeners.toArray(listeners);
183        }
184        for (int i = 0; i < listeners.length; i++) {
185            listeners[i].entriesReceived(from, remoteRosterEntries);
186        }
187    }
188}