001/**
002 *
003 * Copyright 2003-2007 Jive Software, 2016-2021 Florian Schmaus.
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 */
017
018package org.jivesoftware.smack.roster;
019
020import java.util.ArrayList;
021import java.util.Arrays;
022import java.util.Collection;
023import java.util.Collections;
024import java.util.HashSet;
025import java.util.LinkedHashSet;
026import java.util.List;
027import java.util.Map;
028import java.util.Set;
029import java.util.WeakHashMap;
030import java.util.concurrent.ConcurrentHashMap;
031import java.util.concurrent.CopyOnWriteArraySet;
032import java.util.logging.Level;
033import java.util.logging.Logger;
034
035import org.jivesoftware.smack.AsyncButOrdered;
036import org.jivesoftware.smack.ConnectionCreationListener;
037import org.jivesoftware.smack.ConnectionListener;
038import org.jivesoftware.smack.Manager;
039import org.jivesoftware.smack.SmackException;
040import org.jivesoftware.smack.SmackException.FeatureNotSupportedException;
041import org.jivesoftware.smack.SmackException.NoResponseException;
042import org.jivesoftware.smack.SmackException.NotConnectedException;
043import org.jivesoftware.smack.SmackException.NotLoggedInException;
044import org.jivesoftware.smack.SmackFuture;
045import org.jivesoftware.smack.StanzaListener;
046import org.jivesoftware.smack.XMPPConnection;
047import org.jivesoftware.smack.XMPPConnectionRegistry;
048import org.jivesoftware.smack.XMPPException.XMPPErrorException;
049import org.jivesoftware.smack.filter.AndFilter;
050import org.jivesoftware.smack.filter.PresenceTypeFilter;
051import org.jivesoftware.smack.filter.StanzaFilter;
052import org.jivesoftware.smack.filter.StanzaTypeFilter;
053import org.jivesoftware.smack.filter.ToMatchesFilter;
054import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
055import org.jivesoftware.smack.packet.IQ;
056import org.jivesoftware.smack.packet.Presence;
057import org.jivesoftware.smack.packet.PresenceBuilder;
058import org.jivesoftware.smack.packet.Stanza;
059import org.jivesoftware.smack.packet.StanzaBuilder;
060import org.jivesoftware.smack.packet.StanzaError.Condition;
061import org.jivesoftware.smack.roster.SubscribeListener.SubscribeAnswer;
062import org.jivesoftware.smack.roster.packet.RosterPacket;
063import org.jivesoftware.smack.roster.packet.RosterPacket.Item;
064import org.jivesoftware.smack.roster.packet.RosterVer;
065import org.jivesoftware.smack.roster.packet.SubscriptionPreApproval;
066import org.jivesoftware.smack.roster.rosterstore.RosterStore;
067import org.jivesoftware.smack.util.ExceptionCallback;
068import org.jivesoftware.smack.util.Objects;
069import org.jivesoftware.smack.util.SuccessCallback;
070
071import org.jxmpp.jid.BareJid;
072import org.jxmpp.jid.EntityBareJid;
073import org.jxmpp.jid.EntityFullJid;
074import org.jxmpp.jid.FullJid;
075import org.jxmpp.jid.Jid;
076import org.jxmpp.jid.impl.JidCreate;
077import org.jxmpp.jid.parts.Resourcepart;
078import org.jxmpp.util.cache.LruCache;
079
080/**
081 * Represents a user's roster, which is the collection of users a person receives
082 * presence updates for. Roster items are categorized into groups for easier management.
083 *
084 * Other users may attempt to subscribe to this user using a subscription request. Three
085 * modes are supported for handling these requests: <ul>
086 * <li>{@link SubscriptionMode#accept_all accept_all} -- accept all subscription requests.</li>
087 * <li>{@link SubscriptionMode#reject_all reject_all} -- reject all subscription requests.</li>
088 * <li>{@link SubscriptionMode#manual manual} -- manually process all subscription requests.</li>
089 * </ul>
090 *
091 * @author Matt Tucker
092 * @see #getInstanceFor(XMPPConnection)
093 */
094public final class Roster extends Manager {
095
096    private static final Logger LOGGER = Logger.getLogger(Roster.class.getName());
097
098    static {
099        XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
100            @Override
101            public void connectionCreated(XMPPConnection connection) {
102                getInstanceFor(connection);
103            }
104        });
105    }
106
107    private static final Map<XMPPConnection, Roster> INSTANCES = new WeakHashMap<>();
108
109    /**
110     * Returns the roster for the user.
111     * <p>
112     * This method will never return <code>null</code>, instead if the user has not yet logged into
113     * the server all modifying methods of the returned roster object
114     * like {@link Roster#createEntry(BareJid, String, String[])},
115     * {@link Roster#removeEntry(RosterEntry)} , etc. except adding or removing
116     * {@link RosterListener}s will throw an IllegalStateException.
117     * </p>
118     *
119     * @param connection the connection the roster should be retrieved for.
120     * @return the user's roster.
121     */
122    public static synchronized Roster getInstanceFor(XMPPConnection connection) {
123        Roster roster = INSTANCES.get(connection);
124        if (roster == null) {
125            roster = new Roster(connection);
126            INSTANCES.put(connection, roster);
127        }
128        return roster;
129    }
130
131    private static final StanzaFilter PRESENCE_PACKET_FILTER = StanzaTypeFilter.PRESENCE;
132
133    private static final StanzaFilter OUTGOING_USER_UNAVAILABLE_PRESENCE = new AndFilter(PresenceTypeFilter.UNAVAILABLE, ToMatchesFilter.MATCH_NO_TO_SET);
134
135    private static boolean rosterLoadedAtLoginDefault = true;
136
137    /**
138     * The default subscription processing mode to use when a Roster is created. By default
139     * all subscription requests are automatically rejected.
140     */
141    private static SubscriptionMode defaultSubscriptionMode = SubscriptionMode.reject_all;
142
143    /**
144     * The initial maximum size of the map holding presence information of entities without an Roster entry. Currently
145     * {@value #INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE}.
146     */
147    public static final int INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE = 1024;
148
149    private static int defaultNonRosterPresenceMapMaxSize = INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE;
150
151    private RosterStore rosterStore;
152
153    /**
154     * The groups of this roster.
155     * <p>
156     * Note that we use {@link ConcurrentHashMap} also as static type of this field, since we use the fact that the same
157     * thread can modify this collection, e.g. remove items, while iterating over it. This is done, for example in
158     * {@link #deleteEntry(Collection, RosterEntry)}. If we do not denote the static type to ConcurrentHashMap, but
159     * {@link Map} instead, then error prone would report a ModifyCollectionInEnhancedForLoop but.
160     * </p>
161     */
162    private final ConcurrentHashMap<String, RosterGroup> groups = new ConcurrentHashMap<>();
163
164    /**
165     * Concurrent hash map from JID to its roster entry.
166     */
167    private final Map<BareJid, RosterEntry> entries = new ConcurrentHashMap<>();
168
169    private final Set<RosterEntry> unfiledEntries = new CopyOnWriteArraySet<>();
170    private final Set<RosterListener> rosterListeners = new LinkedHashSet<>();
171
172    private final Set<PresenceEventListener> presenceEventListeners = new CopyOnWriteArraySet<>();
173
174    /**
175     * A map of JIDs to another Map of Resourceparts to Presences. The 'inner' map may contain
176     * {@link Resourcepart#EMPTY} if there are no other Presences available.
177     */
178    private final Map<BareJid, Map<Resourcepart, Presence>> presenceMap = new ConcurrentHashMap<>();
179
180    /**
181     * Like {@link presenceMap} but for presences of entities not in our Roster.
182     */
183    // TODO Ideally we want here to use a LRU cache like Map which will evict all superfluous items
184    // if their maximum size is lowered below the current item count. LruCache does not provide
185    // this.
186    private final LruCache<BareJid, Map<Resourcepart, Presence>> nonRosterPresenceMap = new LruCache<>(
187                    defaultNonRosterPresenceMapMaxSize);
188
189    /**
190     * Listeners called when the Roster was loaded.
191     */
192    private final Set<RosterLoadedListener> rosterLoadedListeners = new LinkedHashSet<>();
193
194    /**
195     * Mutually exclude roster listener invocation and changing the {@link entries} map. Also used
196     * to synchronize access to either the roster listeners or the entries map.
197     */
198    private final Object rosterListenersAndEntriesLock = new Object();
199
200    private enum RosterState {
201        uninitialized,
202        loading,
203        loaded,
204    }
205
206    /**
207     * The current state of the roster.
208     */
209    private RosterState rosterState = RosterState.uninitialized;
210
211    private final PresencePacketListener presencePacketListener = new PresencePacketListener();
212
213    /**
214     *
215     */
216    private boolean rosterLoadedAtLogin = rosterLoadedAtLoginDefault;
217
218    private SubscriptionMode subscriptionMode = getDefaultSubscriptionMode();
219
220    private final Set<SubscribeListener> subscribeListeners = new CopyOnWriteArraySet<>();
221
222    private SubscriptionMode previousSubscriptionMode;
223
224    /**
225     * Returns the default subscription processing mode to use when a new Roster is created. The
226     * subscription processing mode dictates what action Smack will take when subscription
227     * requests from other users are made. The default subscription mode
228     * is {@link SubscriptionMode#reject_all}.
229     *
230     * @return the default subscription mode to use for new Rosters
231     */
232    public static SubscriptionMode getDefaultSubscriptionMode() {
233        return defaultSubscriptionMode;
234    }
235
236    /**
237     * Sets the default subscription processing mode to use when a new Roster is created. The
238     * subscription processing mode dictates what action Smack will take when subscription
239     * requests from other users are made. The default subscription mode
240     * is {@link SubscriptionMode#reject_all}.
241     *
242     * @param subscriptionMode the default subscription mode to use for new Rosters.
243     */
244    public static void setDefaultSubscriptionMode(SubscriptionMode subscriptionMode) {
245        defaultSubscriptionMode = subscriptionMode;
246    }
247
248    private final AsyncButOrdered<BareJid> asyncButOrdered = new AsyncButOrdered<>();
249
250    /**
251     * Creates a new roster.
252     *
253     * @param connection an XMPP connection.
254     */
255    private Roster(final XMPPConnection connection) {
256        super(connection);
257
258        // Note that we use sync packet listeners because RosterListeners should be invoked in the same order as the
259        // roster stanzas arrive.
260        // Listen for any roster packets.
261        connection.registerIQRequestHandler(new RosterPushListener());
262        // Listen for any presence packets.
263        connection.addSyncStanzaListener(presencePacketListener, PRESENCE_PACKET_FILTER);
264
265        connection.addAsyncStanzaListener(new StanzaListener() {
266            @SuppressWarnings("fallthrough")
267            @Override
268            public void processStanza(Stanza stanza) throws NotConnectedException,
269                            InterruptedException, NotLoggedInException {
270                Presence presence = (Presence) stanza;
271                Jid from = presence.getFrom();
272                SubscribeAnswer subscribeAnswer = null;
273                switch (subscriptionMode) {
274                case manual:
275                    for (SubscribeListener subscribeListener : subscribeListeners) {
276                        subscribeAnswer = subscribeListener.processSubscribe(from, presence);
277                        if (subscribeAnswer != null) {
278                            break;
279                        }
280                    }
281                    if (subscribeAnswer == null) {
282                        return;
283                    }
284                    break;
285                case accept_all:
286                    // Accept all subscription requests.
287                    subscribeAnswer = SubscribeAnswer.Approve;
288                    break;
289                case reject_all:
290                    // Reject all subscription requests.
291                    subscribeAnswer = SubscribeAnswer.Deny;
292                    break;
293                }
294
295                if (subscribeAnswer == null) {
296                    return;
297                }
298
299                Presence.Type type;
300                switch (subscribeAnswer) {
301                case ApproveAndAlsoRequestIfRequired:
302                    BareJid bareFrom = from.asBareJid();
303                    RosterUtil.askForSubscriptionIfRequired(Roster.this, bareFrom);
304                    // The fall through is intended.
305                case Approve:
306                    type = Presence.Type.subscribed;
307                    break;
308                case Deny:
309                    type = Presence.Type.unsubscribed;
310                    break;
311                default:
312                    throw new AssertionError();
313                }
314
315                Presence response = connection.getStanzaFactory().buildPresenceStanza()
316                        .ofType(type)
317                        .to(presence.getFrom())
318                        .build();
319                connection.sendStanza(response);
320            }
321        }, PresenceTypeFilter.SUBSCRIBE);
322
323        // Listen for connection events
324        connection.addConnectionListener(new ConnectionListener() {
325
326            @Override
327            public void authenticated(XMPPConnection connection, boolean resumed) {
328                if (!isRosterLoadedAtLogin())
329                    return;
330                // We are done here if the connection was resumed
331                if (resumed) {
332                    return;
333                }
334
335                // Ensure that all available presences received so far in a eventually existing previous session are
336                // marked 'offline'.
337                setOfflinePresencesAndResetLoaded();
338
339                try {
340                    Roster.this.reload();
341                }
342                catch (InterruptedException | SmackException e) {
343                    LOGGER.log(Level.SEVERE, "Could not reload Roster", e);
344                    return;
345                }
346            }
347
348            @Override
349            public void connectionClosed() {
350                // Changes the presence available contacts to unavailable
351                setOfflinePresencesAndResetLoaded();
352            }
353
354        });
355
356        connection.addStanzaSendingListener(new StanzaListener() {
357            @Override
358            public void processStanza(Stanza stanzav) throws NotConnectedException, InterruptedException {
359                // Once we send an unavailable presence, the server is allowed to suppress sending presence status
360                // information to us as optimization (RFC 6121 § 4.4.2). Thus XMPP clients which are unavailable, should
361                // consider the presence information of their contacts as not up-to-date. We make the user obvious of
362                // this situation by setting the presences of all contacts to unavailable (while keeping the roster
363                // state).
364                setOfflinePresences();
365            }
366        }, OUTGOING_USER_UNAVAILABLE_PRESENCE);
367
368        // If the connection is already established, call reload
369        if (connection.isAuthenticated()) {
370            try {
371                reloadAndWait();
372            }
373            catch (InterruptedException | SmackException e) {
374                LOGGER.log(Level.SEVERE, "Could not reload Roster", e);
375            }
376        }
377
378    }
379
380    /**
381     * Retrieve the user presences (a map from resource to {@link Presence}) for a given XMPP entity represented by their bare JID.
382     *
383     * @param entity the entity
384     * @return the user presences
385     */
386    private Map<Resourcepart, Presence> getPresencesInternal(BareJid entity) {
387        Map<Resourcepart, Presence> entityPresences = presenceMap.get(entity);
388        if (entityPresences == null) {
389            entityPresences = nonRosterPresenceMap.lookup(entity);
390        }
391        return entityPresences;
392    }
393
394    /**
395     * Retrieve the user presences (a map from resource to {@link Presence}) for a given XMPP entity represented by their bare JID.
396     *
397     * @param entity the entity
398     * @return the user presences
399     */
400    private synchronized Map<Resourcepart, Presence> getOrCreatePresencesInternal(BareJid entity) {
401        Map<Resourcepart, Presence> entityPresences = getPresencesInternal(entity);
402        if (entityPresences == null) {
403            if (contains(entity)) {
404                entityPresences = new ConcurrentHashMap<>();
405                presenceMap.put(entity, entityPresences);
406            }
407            else {
408                LruCache<Resourcepart, Presence> nonRosterEntityPresences = new LruCache<>(32);
409                nonRosterPresenceMap.put(entity, nonRosterEntityPresences);
410                entityPresences = nonRosterEntityPresences;
411            }
412        }
413        return entityPresences;
414    }
415
416    /**
417     * Returns the subscription processing mode, which dictates what action
418     * Smack will take when subscription requests from other users are made.
419     * The default subscription mode is {@link SubscriptionMode#reject_all}.
420     * <p>
421     * If using the manual mode, a PacketListener should be registered that
422     * listens for Presence packets that have a type of
423     * {@link org.jivesoftware.smack.packet.Presence.Type#subscribe}.
424     * </p>
425     *
426     * @return the subscription mode.
427     */
428    public SubscriptionMode getSubscriptionMode() {
429        return subscriptionMode;
430    }
431
432    /**
433     * Sets the subscription processing mode, which dictates what action
434     * Smack will take when subscription requests from other users are made.
435     * The default subscription mode is {@link SubscriptionMode#reject_all}.
436     * <p>
437     * If using the manual mode, a PacketListener should be registered that
438     * listens for Presence packets that have a type of
439     * {@link org.jivesoftware.smack.packet.Presence.Type#subscribe}.
440     * </p>
441     *
442     * @param subscriptionMode the subscription mode.
443     */
444    public void setSubscriptionMode(SubscriptionMode subscriptionMode) {
445        this.subscriptionMode = subscriptionMode;
446    }
447
448    /**
449     * Reloads the entire roster from the server. This is an asynchronous operation,
450     * which means the method will return immediately, and the roster will be
451     * reloaded at a later point when the server responds to the reload request.
452     * @throws NotLoggedInException If not logged in.
453     * @throws NotConnectedException if the XMPP connection is not connected.
454     * @throws InterruptedException if the calling thread was interrupted.
455     */
456    public void reload() throws NotLoggedInException, NotConnectedException, InterruptedException {
457        final XMPPConnection connection = getAuthenticatedConnectionOrThrow();
458
459        RosterPacket packet = new RosterPacket();
460        if (rosterStore != null && isRosterVersioningSupported()) {
461            packet.setVersion(rosterStore.getRosterVersion());
462        }
463        rosterState = RosterState.loading;
464
465        SmackFuture<IQ, Exception> future = connection.sendIqRequestAsync(packet);
466
467        future.onSuccess(new RosterResultListener()).onError(new ExceptionCallback<Exception>() {
468
469            @Override
470            public void processException(Exception exception) {
471                rosterState = RosterState.uninitialized;
472                Level logLevel;
473                if (exception instanceof NotConnectedException) {
474                    logLevel = Level.FINE;
475                } else {
476                    logLevel = Level.SEVERE;
477                }
478                LOGGER.log(logLevel, "Exception reloading roster", exception);
479                for (RosterLoadedListener listener : rosterLoadedListeners) {
480                    listener.onRosterLoadingFailed(exception);
481                }
482            }
483
484        });
485    }
486
487    /**
488     * Reload the roster and block until it is reloaded.
489     *
490     * @throws NotLoggedInException if the XMPP connection is not authenticated.
491     * @throws NotConnectedException if the XMPP connection is not connected.
492     * @throws InterruptedException if the calling thread was interrupted.
493     * @since 4.1
494     */
495    public void reloadAndWait() throws NotLoggedInException, NotConnectedException, InterruptedException {
496        reload();
497        waitUntilLoaded();
498    }
499
500    /**
501     * Set the roster store, may cause a roster reload.
502     *
503     * @param rosterStore TODO javadoc me please
504     * @return true if the roster reload was initiated, false otherwise.
505     * @since 4.1
506     */
507    public boolean setRosterStore(RosterStore rosterStore) {
508        this.rosterStore = rosterStore;
509        try {
510            reload();
511        }
512        catch (InterruptedException | NotLoggedInException | NotConnectedException e) {
513            LOGGER.log(Level.FINER, "Could not reload roster", e);
514            return false;
515        }
516        return true;
517    }
518
519    boolean waitUntilLoaded() throws InterruptedException {
520        long waitTime = connection().getReplyTimeout();
521        long start = System.currentTimeMillis();
522        while (!isLoaded()) {
523            if (waitTime <= 0) {
524                break;
525            }
526            synchronized (this) {
527                if (!isLoaded()) {
528                    wait(waitTime);
529                }
530            }
531            long now = System.currentTimeMillis();
532            waitTime -= now - start;
533            start = now;
534        }
535        return isLoaded();
536    }
537
538    /**
539     * Check if the roster is loaded.
540     *
541     * @return true if the roster is loaded.
542     * @since 4.1
543     */
544    public boolean isLoaded() {
545        return rosterState == RosterState.loaded;
546    }
547
548    /**
549     * Adds a listener to this roster. The listener will be fired anytime one or more
550     * changes to the roster are pushed from the server.
551     *
552     * @param rosterListener a roster listener.
553     * @return true if the listener was not already added.
554     * @see #getEntriesAndAddListener(RosterListener, RosterEntries)
555     */
556    public boolean addRosterListener(RosterListener rosterListener) {
557        synchronized (rosterListenersAndEntriesLock) {
558            return rosterListeners.add(rosterListener);
559        }
560    }
561
562    /**
563     * Removes a listener from this roster. The listener will be fired anytime one or more
564     * changes to the roster are pushed from the server.
565     *
566     * @param rosterListener a roster listener.
567     * @return true if the listener was active and got removed.
568     */
569    public boolean removeRosterListener(RosterListener rosterListener) {
570        synchronized (rosterListenersAndEntriesLock) {
571            return rosterListeners.remove(rosterListener);
572        }
573    }
574
575    /**
576     * Add a roster loaded listener. Roster loaded listeners are invoked once the {@link Roster}
577     * was successfully loaded.
578     *
579     * @param rosterLoadedListener the listener to add.
580     * @return true if the listener was not already added.
581     * @see RosterLoadedListener
582     * @since 4.1
583     */
584    public boolean addRosterLoadedListener(RosterLoadedListener rosterLoadedListener) {
585        synchronized (rosterLoadedListener) {
586            return rosterLoadedListeners.add(rosterLoadedListener);
587        }
588    }
589
590    /**
591     * Remove a roster loaded listener.
592     *
593     * @param rosterLoadedListener the listener to remove.
594     * @return true if the listener was active and got removed.
595     * @see RosterLoadedListener
596     * @since 4.1
597     */
598    public boolean removeRosterLoadedListener(RosterLoadedListener rosterLoadedListener) {
599        synchronized (rosterLoadedListener) {
600            return rosterLoadedListeners.remove(rosterLoadedListener);
601        }
602    }
603
604    /**
605     * Add a {@link PresenceEventListener}. Such a listener will be fired whenever certain
606     * presence events happen.<p>
607     * Among those events are:
608     * <ul>
609     * <li> 'available' presence received
610     * <li> 'unavailable' presence received
611     * <li> 'error' presence received
612     * <li> 'subscribed' presence received
613     * <li> 'unsubscribed' presence received
614     * </ul>
615     * @param presenceEventListener listener to add.
616     * @return true if the listener was not already added.
617     */
618    public boolean addPresenceEventListener(PresenceEventListener presenceEventListener) {
619        return presenceEventListeners.add(presenceEventListener);
620    }
621
622    public boolean removePresenceEventListener(PresenceEventListener presenceEventListener) {
623        return presenceEventListeners.remove(presenceEventListener);
624    }
625
626    /**
627     * Creates a new group.
628     * <p>
629     * Note: you must add at least one entry to the group for the group to be kept
630     * after a logout/login. This is due to the way that XMPP stores group information.
631     * </p>
632     *
633     * @param name the name of the group.
634     * @return a new group, or null if the group already exists
635     */
636    public RosterGroup createGroup(String name) {
637        final XMPPConnection connection = connection();
638        if (groups.containsKey(name)) {
639            return groups.get(name);
640        }
641
642        RosterGroup group = new RosterGroup(name, connection);
643        groups.put(name, group);
644        return group;
645    }
646
647    /**
648     * Creates a new roster entry and presence subscription. The server will asynchronously
649     * update the roster with the subscription status.
650     *
651     * @param user   the user. (e.g. johndoe@jabber.org)
652     * @param name   the nickname of the user.
653     * @param groups the list of group names the entry will belong to, or <code>null</code> if the
654     *               the roster entry won't belong to a group.
655     * @throws NoResponseException if there was no response from the server.
656     * @throws XMPPErrorException if an XMPP exception occurs.
657     * @throws NotLoggedInException If not logged in.
658     * @throws NotConnectedException if the XMPP connection is not connected.
659     * @throws InterruptedException if the calling thread was interrupted.
660     * @deprecated use {@link #createItemAndRequestSubscription(BareJid, String, String[])} instead.
661     */
662    // TODO: Remove in Smack 4.5.
663    @Deprecated
664    public void createEntry(BareJid user, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
665        createItemAndRequestSubscription(user, name, groups);
666    }
667
668    /**
669     * Creates a new roster item. The server will asynchronously update the roster with the subscription status.
670     * <p>
671     * There will be no presence subscription request. Consider using
672     * {@link #createItemAndRequestSubscription(BareJid, String, String[])} if you also want to request a presence
673     * subscription from the contact.
674     * </p>
675     *
676     * @param jid the XMPP address of the contact (e.g. johndoe@jabber.org)
677     * @param name the nickname of the user.
678     * @param groups the list of group names the entry will belong to, or <code>null</code> if the the roster entry won't
679     *        belong to a group.
680     * @throws NoResponseException if there was no response from the server.
681     * @throws XMPPErrorException if an XMPP exception occurs.
682     * @throws NotLoggedInException If not logged in.
683     * @throws NotConnectedException if the XMPP connection is not connected.
684     * @throws InterruptedException if the calling thread was interrupted.
685     * @since 4.4.0
686     */
687    public void createItem(BareJid jid, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
688        final XMPPConnection connection = getAuthenticatedConnectionOrThrow();
689
690        // Create and send roster entry creation packet.
691        RosterPacket rosterPacket = new RosterPacket();
692        rosterPacket.setType(IQ.Type.set);
693        RosterPacket.Item item = new RosterPacket.Item(jid, name);
694        if (groups != null) {
695            for (String group : groups) {
696                if (group != null && group.trim().length() > 0) {
697                    item.addGroupName(group);
698                }
699            }
700        }
701        rosterPacket.addRosterItem(item);
702        connection.sendIqRequestAndWaitForResponse(rosterPacket);
703    }
704
705    /**
706     * Creates a new roster entry and presence subscription. The server will asynchronously
707     * update the roster with the subscription status.
708     *
709     * @param jid the XMPP address of the contact (e.g. johndoe@jabber.org)
710     * @param name   the nickname of the user.
711     * @param groups the list of group names the entry will belong to, or <code>null</code> if the
712     *               the roster entry won't belong to a group.
713     * @throws NoResponseException if there was no response from the server.
714     * @throws XMPPErrorException if an XMPP exception occurs.
715     * @throws NotLoggedInException If not logged in.
716     * @throws NotConnectedException if the XMPP connection is not connected.
717     * @throws InterruptedException if the calling thread was interrupted.
718     * @since 4.4.0
719     */
720    public void createItemAndRequestSubscription(BareJid jid, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
721        createItem(jid, name, groups);
722
723        sendSubscriptionRequest(jid);
724    }
725
726    /**
727     * Creates a new pre-approved roster entry and presence subscription. The server will
728     * asynchronously update the roster with the subscription status.
729     *
730     * @param user   the user. (e.g. johndoe@jabber.org)
731     * @param name   the nickname of the user.
732     * @param groups the list of group names the entry will belong to, or <code>null</code> if the
733     *               the roster entry won't belong to a group.
734     * @throws NoResponseException if there was no response from the server.
735     * @throws XMPPErrorException if an XMPP exception occurs.
736     * @throws NotLoggedInException if not logged in.
737     * @throws NotConnectedException if the XMPP connection is not connected.
738     * @throws InterruptedException if the calling thread was interrupted.
739     * @throws FeatureNotSupportedException if pre-approving is not supported.
740     * @since 4.2
741     */
742    public void preApproveAndCreateEntry(BareJid user, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, FeatureNotSupportedException {
743        preApprove(user);
744        createItemAndRequestSubscription(user, name, groups);
745    }
746
747    /**
748     * Pre-approve user presence subscription.
749     *
750     * @param user the user. (e.g. johndoe@jabber.org)
751     * @throws NotLoggedInException if not logged in.
752     * @throws NotConnectedException if the XMPP connection is not connected.
753     * @throws InterruptedException if the calling thread was interrupted.
754     * @throws FeatureNotSupportedException if pre-approving is not supported.
755     * @since 4.2
756     */
757    public void preApprove(BareJid user) throws NotLoggedInException, NotConnectedException, InterruptedException, FeatureNotSupportedException {
758        final XMPPConnection connection = connection();
759        if (!isSubscriptionPreApprovalSupported()) {
760            throw new FeatureNotSupportedException("Pre-approving");
761        }
762
763        Presence presencePacket = connection.getStanzaFactory().buildPresenceStanza()
764            .ofType(Presence.Type.subscribed)
765            .to(user)
766            .build();
767        connection.sendStanza(presencePacket);
768    }
769
770    /**
771     * Check for subscription pre-approval support.
772     *
773     * @return true if subscription pre-approval is supported by the server.
774     * @throws NotLoggedInException if not logged in.
775     * @since 4.2
776     */
777    public boolean isSubscriptionPreApprovalSupported() throws NotLoggedInException {
778        final XMPPConnection connection = getAuthenticatedConnectionOrThrow();
779        return connection.hasFeature(SubscriptionPreApproval.ELEMENT, SubscriptionPreApproval.NAMESPACE);
780    }
781
782    public void sendSubscriptionRequest(BareJid jid) throws NotLoggedInException, NotConnectedException, InterruptedException {
783        final XMPPConnection connection = getAuthenticatedConnectionOrThrow();
784
785        // Create a presence subscription packet and send.
786        Presence presencePacket = connection.getStanzaFactory().buildPresenceStanza()
787                .ofType(Presence.Type.subscribe)
788                .to(jid)
789                .build();
790        connection.sendStanza(presencePacket);
791    }
792
793    /**
794     * Add a subscribe listener, which is invoked on incoming subscription requests and if
795     * {@link SubscriptionMode} is set to {@link SubscriptionMode#manual}. This also sets subscription
796     * mode to {@link SubscriptionMode#manual}.
797     *
798     * @param subscribeListener the subscribe listener to add.
799     * @return <code>true</code> if the listener was not already added.
800     * @since 4.2
801     */
802    public boolean addSubscribeListener(SubscribeListener subscribeListener) {
803        Objects.requireNonNull(subscribeListener, "SubscribeListener argument must not be null");
804        if (subscriptionMode != SubscriptionMode.manual) {
805            previousSubscriptionMode = subscriptionMode;
806            subscriptionMode = SubscriptionMode.manual;
807        }
808        return subscribeListeners.add(subscribeListener);
809    }
810
811    /**
812     * Remove a subscribe listener. Also restores the previous subscription mode
813     * state, if the last listener got removed.
814     *
815     * @param subscribeListener TODO javadoc me please
816     *            the subscribe listener to remove.
817     * @return <code>true</code> if the listener registered and got removed.
818     * @since 4.2
819     */
820    public boolean removeSubscribeListener(SubscribeListener subscribeListener) {
821        boolean removed = subscribeListeners.remove(subscribeListener);
822        if (removed && subscribeListeners.isEmpty()) {
823            setSubscriptionMode(previousSubscriptionMode);
824        }
825        return removed;
826    }
827
828    /**
829     * Removes a roster entry from the roster. The roster entry will also be removed from the
830     * unfiled entries or from any roster group where it could belong and will no longer be part
831     * of the roster. Note that this is a synchronous call -- Smack must wait for the server
832     * to send an updated subscription status.
833     *
834     * @param entry a roster entry.
835     * @throws XMPPErrorException if an XMPP error occurs.
836     * @throws NotLoggedInException if not logged in.
837     * @throws NoResponseException SmackException if there was no response from the server.
838     * @throws NotConnectedException if the XMPP connection is not connected.
839     * @throws InterruptedException if the calling thread was interrupted.
840     */
841    public void removeEntry(RosterEntry entry) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
842        final XMPPConnection connection = getAuthenticatedConnectionOrThrow();
843
844        // Only remove the entry if it's in the entry list.
845        // The actual removal logic takes place in RosterPacketListenerProcess>>Packet(Packet)
846        if (!entries.containsKey(entry.getJid())) {
847            return;
848        }
849        RosterPacket packet = new RosterPacket();
850        packet.setType(IQ.Type.set);
851        RosterPacket.Item item = RosterEntry.toRosterItem(entry);
852        // Set the item type as REMOVE so that the server will delete the entry
853        item.setItemType(RosterPacket.ItemType.remove);
854        packet.addRosterItem(item);
855        connection.sendIqRequestAndWaitForResponse(packet);
856    }
857
858    /**
859     * Returns a count of the entries in the roster.
860     *
861     * @return the number of entries in the roster.
862     */
863    public int getEntryCount() {
864        return getEntries().size();
865    }
866
867    /**
868     * Add a roster listener and invoke the roster entries with all entries of the roster.
869     * <p>
870     * The method guarantees that the listener is only invoked after
871     * {@link RosterEntries#rosterEntries(Collection)} has been invoked, and that all roster events
872     * that happen while <code>rosterEntries(Collection) </code> is called are queued until the
873     * method returns.
874     * </p>
875     * <p>
876     * This guarantee makes this the ideal method to e.g. populate a UI element with the roster while
877     * installing a {@link RosterListener} to listen for subsequent roster events.
878     * </p>
879     *
880     * @param rosterListener the listener to install
881     * @param rosterEntries the roster entries callback interface
882     * @since 4.1
883     */
884    public void getEntriesAndAddListener(RosterListener rosterListener, RosterEntries rosterEntries) {
885        Objects.requireNonNull(rosterListener, "listener must not be null");
886        Objects.requireNonNull(rosterEntries, "rosterEntries must not be null");
887
888        synchronized (rosterListenersAndEntriesLock) {
889            rosterEntries.rosterEntries(entries.values());
890            addRosterListener(rosterListener);
891        }
892    }
893
894    /**
895     * Returns a set of all entries in the roster, including entries
896     * that don't belong to any groups.
897     *
898     * @return all entries in the roster.
899     */
900    public Set<RosterEntry> getEntries() {
901        Set<RosterEntry> allEntries;
902        synchronized (rosterListenersAndEntriesLock) {
903            allEntries = new HashSet<>(entries.size());
904            for (RosterEntry entry : entries.values()) {
905                allEntries.add(entry);
906            }
907        }
908        return allEntries;
909    }
910
911    /**
912     * Returns a count of the unfiled entries in the roster. An unfiled entry is
913     * an entry that doesn't belong to any groups.
914     *
915     * @return the number of unfiled entries in the roster.
916     */
917    public int getUnfiledEntryCount() {
918        return unfiledEntries.size();
919    }
920
921    /**
922     * Returns an unmodifiable set for the unfiled roster entries. An unfiled entry is
923     * an entry that doesn't belong to any groups.
924     *
925     * @return the unfiled roster entries.
926     */
927    public Set<RosterEntry> getUnfiledEntries() {
928        return Collections.unmodifiableSet(unfiledEntries);
929    }
930
931    /**
932     * Returns the roster entry associated with the given XMPP address or
933     * <code>null</code> if the user is not an entry in the roster.
934     *
935     * @param jid the XMPP address of the user (eg "jsmith@example.com"). The address could be
936     *             in any valid format (e.g. "domain/resource", "user@domain" or "user@domain/resource").
937     * @return the roster entry or <code>null</code> if it does not exist.
938     */
939    public RosterEntry getEntry(BareJid jid) {
940        if (jid == null) {
941            return null;
942        }
943        return entries.get(jid);
944    }
945
946    /**
947     * Returns true if the specified XMPP address is an entry in the roster.
948     *
949     * @param jid the XMPP address of the user (eg "jsmith@example.com"). The
950     *             address must be a bare JID e.g. "domain/resource" or
951     *             "user@domain".
952     * @return true if the XMPP address is an entry in the roster.
953     */
954    public boolean contains(BareJid jid) {
955        return getEntry(jid) != null;
956    }
957
958    /**
959     * Returns the roster group with the specified name, or <code>null</code> if the
960     * group doesn't exist.
961     *
962     * @param name the name of the group.
963     * @return the roster group with the specified name.
964     */
965    public RosterGroup getGroup(String name) {
966        return groups.get(name);
967    }
968
969    /**
970     * Returns the number of the groups in the roster.
971     *
972     * @return the number of groups in the roster.
973     */
974    public int getGroupCount() {
975        return groups.size();
976    }
977
978    /**
979     * Returns an unmodifiable collections of all the roster groups.
980     *
981     * @return an iterator for all roster groups.
982     */
983    public Collection<RosterGroup> getGroups() {
984        return Collections.unmodifiableCollection(groups.values());
985    }
986
987    /**
988     * Returns the presence info for a particular user. If the user is offline, or
989     * if no presence data is available (such as when you are not subscribed to the
990     * user's presence updates), unavailable presence will be returned.
991     *
992     * If the user has several presences (one for each resource), then the presence with
993     * highest priority will be returned. If multiple presences have the same priority,
994     * the one with the "most available" presence mode will be returned. In order,
995     * that's {@link org.jivesoftware.smack.packet.Presence.Mode#chat free to chat},
996     * {@link org.jivesoftware.smack.packet.Presence.Mode#available available},
997     * {@link org.jivesoftware.smack.packet.Presence.Mode#away away},
998     * {@link org.jivesoftware.smack.packet.Presence.Mode#xa extended away}, and
999     * {@link org.jivesoftware.smack.packet.Presence.Mode#dnd do not disturb}.
1000     *
1001     * <p>
1002     * Note that presence information is received asynchronously. So, just after logging
1003     * in to the server, presence values for users in the roster may be unavailable
1004     * even if they are actually online. In other words, the value returned by this
1005     * method should only be treated as a snapshot in time, and may not accurately reflect
1006     * other user's presence instant by instant. If you need to track presence over time,
1007     * such as when showing a visual representation of the roster, consider using a
1008     * {@link RosterListener}.
1009     * </p>
1010     *
1011     * @param jid the XMPP address of the user (eg "jsmith@example.com"). The
1012     *             address must be a bare JID e.g. "domain/resource" or
1013     *             "user@domain".
1014     * @return the user's current presence, or unavailable presence if the user is offline
1015     *         or if no presence information is available..
1016     */
1017    public Presence getPresence(BareJid jid) {
1018        Map<Resourcepart, Presence> userPresences = getPresencesInternal(jid);
1019        if (userPresences == null) {
1020            Presence presence = synthesizeUnvailablePresence(jid);
1021            return presence;
1022        }
1023        else {
1024            // Find the resource with the highest priority
1025            // Might be changed to use the resource with the highest availability instead.
1026            Presence presence = null;
1027            // This is used in case no available presence is found
1028            Presence unavailable = null;
1029
1030            for (Presence p : userPresences.values()) {
1031                if (!p.isAvailable()) {
1032                    unavailable = p;
1033                    continue;
1034                }
1035                // Chose presence with highest priority first.
1036                if (presence == null || p.getPriority() > presence.getPriority()) {
1037                    presence = p;
1038                }
1039                // If equal priority, choose "most available" by the mode value.
1040                else if (p.getPriority() == presence.getPriority()) {
1041                    Presence.Mode pMode = p.getMode();
1042                    // Default to presence mode of available.
1043                    if (pMode == null) {
1044                        pMode = Presence.Mode.available;
1045                    }
1046                    Presence.Mode presenceMode = presence.getMode();
1047                    // Default to presence mode of available.
1048                    if (presenceMode == null) {
1049                        presenceMode = Presence.Mode.available;
1050                    }
1051                    if (pMode.compareTo(presenceMode) < 0) {
1052                        presence = p;
1053                    }
1054                }
1055            }
1056            if (presence == null) {
1057                if (unavailable != null) {
1058                    return unavailable;
1059                }
1060                else {
1061                    presence = synthesizeUnvailablePresence(jid);
1062                    return presence;
1063                }
1064            }
1065            else {
1066                return presence;
1067            }
1068        }
1069    }
1070
1071    /**
1072     * Returns the presence info for a particular user's resource, or unavailable presence
1073     * if the user is offline or if no presence information is available, such as
1074     * when you are not subscribed to the user's presence updates.
1075     *
1076     * @param userWithResource a fully qualified XMPP ID including a resource (user@domain/resource).
1077     * @return the user's current presence, or unavailable presence if the user is offline
1078     *         or if no presence information is available.
1079     */
1080    public Presence getPresenceResource(FullJid userWithResource) {
1081        BareJid key = userWithResource.asBareJid();
1082        Resourcepart resource = userWithResource.getResourcepart();
1083        Map<Resourcepart, Presence> userPresences = getPresencesInternal(key);
1084        if (userPresences == null) {
1085            Presence presence = synthesizeUnvailablePresence(userWithResource);
1086            return presence;
1087        }
1088        else {
1089            Presence presence = userPresences.get(resource);
1090            if (presence == null) {
1091                presence = synthesizeUnvailablePresence(userWithResource);
1092                return presence;
1093            }
1094            else {
1095                return presence;
1096            }
1097        }
1098    }
1099
1100    /**
1101     * Returns a List of Presence objects for all of a user's current presences if no presence information is available,
1102     * such as when you are not subscribed to the user's presence updates.
1103     *
1104     * @param bareJid an XMPP ID, e.g. jdoe@example.com.
1105     * @return a List of Presence objects for all the user's current presences, or an unavailable presence if no
1106     *         presence information is available.
1107     */
1108    public List<Presence> getAllPresences(BareJid bareJid) {
1109        Map<Resourcepart, Presence> userPresences = getPresencesInternal(bareJid);
1110        List<Presence> res;
1111        if (userPresences == null) {
1112            // Create an unavailable presence if none was found
1113            Presence unavailable = synthesizeUnvailablePresence(bareJid);
1114            res = new ArrayList<>(Arrays.asList(unavailable));
1115        } else {
1116            res = new ArrayList<>(userPresences.values().size());
1117            for (Presence presence : userPresences.values()) {
1118                res.add(presence);
1119            }
1120        }
1121        return res;
1122    }
1123
1124    /**
1125     * Returns a List of all <b>available</b> Presence Objects for the given bare JID. If there are no available
1126     * presences, then the empty list will be returned.
1127     *
1128     * @param bareJid the bare JID from which the presences should be retrieved.
1129     * @return available presences for the bare JID.
1130     */
1131    public List<Presence> getAvailablePresences(BareJid bareJid) {
1132        List<Presence> allPresences = getAllPresences(bareJid);
1133        List<Presence> res = new ArrayList<>(allPresences.size());
1134        for (Presence presence : allPresences) {
1135            if (presence.isAvailable()) {
1136                // No need to clone presence here, getAllPresences already returns clones
1137                res.add(presence);
1138            }
1139        }
1140        return res;
1141    }
1142
1143    /**
1144     * Returns a List of Presence objects for all of a user's current presences
1145     * or an unavailable presence if the user is unavailable (offline) or if no presence
1146     * information is available, such as when you are not subscribed to the user's presence
1147     * updates.
1148     *
1149     * @param jid an XMPP ID, e.g. jdoe@example.com.
1150     * @return a List of Presence objects for all the user's current presences,
1151     *         or an unavailable presence if the user is offline or if no presence information
1152     *         is available.
1153     */
1154    public List<Presence> getPresences(BareJid jid) {
1155        List<Presence> res;
1156        Map<Resourcepart, Presence> userPresences = getPresencesInternal(jid);
1157        if (userPresences == null) {
1158            Presence presence = synthesizeUnvailablePresence(jid);
1159            res = Arrays.asList(presence);
1160        }
1161        else {
1162            List<Presence> answer = new ArrayList<>();
1163            // Used in case no available presence is found
1164            Presence unavailable = null;
1165            for (Presence presence : userPresences.values()) {
1166                if (presence.isAvailable()) {
1167                    answer.add(presence);
1168                }
1169                else {
1170                    unavailable = presence;
1171                }
1172            }
1173            if (!answer.isEmpty()) {
1174                res = answer;
1175            }
1176            else if (unavailable != null) {
1177                res = Arrays.asList(unavailable);
1178            }
1179            else {
1180                Presence presence = synthesizeUnvailablePresence(jid);
1181                res = Arrays.asList(presence);
1182            }
1183        }
1184        return res;
1185    }
1186
1187    /**
1188     * Check if the given JID is subscribed to the user's presence.
1189     * <p>
1190     * If the JID is subscribed to the user's presence then it is allowed to see the presence and
1191     * will get notified about presence changes. Also returns true, if the JID is the service
1192     * name of the XMPP connection (the "XMPP domain"), i.e. the XMPP service is treated like
1193     * having an implicit subscription to the users presence.
1194     * </p>
1195     * Note that if the roster is not loaded, then this method will always return false.
1196     *
1197     * @param jid TODO javadoc me please
1198     * @return true if the given JID is allowed to see the users presence.
1199     * @since 4.1
1200     */
1201    public boolean isSubscribedToMyPresence(Jid jid) {
1202        if (jid == null) {
1203            return false;
1204        }
1205        BareJid bareJid = jid.asBareJid();
1206        if (connection().getXMPPServiceDomain().equals(bareJid)) {
1207            return true;
1208        }
1209        RosterEntry entry = getEntry(bareJid);
1210        if (entry == null) {
1211            return false;
1212        }
1213        return entry.canSeeMyPresence();
1214    }
1215
1216    /**
1217     * Check if the XMPP entity this roster belongs to is subscribed to the presence of the given JID.
1218     *
1219     * @param jid the jid to check.
1220     * @return <code>true</code> if we are subscribed to the presence of the given jid.
1221     * @since 4.2
1222     */
1223    public boolean iAmSubscribedTo(Jid jid) {
1224        if (jid == null) {
1225            return false;
1226        }
1227        BareJid bareJid = jid.asBareJid();
1228        RosterEntry entry = getEntry(bareJid);
1229        if (entry == null) {
1230            return false;
1231        }
1232        return entry.canSeeHisPresence();
1233    }
1234
1235    /**
1236     * Sets if the roster will be loaded from the server when logging in for newly created instances
1237     * of {@link Roster}.
1238     *
1239     * @param rosterLoadedAtLoginDefault if the roster will be loaded from the server when logging in.
1240     * @see #setRosterLoadedAtLogin(boolean)
1241     * @since 4.1.7
1242     */
1243    public static void setRosterLoadedAtLoginDefault(boolean rosterLoadedAtLoginDefault) {
1244        Roster.rosterLoadedAtLoginDefault = rosterLoadedAtLoginDefault;
1245    }
1246
1247    /**
1248     * Sets if the roster will be loaded from the server when logging in. This
1249     * is the common behaviour for clients but sometimes clients may want to differ this
1250     * or just never do it if not interested in rosters.
1251     *
1252     * @param rosterLoadedAtLogin if the roster will be loaded from the server when logging in.
1253     */
1254    public void setRosterLoadedAtLogin(boolean rosterLoadedAtLogin) {
1255        this.rosterLoadedAtLogin = rosterLoadedAtLogin;
1256    }
1257
1258    /**
1259     * Returns true if the roster will be loaded from the server when logging in. This
1260     * is the common behavior for clients but sometimes clients may want to differ this
1261     * or just never do it if not interested in rosters.
1262     *
1263     * @return true if the roster will be loaded from the server when logging in.
1264     * @see <a href="http://xmpp.org/rfcs/rfc6121.html#roster-login">RFC 6121 2.2 - Retrieving the Roster on Login</a>
1265     */
1266    public boolean isRosterLoadedAtLogin() {
1267        return rosterLoadedAtLogin;
1268    }
1269
1270    RosterStore getRosterStore() {
1271        return rosterStore;
1272    }
1273
1274    /**
1275     * Changes the presence of available contacts offline by simulating an unavailable
1276     * presence sent from the server.
1277     */
1278    private void setOfflinePresences() {
1279        outerloop: for (Jid user : presenceMap.keySet()) {
1280            Map<Resourcepart, Presence> resources = presenceMap.get(user);
1281            if (resources != null) {
1282                for (Resourcepart resource : resources.keySet()) {
1283                    PresenceBuilder presenceBuilder = StanzaBuilder.buildPresence()
1284                            .ofType(Presence.Type.unavailable);
1285                    EntityBareJid bareUserJid = user.asEntityBareJidIfPossible();
1286                    if (bareUserJid == null) {
1287                        LOGGER.warning("Can not transform user JID to bare JID: '" + user + "'");
1288                        continue;
1289                    }
1290                    presenceBuilder.from(JidCreate.fullFrom(bareUserJid, resource));
1291                    try {
1292                        presencePacketListener.processStanza(presenceBuilder.build());
1293                    }
1294                    catch (NotConnectedException e) {
1295                        throw new IllegalStateException(
1296                                        "presencePacketListener should never throw a NotConnectedException when processStanza is called with a presence of type unavailable",
1297                                        e);
1298                    }
1299                    catch (InterruptedException e) {
1300                        break outerloop;
1301                    }
1302                }
1303            }
1304        }
1305    }
1306
1307    /**
1308     * Changes the presence of available contacts offline by simulating an unavailable
1309     * presence sent from the server. After a disconnection, every Presence is set
1310     * to offline.
1311     */
1312    private void setOfflinePresencesAndResetLoaded() {
1313        setOfflinePresences();
1314        rosterState = RosterState.uninitialized;
1315    }
1316
1317    /**
1318     * Fires roster changed event to roster listeners indicating that the
1319     * specified collections of contacts have been added, updated or deleted
1320     * from the roster.
1321     *
1322     * @param addedEntries   the collection of address of the added contacts.
1323     * @param updatedEntries the collection of address of the updated contacts.
1324     * @param deletedEntries the collection of address of the deleted contacts.
1325     */
1326    private void fireRosterChangedEvent(final Collection<Jid> addedEntries, final Collection<Jid> updatedEntries,
1327                    final Collection<Jid> deletedEntries) {
1328        synchronized (rosterListenersAndEntriesLock) {
1329            for (RosterListener listener : rosterListeners) {
1330                if (!addedEntries.isEmpty()) {
1331                    listener.entriesAdded(addedEntries);
1332                }
1333                if (!updatedEntries.isEmpty()) {
1334                    listener.entriesUpdated(updatedEntries);
1335                }
1336                if (!deletedEntries.isEmpty()) {
1337                    listener.entriesDeleted(deletedEntries);
1338                }
1339            }
1340        }
1341    }
1342
1343    /**
1344     * Fires roster presence changed event to roster listeners.
1345     *
1346     * @param presence the presence change.
1347     */
1348    private void fireRosterPresenceEvent(final Presence presence) {
1349        synchronized (rosterListenersAndEntriesLock) {
1350            for (RosterListener listener : rosterListeners) {
1351                listener.presenceChanged(presence);
1352            }
1353        }
1354    }
1355
1356    private void addUpdateEntry(Collection<Jid> addedEntries, Collection<Jid> updatedEntries,
1357                    Collection<Jid> unchangedEntries, RosterPacket.Item item, RosterEntry entry) {
1358        RosterEntry oldEntry;
1359        synchronized (rosterListenersAndEntriesLock) {
1360            oldEntry = entries.put(item.getJid(), entry);
1361        }
1362        if (oldEntry == null) {
1363            BareJid jid = item.getJid();
1364            addedEntries.add(jid);
1365            // Move the eventually existing presences from nonRosterPresenceMap to presenceMap.
1366            move(jid, nonRosterPresenceMap, presenceMap);
1367        }
1368        else {
1369            RosterPacket.Item oldItem = RosterEntry.toRosterItem(oldEntry);
1370            if (!oldEntry.equalsDeep(entry) || !item.getGroupNames().equals(oldItem.getGroupNames())) {
1371                updatedEntries.add(item.getJid());
1372                oldEntry.updateItem(item);
1373            } else {
1374                // Record the entry as unchanged, so that it doesn't end up as deleted entry
1375                unchangedEntries.add(item.getJid());
1376            }
1377        }
1378
1379        // Mark the entry as unfiled if it does not belong to any groups.
1380        if (item.getGroupNames().isEmpty()) {
1381            unfiledEntries.add(entry);
1382        }
1383        else {
1384            unfiledEntries.remove(entry);
1385        }
1386
1387        // Add the entry/user to the groups
1388        List<String> newGroupNames = new ArrayList<>();
1389        for (String groupName : item.getGroupNames()) {
1390            // Add the group name to the list.
1391            newGroupNames.add(groupName);
1392
1393            // Add the entry to the group.
1394            RosterGroup group = getGroup(groupName);
1395            if (group == null) {
1396                group = createGroup(groupName);
1397                groups.put(groupName, group);
1398            }
1399            // Add the entry.
1400            group.addEntryLocal(entry);
1401        }
1402
1403        // Remove user from the remaining groups.
1404        List<String> oldGroupNames = new ArrayList<>();
1405        for (RosterGroup group : getGroups()) {
1406            oldGroupNames.add(group.getName());
1407        }
1408        oldGroupNames.removeAll(newGroupNames);
1409
1410        for (String groupName : oldGroupNames) {
1411            RosterGroup group = getGroup(groupName);
1412            group.removeEntryLocal(entry);
1413            if (group.getEntryCount() == 0) {
1414                groups.remove(groupName);
1415            }
1416        }
1417    }
1418
1419    private void deleteEntry(Collection<Jid> deletedEntries, RosterEntry entry) {
1420        BareJid user = entry.getJid();
1421        entries.remove(user);
1422        unfiledEntries.remove(entry);
1423        // Move the presences from the presenceMap to the nonRosterPresenceMap.
1424        move(user, presenceMap, nonRosterPresenceMap);
1425        deletedEntries.add(user);
1426
1427        for (Map.Entry<String, RosterGroup> e : groups.entrySet()) {
1428            RosterGroup group = e.getValue();
1429            group.removeEntryLocal(entry);
1430            if (group.getEntryCount() == 0) {
1431                groups.remove(e.getKey());
1432            }
1433        }
1434    }
1435
1436    /**
1437     * Removes all the groups with no entries.
1438     *
1439     * This is used by {@link RosterPushListener} and {@link RosterResultListener} to
1440     * cleanup groups after removing contacts.
1441     */
1442    private void removeEmptyGroups() {
1443        // We have to do this because RosterGroup.removeEntry removes the entry immediately
1444        // (locally) and the group could remain empty.
1445        // TODO Check the performance/logic for rosters with large number of groups
1446        for (RosterGroup group : getGroups()) {
1447            if (group.getEntryCount() == 0) {
1448                groups.remove(group.getName());
1449            }
1450        }
1451    }
1452
1453    /**
1454     * Move presences from 'entity' from one presence map to another.
1455     *
1456     * @param entity the entity
1457     * @param from the map to move presences from
1458     * @param to the map to move presences to
1459     */
1460    private static void move(BareJid entity, Map<BareJid, Map<Resourcepart, Presence>> from, Map<BareJid, Map<Resourcepart, Presence>> to) {
1461        Map<Resourcepart, Presence> presences = from.remove(entity);
1462        if (presences != null && !presences.isEmpty()) {
1463            to.put(entity, presences);
1464        }
1465    }
1466
1467    /**
1468     * Ignore ItemTypes as of RFC 6121, 2.1.2.5.
1469     *
1470     * This is used by {@link RosterPushListener} and {@link RosterResultListener}.
1471     * */
1472    private static boolean hasValidSubscriptionType(RosterPacket.Item item) {
1473        switch (item.getItemType()) {
1474            case none:
1475            case from:
1476            case to:
1477            case both:
1478                return true;
1479            default:
1480                return false;
1481        }
1482    }
1483
1484    private static Presence synthesizeUnvailablePresence(Jid from) {
1485        return StanzaBuilder.buildPresence()
1486                .ofType(Presence.Type.unavailable)
1487                .from(from)
1488                .build();
1489    }
1490
1491    /**
1492     * Check if the server supports roster versioning.
1493     *
1494     * @return true if the server supports roster versioning, false otherwise.
1495     */
1496    public boolean isRosterVersioningSupported() {
1497        return connection().hasFeature(RosterVer.ELEMENT, RosterVer.NAMESPACE);
1498    }
1499
1500    /**
1501     * An enumeration for the subscription mode options.
1502     */
1503    public enum SubscriptionMode {
1504
1505        /**
1506         * Automatically accept all subscription and unsubscription requests.
1507         * This is suitable for simple clients. More complex clients will
1508         * likely wish to handle subscription requests manually.
1509         */
1510        accept_all,
1511
1512        /**
1513         * Automatically reject all subscription requests. This is the default mode.
1514         */
1515        reject_all,
1516
1517        /**
1518         * Subscription requests are ignored, which means they must be manually
1519         * processed by registering a listener for presence packets and then looking
1520         * for any presence requests that have the type Presence.Type.SUBSCRIBE or
1521         * Presence.Type.UNSUBSCRIBE.
1522         */
1523        manual
1524    }
1525
1526    /**
1527     * Listens for all presence packets and processes them.
1528     */
1529    private class PresencePacketListener implements StanzaListener {
1530
1531        @Override
1532        public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException {
1533            // Try to ensure that the roster is loaded when processing presence stanzas. While the
1534            // presence listener is synchronous, the roster result listener is not, which means that
1535            // the presence listener may be invoked with a not yet loaded roster.
1536            if (rosterState == RosterState.loading) {
1537                try {
1538                    waitUntilLoaded();
1539                }
1540                catch (InterruptedException e) {
1541                    LOGGER.log(Level.INFO, "Presence listener was interrupted", e);
1542
1543                }
1544            }
1545            if (!isLoaded() && rosterLoadedAtLogin) {
1546                LOGGER.warning("Roster not loaded while processing " + packet);
1547            }
1548            final Presence presence = (Presence) packet;
1549            final Jid from = presence.getFrom();
1550
1551            final BareJid key;
1552            if (from != null) {
1553                key = from.asBareJid();
1554            } else {
1555                XMPPConnection connection = connection();
1556                if (connection == null) {
1557                    LOGGER.finest("Connection was null while trying to handle exotic presence stanza: " + presence);
1558                    return;
1559                }
1560                // Assume the presence come "from the users account on the server" since no from was set (RFC 6120 §
1561                // 8.1.2.1 4.). Note that getUser() may return null, but should never return null in this case as where
1562                // connected.
1563                EntityFullJid myJid = connection.getUser();
1564                if (myJid == null) {
1565                    LOGGER.info(
1566                            "Connection had no local address in Roster's presence listener."
1567                            + " Possibly we received a presence without from before being authenticated."
1568                            + " Presence: " + presence);
1569                    return;
1570                }
1571                LOGGER.info("Exotic presence stanza without from received: " + presence);
1572                key = myJid.asBareJid();
1573            }
1574
1575            asyncButOrdered.performAsyncButOrdered(key, new Runnable() {
1576                @Override
1577                public void run() {
1578                    Resourcepart fromResource = Resourcepart.EMPTY;
1579                    BareJid bareFrom = null;
1580                    FullJid fullFrom = null;
1581                    if (from != null) {
1582                        fromResource = from.getResourceOrNull();
1583                        if (fromResource == null) {
1584                            fromResource = Resourcepart.EMPTY;
1585                            bareFrom = from.asBareJid();
1586                        }
1587                        else {
1588                            fullFrom = from.asFullJidIfPossible();
1589                            // We know that this must be a full JID in this case.
1590                            assert fullFrom != null;
1591                        }
1592                    }
1593                    Map<Resourcepart, Presence> userPresences;
1594                    // If an "available" presence, add it to the presence map. Each presence
1595                    // map will hold for a particular user a map with the presence
1596                    // packets saved for each resource.
1597                    switch (presence.getType()) {
1598                    case available:
1599                        // Get the user presence map
1600                        userPresences = getOrCreatePresencesInternal(key);
1601                        // See if an offline presence was being stored in the map. If so, remove
1602                        // it since we now have an online presence.
1603                        userPresences.remove(Resourcepart.EMPTY);
1604                        // Add the new presence, using the resources as a key.
1605                        userPresences.put(fromResource, presence);
1606                        // If the user is in the roster, fire an event.
1607                        if (contains(key)) {
1608                            fireRosterPresenceEvent(presence);
1609                        }
1610                        for (PresenceEventListener presenceEventListener : presenceEventListeners) {
1611                            presenceEventListener.presenceAvailable(fullFrom, presence);
1612                        }
1613                        break;
1614                    // If an "unavailable" packet.
1615                    case unavailable:
1616                        // If no resource, this is likely an offline presence as part of
1617                        // a roster presence flood. In that case, we store it.
1618                        userPresences = getOrCreatePresencesInternal(key);
1619                        if (from.hasNoResource()) {
1620                            // Get the user presence map
1621                            userPresences.put(Resourcepart.EMPTY, presence);
1622                        }
1623                        // Otherwise, this is a normal offline presence.
1624                        else {
1625                            // Store the offline presence, as it may include extra information
1626                            // such as the user being on vacation.
1627                            userPresences.put(fromResource, presence);
1628                        }
1629                        // If the user is in the roster, fire an event.
1630                        if (contains(key)) {
1631                            fireRosterPresenceEvent(presence);
1632                        }
1633
1634                        // Ensure that 'from' is a full JID before invoking the presence unavailable
1635                        // listeners. Usually unavailable presences always have a resourcepart, i.e. are
1636                        // full JIDs, but RFC 6121 § 4.5.4 has an implementation note that unavailable
1637                        // presences from a bare JID SHOULD be treated as applying to all resources. I don't
1638                        // think any client or server ever implemented that, I do think that this
1639                        // implementation note is a terrible idea since it adds another corner case in
1640                        // client code, instead of just having the invariant
1641                        // "unavailable presences are always from the full JID".
1642                        if (fullFrom != null) {
1643                            for (PresenceEventListener presenceEventListener : presenceEventListeners) {
1644                                presenceEventListener.presenceUnavailable(fullFrom, presence);
1645                            }
1646                        } else {
1647                            LOGGER.fine("Unavailable presence from bare JID: " + presence);
1648                        }
1649
1650                        break;
1651                    // Error presence packets from a bare JID mean we invalidate all existing
1652                    // presence info for the user.
1653                    case error:
1654                        // No need to act on error presences send without from, i.e.
1655                        // directly send from the users XMPP service, or where the from
1656                        // address is not a bare JID
1657                        if (from == null || !from.isEntityBareJid()) {
1658                            break;
1659                        }
1660                        userPresences = getOrCreatePresencesInternal(key);
1661                        // Any other presence data is invalidated by the error packet.
1662                        userPresences.clear();
1663
1664                        // Set the new presence using the empty resource as a key.
1665                        userPresences.put(Resourcepart.EMPTY, presence);
1666                        // If the user is in the roster, fire an event.
1667                        if (contains(key)) {
1668                            fireRosterPresenceEvent(presence);
1669                        }
1670                        for (PresenceEventListener presenceEventListener : presenceEventListeners) {
1671                            presenceEventListener.presenceError(from, presence);
1672                        }
1673                        break;
1674                    case subscribed:
1675                        for (PresenceEventListener presenceEventListener : presenceEventListeners) {
1676                            presenceEventListener.presenceSubscribed(bareFrom, presence);
1677                        }
1678                        break;
1679                    case unsubscribed:
1680                        for (PresenceEventListener presenceEventListener : presenceEventListeners) {
1681                            presenceEventListener.presenceUnsubscribed(bareFrom, presence);
1682                        }
1683                        break;
1684                    default:
1685                        break;
1686                    }
1687                }
1688            });
1689        }
1690    }
1691
1692    /**
1693     * Handles Roster results as described in <a href="https://tools.ietf.org/html/rfc6121#section-2.1.4">RFC 6121 2.1.4</a>.
1694     */
1695    private class RosterResultListener implements SuccessCallback<IQ> {
1696
1697        @Override
1698        public void onSuccess(IQ packet) {
1699            final XMPPConnection connection = connection();
1700            LOGGER.log(Level.FINE, "RosterResultListener received {0}", packet);
1701            Collection<Jid> addedEntries = new ArrayList<>();
1702            Collection<Jid> updatedEntries = new ArrayList<>();
1703            Collection<Jid> deletedEntries = new ArrayList<>();
1704            Collection<Jid> unchangedEntries = new ArrayList<>();
1705
1706            if (packet instanceof RosterPacket) {
1707                // Non-empty roster result. This stanza contains all the roster elements.
1708                RosterPacket rosterPacket = (RosterPacket) packet;
1709
1710                // Ignore items without valid subscription type
1711                ArrayList<Item> validItems = new ArrayList<>();
1712                for (RosterPacket.Item item : rosterPacket.getRosterItems()) {
1713                    if (hasValidSubscriptionType(item)) {
1714                        validItems.add(item);
1715                    }
1716                }
1717
1718                for (RosterPacket.Item item : validItems) {
1719                    RosterEntry entry = new RosterEntry(item, Roster.this, connection);
1720                    addUpdateEntry(addedEntries, updatedEntries, unchangedEntries, item, entry);
1721                }
1722
1723                // Delete all entries which where not added or updated
1724                Set<Jid> toDelete = new HashSet<>();
1725                for (RosterEntry entry : entries.values()) {
1726                    toDelete.add(entry.getJid());
1727                }
1728                toDelete.removeAll(addedEntries);
1729                toDelete.removeAll(updatedEntries);
1730                toDelete.removeAll(unchangedEntries);
1731                for (Jid user : toDelete) {
1732                    deleteEntry(deletedEntries, entries.get(user));
1733                }
1734
1735                if (rosterStore != null) {
1736                    String version = rosterPacket.getVersion();
1737                    rosterStore.resetEntries(validItems, version);
1738                }
1739
1740                removeEmptyGroups();
1741            }
1742            else {
1743                // Empty roster result as defined in RFC6121 2.6.3. An empty roster result basically
1744                // means that rosterver was used and the roster hasn't changed (much) since the
1745                // version we presented the server. So we simply load the roster from the store and
1746                // await possible further roster pushes.
1747                List<RosterPacket.Item> storedItems = rosterStore.getEntries();
1748                if (storedItems == null) {
1749                    // The roster store was corrupted. Reset the store and reload the roster without using a roster version.
1750                    rosterStore.resetStore();
1751                    try {
1752                        reload();
1753                    } catch (NotLoggedInException | NotConnectedException
1754                            | InterruptedException e) {
1755                        LOGGER.log(Level.FINE,
1756                                "Exception while trying to load the roster after the roster store was corrupted",
1757                                e);
1758                    }
1759                    return;
1760                }
1761                for (RosterPacket.Item item : storedItems) {
1762                    RosterEntry entry = new RosterEntry(item, Roster.this, connection);
1763                    addUpdateEntry(addedEntries, updatedEntries, unchangedEntries, item, entry);
1764                }
1765            }
1766
1767            rosterState = RosterState.loaded;
1768            synchronized (Roster.this) {
1769                Roster.this.notifyAll();
1770            }
1771            // Fire event for roster listeners.
1772            fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries);
1773
1774            // Call the roster loaded listeners after the roster events have been fired. This is
1775            // important because the user may call getEntriesAndAddListener() in onRosterLoaded(),
1776            // and if the order would be the other way around, the roster listener added by
1777            // getEntriesAndAddListener() would be invoked with information that was already
1778            // available at the time getEntriesAndAddListener() was called.
1779            try {
1780                synchronized (rosterLoadedListeners) {
1781                    for (RosterLoadedListener rosterLoadedListener : rosterLoadedListeners) {
1782                        rosterLoadedListener.onRosterLoaded(Roster.this);
1783                    }
1784                }
1785            }
1786            catch (Exception e) {
1787                LOGGER.log(Level.WARNING, "RosterLoadedListener threw exception", e);
1788            }
1789        }
1790    }
1791
1792    /**
1793     * Listens for all roster pushes and processes them.
1794     */
1795    private final class RosterPushListener extends AbstractIqRequestHandler {
1796
1797        private RosterPushListener() {
1798            super(RosterPacket.ELEMENT, RosterPacket.NAMESPACE, IQ.Type.set, Mode.sync);
1799        }
1800
1801        @Override
1802        public IQ handleIQRequest(IQ iqRequest) {
1803            final XMPPConnection connection = connection();
1804            RosterPacket rosterPacket = (RosterPacket) iqRequest;
1805
1806            EntityFullJid ourFullJid = connection.getUser();
1807            if (ourFullJid == null) {
1808                LOGGER.warning("Ignoring roster push " + iqRequest + " while " + connection
1809                                + " has no bound resource. This may be a server bug.");
1810                return null;
1811            }
1812
1813            // Roster push (RFC 6121, 2.1.6)
1814            // A roster push with a non-empty from not matching our address MUST be ignored
1815            EntityBareJid ourBareJid = ourFullJid.asEntityBareJid();
1816            Jid from = rosterPacket.getFrom();
1817            if (from != null) {
1818                if (from.equals(ourFullJid)) {
1819                    // Since RFC 6121 roster pushes are no longer allowed to
1820                    // origin from the full JID as it was the case with RFC
1821                    // 3921. Log a warning an continue processing the push.
1822                    // See also SMACK-773.
1823                    LOGGER.warning(
1824                            "Received roster push from full JID. This behavior is since RFC 6121 not longer standard compliant. "
1825                                    + "Please ask your server vendor to fix this and comply to RFC 6121 § 2.1.6. IQ roster push stanza: "
1826                                    + iqRequest);
1827                } else if (!from.equals(ourBareJid)) {
1828                    LOGGER.warning("Ignoring roster push with a non matching 'from' ourJid='" + ourBareJid + "' from='"
1829                            + from + "'");
1830                    return IQ.createErrorResponse(iqRequest, Condition.service_unavailable);
1831                }
1832            }
1833
1834            // A roster push must contain exactly one entry
1835            Collection<Item> items = rosterPacket.getRosterItems();
1836            if (items.size() != 1) {
1837                LOGGER.warning("Ignoring roster push with not exactly one entry. size=" + items.size());
1838                return IQ.createErrorResponse(iqRequest, Condition.bad_request);
1839            }
1840
1841            Collection<Jid> addedEntries = new ArrayList<>();
1842            Collection<Jid> updatedEntries = new ArrayList<>();
1843            Collection<Jid> deletedEntries = new ArrayList<>();
1844            Collection<Jid> unchangedEntries = new ArrayList<>();
1845
1846            // We assured above that the size of items is exactly 1, therefore we are able to
1847            // safely retrieve this single item here.
1848            Item item = items.iterator().next();
1849            RosterEntry entry = new RosterEntry(item, Roster.this, connection);
1850            String version = rosterPacket.getVersion();
1851
1852            if (item.getItemType().equals(RosterPacket.ItemType.remove)) {
1853                deleteEntry(deletedEntries, entry);
1854                if (rosterStore != null) {
1855                    rosterStore.removeEntry(entry.getJid(), version);
1856                }
1857            }
1858            else if (hasValidSubscriptionType(item)) {
1859                addUpdateEntry(addedEntries, updatedEntries, unchangedEntries, item, entry);
1860                if (rosterStore != null) {
1861                    rosterStore.addEntry(item, version);
1862                }
1863            }
1864
1865            removeEmptyGroups();
1866
1867            // Fire event for roster listeners.
1868            fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries);
1869
1870            return IQ.createResultIQ(rosterPacket);
1871        }
1872    }
1873
1874    /**
1875     * Set the default maximum size of the non-Roster presence map.
1876     * <p>
1877     * The roster will only store this many presence entries for entities non in the Roster. The
1878     * default is {@value #INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE}.
1879     * </p>
1880     *
1881     * @param maximumSize the maximum size
1882     * @since 4.2
1883     */
1884    public static void setDefaultNonRosterPresenceMapMaxSize(int maximumSize) {
1885        defaultNonRosterPresenceMapMaxSize = maximumSize;
1886    }
1887
1888    /**
1889     * Set the maximum size of the non-Roster presence map.
1890     *
1891     * @param maximumSize TODO javadoc me please
1892     * @since 4.2
1893     * @see #setDefaultNonRosterPresenceMapMaxSize(int)
1894     */
1895    public void setNonRosterPresenceMapMaxSize(int maximumSize) {
1896        nonRosterPresenceMap.setMaxCacheSize(maximumSize);
1897    }
1898
1899}