Roster.java

  1. /**
  2.  *
  3.  * Copyright 2003-2007 Jive Software, 2016-2024 Florian Schmaus.
  4.  *
  5.  * Licensed under the Apache License, Version 2.0 (the "License");
  6.  * you may not use this file except in compliance with the License.
  7.  * You may obtain a copy of the License at
  8.  *
  9.  *     http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */

  17. package org.jivesoftware.smack.roster;

  18. import java.util.ArrayList;
  19. import java.util.Arrays;
  20. import java.util.Collection;
  21. import java.util.Collections;
  22. import java.util.HashSet;
  23. import java.util.LinkedHashSet;
  24. import java.util.List;
  25. import java.util.Map;
  26. import java.util.Set;
  27. import java.util.WeakHashMap;
  28. import java.util.concurrent.ConcurrentHashMap;
  29. import java.util.concurrent.CopyOnWriteArraySet;
  30. import java.util.logging.Level;
  31. import java.util.logging.Logger;

  32. import org.jivesoftware.smack.AsyncButOrdered;
  33. import org.jivesoftware.smack.ConnectionCreationListener;
  34. import org.jivesoftware.smack.ConnectionListener;
  35. import org.jivesoftware.smack.Manager;
  36. import org.jivesoftware.smack.SmackException;
  37. import org.jivesoftware.smack.SmackException.FeatureNotSupportedException;
  38. import org.jivesoftware.smack.SmackException.NoResponseException;
  39. import org.jivesoftware.smack.SmackException.NotConnectedException;
  40. import org.jivesoftware.smack.SmackException.NotLoggedInException;
  41. import org.jivesoftware.smack.SmackFuture;
  42. import org.jivesoftware.smack.StanzaListener;
  43. import org.jivesoftware.smack.XMPPConnection;
  44. import org.jivesoftware.smack.XMPPConnectionRegistry;
  45. import org.jivesoftware.smack.XMPPException.XMPPErrorException;
  46. import org.jivesoftware.smack.filter.AndFilter;
  47. import org.jivesoftware.smack.filter.PresenceTypeFilter;
  48. import org.jivesoftware.smack.filter.StanzaFilter;
  49. import org.jivesoftware.smack.filter.StanzaTypeFilter;
  50. import org.jivesoftware.smack.filter.ToMatchesFilter;
  51. import org.jivesoftware.smack.iqrequest.AbstractIqRequestHandler;
  52. import org.jivesoftware.smack.packet.IQ;
  53. import org.jivesoftware.smack.packet.Presence;
  54. import org.jivesoftware.smack.packet.PresenceBuilder;
  55. import org.jivesoftware.smack.packet.Stanza;
  56. import org.jivesoftware.smack.packet.StanzaBuilder;
  57. import org.jivesoftware.smack.packet.StanzaError.Condition;
  58. import org.jivesoftware.smack.roster.SubscribeListener.SubscribeAnswer;
  59. import org.jivesoftware.smack.roster.packet.RosterPacket;
  60. import org.jivesoftware.smack.roster.packet.RosterPacket.Item;
  61. import org.jivesoftware.smack.roster.packet.RosterVer;
  62. import org.jivesoftware.smack.roster.packet.SubscriptionPreApproval;
  63. import org.jivesoftware.smack.roster.rosterstore.RosterStore;
  64. import org.jivesoftware.smack.util.ExceptionCallback;
  65. import org.jivesoftware.smack.util.Objects;
  66. import org.jivesoftware.smack.util.SuccessCallback;

  67. import org.jxmpp.jid.BareJid;
  68. import org.jxmpp.jid.EntityBareJid;
  69. import org.jxmpp.jid.EntityFullJid;
  70. import org.jxmpp.jid.FullJid;
  71. import org.jxmpp.jid.Jid;
  72. import org.jxmpp.jid.impl.JidCreate;
  73. import org.jxmpp.jid.parts.Resourcepart;
  74. import org.jxmpp.util.cache.LruCache;

  75. /**
  76.  * <p>
  77.  * The roster lets you keep track of the availability ("presence") of other
  78.  * users. A roster also allows you to organize users into groups such as
  79.  * "Friends" and "Co-workers". Other IM systems refer to the roster as the buddy
  80.  * list, contact list, etc.
  81.  * </p>
  82.  * <p>
  83.  * You can obtain a Roster instance for your connection via
  84.  * {@link #getInstanceFor(XMPPConnection)}. A detailed description of the
  85.  * protocol behind the Roster and Presence semantics can be found in
  86.  * <a href="https://tools.ietf.org/html/rfc6121">RFC 6120</a>.
  87.  * </p>
  88.  *
  89.  * <h2>Roster Entries</h2>
  90.  * Every user in a roster is represented by a RosterEntry, which consists
  91.  * of:
  92.  * <ul>
  93.  * <li>An XMPP address, aka. JID (e.g. jsmith@example.com).</li>
  94.  * <li>A name you've assigned to the user (e.g. "Joe").</li>
  95.  * <li>The list of groups in the roster that the entry belongs to. If the roster
  96.  * entry belongs to no groups, it's called an "unfiled entry".</li>
  97.  * </ul>
  98.  * The following code snippet prints all entries in the roster:
  99.  *
  100.  * <pre>{@code
  101.  * Roster roster = Roster.getInstanceFor(connection);
  102.  * Collection<RosterEntry> entries = roster.getEntries();
  103.  * for (RosterEntry entry : entries) {
  104.  *     System.out.println(entry);
  105.  * }
  106.  * }</pre>
  107.  *
  108.  * Methods also exist to get individual entries, the list of unfiled entries, or
  109.  * to get one or all roster groups.
  110.  *
  111.  * <h2>Presence</h2>
  112.  * <p>
  113.  * Every entry in the roster has presence associated with it. The
  114.  * {@link #getPresence(BareJid)} method will return a Presence object with the
  115.  * user's presence or `null` if the user is not online or you are not subscribed
  116.  * to the user's presence. _Note:_ Presence subscription is not tied to the
  117.  * user being on the roster, and vice versa: You could be subscribed to a remote
  118.  * users presence without the user in your roster, and a remote user can be in
  119.  * your roster without any presence subscription relation.
  120.  * </p>
  121.  * <p>
  122.  * A user either has a presence of online or offline. When a user is online,
  123.  * their presence may contain extended information such as what they are
  124.  * currently doing, whether they wish to be disturbed, etc. See the Presence
  125.  * class for further details.
  126.  * </p>
  127.  *
  128.  * <h2>Listening for Roster and Presence Changes</h2>
  129.  * <p>
  130.  * The typical use of the roster class is to display a tree view of groups and
  131.  * entries along with the current presence value of each entry. As an example,
  132.  * see the image showing a Roster in the Exodus XMPP client to the right.
  133.  * </p>
  134.  * <p>
  135.  * The presence information will likely change often, and it's also possible for
  136.  * the roster entries to change or be deleted. To listen for changing roster and
  137.  * presence data, a RosterListener should be used. To be informed about all
  138.  * changes to the roster the RosterListener should be registered before logging
  139.  * into the XMPP server. The following code snippet registers a RosterListener
  140.  * with the Roster that prints any presence changes in the roster to standard
  141.  * out. A normal client would use similar code to update the roster UI with the
  142.  * changing information.
  143.  * </p>
  144.  *
  145.  * <pre>{@code
  146.  * Roster roster = Roster.getInstanceFor(con);
  147.  * roster.addRosterListener(new RosterListener() {
  148.  *     // Ignored events public void entriesAdded(Collection<String> addresses) {}
  149.  *     public void entriesDeleted(Collection<String> addresses) {
  150.  *     }
  151.  *
  152.  *     public void entriesUpdated(Collection<String> addresses) {
  153.  *     }
  154.  *
  155.  *     public void presenceChanged(Presence presence) {
  156.  *         System.out.println("Presence changed: " + presence.getFrom() + " " + presence);
  157.  *      }
  158.  * });
  159.  * }</pre>
  160.  *
  161.  * Note that in order to receive presence changed events you need to be
  162.  * subscribed to the users presence. See the following section.
  163.  *
  164.  * <h2>Adding Entries to the Roster</h2>
  165.  *
  166.  * <p>
  167.  * Rosters and presence use a permissions-based model where users must give
  168.  * permission before someone else can see their presence. This protects a user's
  169.  * privacy by making sure that only approved users are able to view their
  170.  * presence information. Therefore, when you add a new roster entry, you will
  171.  * not see the presence information until the other user accepts your request.
  172.  * </p>
  173.  * <p>
  174.  * If another user requests a presence subscription, you must accept or reject
  175.  * that request. Smack handles presence subscription requests in one of three
  176. * ways:
  177.  * </p>
  178.  * <ul>
  179.  * <li>Automatically accept all presence subscription requests
  180.  * ({@link SubscriptionMode#accept_all accept_all})</li>
  181.  * <li>Automatically reject all presence subscription requests
  182.  * ({@link SubscriptionMode#reject_all reject_all})</li>
  183.  * <li>Process presence subscription requests manually.
  184.  * ({@link SubscriptionMode#manual manual})</li>
  185.  * </ul>
  186.  * <p>
  187.  * The mode can be set using {@link #setSubscriptionMode(SubscriptionMode)}.
  188.  * Simple clients normally use one of the automated subscription modes, while
  189.  * full-featured clients should manually process subscription requests and let
  190.  * the end-user accept or reject each request.
  191.  * </p>
  192.  *
  193.  * @author Matt Tucker
  194.  * @see #getInstanceFor(XMPPConnection)
  195.  */
  196. public final class Roster extends Manager {

  197.     private static final Logger LOGGER = Logger.getLogger(Roster.class.getName());

  198.     static {
  199.         XMPPConnectionRegistry.addConnectionCreationListener(new ConnectionCreationListener() {
  200.             @Override
  201.             public void connectionCreated(XMPPConnection connection) {
  202.                 getInstanceFor(connection);
  203.             }
  204.         });
  205.     }

  206.     private static final Map<XMPPConnection, Roster> INSTANCES = new WeakHashMap<>();

  207.     /**
  208.      * Returns the roster for the user.
  209.      * <p>
  210.      * This method will never return <code>null</code>, instead if the user has not yet logged into
  211.      * the server all modifying methods of the returned roster object
  212.      * like {@link Roster#createItemAndRequestSubscription(BareJid, String, String[])},
  213.      * {@link Roster#removeEntry(RosterEntry)} , etc. except adding or removing
  214.      * {@link RosterListener}s will throw an IllegalStateException.
  215.      * </p>
  216.      *
  217.      * @param connection the connection the roster should be retrieved for.
  218.      * @return the user's roster.
  219.      */
  220.     public static synchronized Roster getInstanceFor(XMPPConnection connection) {
  221.         Roster roster = INSTANCES.get(connection);
  222.         if (roster == null) {
  223.             roster = new Roster(connection);
  224.             INSTANCES.put(connection, roster);
  225.         }
  226.         return roster;
  227.     }

  228.     private static final StanzaFilter PRESENCE_PACKET_FILTER = StanzaTypeFilter.PRESENCE;

  229.     private static final StanzaFilter OUTGOING_USER_UNAVAILABLE_PRESENCE = new AndFilter(PresenceTypeFilter.UNAVAILABLE, ToMatchesFilter.MATCH_NO_TO_SET);

  230.     private static boolean rosterLoadedAtLoginDefault = true;

  231.     /**
  232.      * The default subscription processing mode to use when a Roster is created. By default,
  233.      * all subscription requests are automatically rejected.
  234.      */
  235.     private static SubscriptionMode defaultSubscriptionMode = SubscriptionMode.reject_all;

  236.     /**
  237.      * The initial maximum size of the map holding presence information of entities without a Roster entry. Currently
  238.      * {@value #INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE}.
  239.      */
  240.     public static final int INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE = 1024;

  241.     private static int defaultNonRosterPresenceMapMaxSize = INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE;

  242.     private RosterStore rosterStore;

  243.     /**
  244.      * The groups of this roster.
  245.      * <p>
  246.      * Note that we use {@link ConcurrentHashMap} also as static type of this field, since we use the fact that the same
  247.      * thread can modify this collection, e.g. remove items, while iterating over it. This is done, for example in
  248.      * {@link #deleteEntry(Collection, RosterEntry)}. If we do not denote the static type to ConcurrentHashMap, but
  249.      * {@link Map} instead, then error prone would report a ModifyCollectionInEnhancedForLoop but.
  250.      * </p>
  251.      */
  252.     private final ConcurrentHashMap<String, RosterGroup> groups = new ConcurrentHashMap<>();

  253.     /**
  254.      * Concurrent hash map from JID to its roster entry.
  255.      */
  256.     private final Map<BareJid, RosterEntry> entries = new ConcurrentHashMap<>();

  257.     private final Set<RosterEntry> unfiledEntries = new CopyOnWriteArraySet<>();
  258.     private final Set<RosterListener> rosterListeners = new LinkedHashSet<>();

  259.     private final Set<PresenceEventListener> presenceEventListeners = new CopyOnWriteArraySet<>();

  260.     /**
  261.      * A map of JIDs to another Map of Resourceparts to Presences. The 'inner' map may contain
  262.      * {@link Resourcepart#EMPTY} if there are no other Presences available.
  263.      */
  264.     private final Map<BareJid, Map<Resourcepart, Presence>> presenceMap = new ConcurrentHashMap<>();

  265.     /**
  266.      * Like {@link #presenceMap} but for presences of entities not in our Roster.
  267.      */
  268.     // TODO Ideally we want here to use a LRU cache like Map which will evict all superfluous items
  269.     // if their maximum size is lowered below the current item count. LruCache does not provide
  270.     // this.
  271.     private final LruCache<BareJid, Map<Resourcepart, Presence>> nonRosterPresenceMap = new LruCache<>(
  272.                     defaultNonRosterPresenceMapMaxSize);

  273.     /**
  274.      * Listeners called when the Roster was loaded.
  275.      */
  276.     private final Set<RosterLoadedListener> rosterLoadedListeners = new LinkedHashSet<>();

  277.     /**
  278.      * Mutually exclude roster listener invocation and changing the {@link #entries} map. Also used
  279.      * to synchronize access to either the roster listeners or the entries map.
  280.      */
  281.     private final Object rosterListenersAndEntriesLock = new Object();

  282.     private enum RosterState {
  283.         uninitialized,
  284.         loading,
  285.         loaded,
  286.     }

  287.     /**
  288.      * The current state of the roster.
  289.      */
  290.     private RosterState rosterState = RosterState.uninitialized;

  291.     private final PresencePacketListener presencePacketListener = new PresencePacketListener();

  292.     /**
  293.      *
  294.      */
  295.     private boolean rosterLoadedAtLogin = rosterLoadedAtLoginDefault;

  296.     private SubscriptionMode subscriptionMode = getDefaultSubscriptionMode();

  297.     private final Set<SubscribeListener> subscribeListeners = new CopyOnWriteArraySet<>();

  298.     private SubscriptionMode previousSubscriptionMode;

  299.     /**
  300.      * Returns the default subscription processing mode to use when a new Roster is created. The
  301.      * subscription processing mode dictates what action Smack will take when subscription
  302.      * requests from other users are made. The default subscription mode
  303.      * is {@link SubscriptionMode#reject_all}.
  304.      *
  305.      * @return the default subscription mode to use for new Rosters
  306.      */
  307.     public static SubscriptionMode getDefaultSubscriptionMode() {
  308.         return defaultSubscriptionMode;
  309.     }

  310.     /**
  311.      * Sets the default subscription processing mode to use when a new Roster is created. The
  312.      * subscription processing mode dictates what action Smack will take when subscription
  313.      * requests from other users are made. The default subscription mode
  314.      * is {@link SubscriptionMode#reject_all}.
  315.      *
  316.      * @param subscriptionMode the default subscription mode to use for new Rosters.
  317.      */
  318.     public static void setDefaultSubscriptionMode(SubscriptionMode subscriptionMode) {
  319.         defaultSubscriptionMode = subscriptionMode;
  320.     }

  321.     private final AsyncButOrdered<BareJid> asyncButOrdered = new AsyncButOrdered<>();

  322.     /**
  323.      * Creates a new roster.
  324.      *
  325.      * @param connection an XMPP connection.
  326.      */
  327.     private Roster(final XMPPConnection connection) {
  328.         super(connection);

  329.         // Note that we use sync packet listeners because RosterListeners should be invoked in the same order as the
  330.         // roster stanzas arrive.
  331.         // Listen for any roster packets.
  332.         connection.registerIQRequestHandler(new RosterPushListener());
  333.         // Listen for any presence packets.
  334.         connection.addSyncStanzaListener(presencePacketListener, PRESENCE_PACKET_FILTER);

  335.         connection.addAsyncStanzaListener(new StanzaListener() {
  336.             @SuppressWarnings("fallthrough")
  337.             @Override
  338.             public void processStanza(Stanza stanza) throws NotConnectedException,
  339.                             InterruptedException, NotLoggedInException {
  340.                 Presence presence = (Presence) stanza;
  341.                 Jid from = presence.getFrom();
  342.                 SubscribeAnswer subscribeAnswer = null;
  343.                 switch (subscriptionMode) {
  344.                 case manual:
  345.                     for (SubscribeListener subscribeListener : subscribeListeners) {
  346.                         subscribeAnswer = subscribeListener.processSubscribe(from, presence);
  347.                         if (subscribeAnswer != null) {
  348.                             break;
  349.                         }
  350.                     }
  351.                     if (subscribeAnswer == null) {
  352.                         return;
  353.                     }
  354.                     break;
  355.                 case accept_all:
  356.                     // Accept all subscription requests.
  357.                     subscribeAnswer = SubscribeAnswer.Approve;
  358.                     break;
  359.                 case reject_all:
  360.                     // Reject all subscription requests.
  361.                     subscribeAnswer = SubscribeAnswer.Deny;
  362.                     break;
  363.                 }

  364.                 if (subscribeAnswer == null) {
  365.                     return;
  366.                 }

  367.                 Presence.Type type;
  368.                 switch (subscribeAnswer) {
  369.                 case ApproveAndAlsoRequestIfRequired:
  370.                     BareJid bareFrom = from.asBareJid();
  371.                     RosterUtil.askForSubscriptionIfRequired(Roster.this, bareFrom);
  372.                     // The fall through is intended.
  373.                 case Approve:
  374.                     type = Presence.Type.subscribed;
  375.                     break;
  376.                 case Deny:
  377.                     type = Presence.Type.unsubscribed;
  378.                     break;
  379.                 default:
  380.                     throw new AssertionError();
  381.                 }

  382.                 Presence response = connection.getStanzaFactory().buildPresenceStanza()
  383.                         .ofType(type)
  384.                         .to(presence.getFrom())
  385.                         .build();
  386.                 connection.sendStanza(response);
  387.             }
  388.         }, PresenceTypeFilter.SUBSCRIBE);

  389.         // Listen for connection events
  390.         connection.addConnectionListener(new ConnectionListener() {

  391.             @Override
  392.             public void authenticated(XMPPConnection connection, boolean resumed) {
  393.                 if (!isRosterLoadedAtLogin())
  394.                     return;
  395.                 // We are done here if the connection was resumed
  396.                 if (resumed) {
  397.                     return;
  398.                 }

  399.                 // Ensure that all available presences received so far in an eventually existing previous session are
  400.                 // marked 'offline'.
  401.                 setOfflinePresencesAndResetLoaded();

  402.                 try {
  403.                     Roster.this.reload();
  404.                 }
  405.                 catch (InterruptedException | SmackException e) {
  406.                     LOGGER.log(Level.SEVERE, "Could not reload Roster", e);
  407.                     return;
  408.                 }
  409.             }

  410.             @Override
  411.             public void connectionClosed() {
  412.                 // Changes the presence available contacts to unavailable
  413.                 setOfflinePresencesAndResetLoaded();
  414.             }

  415.         });

  416.         connection.addStanzaSendingListener(new StanzaListener() {
  417.             @Override
  418.             public void processStanza(Stanza stanzav) throws NotConnectedException, InterruptedException {
  419.                 // Once we send an unavailable presence, the server is allowed to suppress sending presence status
  420.                 // information to us as optimization (RFC 6121 ยง 4.4.2). Thus XMPP clients which are unavailable, should
  421.                 // consider the presence information of their contacts as not up-to-date. We make the user obvious of
  422.                 // this situation by setting the presences of all contacts to unavailable (while keeping the roster
  423.                 // state).
  424.                 setOfflinePresences();
  425.             }
  426.         }, OUTGOING_USER_UNAVAILABLE_PRESENCE);

  427.         // If the connection is already established, call reload
  428.         if (connection.isAuthenticated()) {
  429.             try {
  430.                 reloadAndWait();
  431.             }
  432.             catch (InterruptedException | SmackException e) {
  433.                 LOGGER.log(Level.SEVERE, "Could not reload Roster", e);
  434.             }
  435.         }

  436.     }

  437.     /**
  438.      * Retrieve the user presences (a map from resource to {@link Presence}) for a given XMPP entity represented by their bare JID.
  439.      *
  440.      * @param entity the entity
  441.      * @return the user presences
  442.      */
  443.     private Map<Resourcepart, Presence> getPresencesInternal(BareJid entity) {
  444.         Map<Resourcepart, Presence> entityPresences = presenceMap.get(entity);
  445.         if (entityPresences == null) {
  446.             entityPresences = nonRosterPresenceMap.lookup(entity);
  447.         }
  448.         return entityPresences;
  449.     }

  450.     /**
  451.      * Retrieve the user presences (a map from resource to {@link Presence}) for a given XMPP entity represented by their bare JID.
  452.      *
  453.      * @param entity the entity
  454.      * @return the user presences
  455.      */
  456.     private synchronized Map<Resourcepart, Presence> getOrCreatePresencesInternal(BareJid entity) {
  457.         Map<Resourcepart, Presence> entityPresences = getPresencesInternal(entity);
  458.         if (entityPresences == null) {
  459.             if (contains(entity)) {
  460.                 entityPresences = new ConcurrentHashMap<>();
  461.                 presenceMap.put(entity, entityPresences);
  462.             }
  463.             else {
  464.                 LruCache<Resourcepart, Presence> nonRosterEntityPresences = new LruCache<>(32);
  465.                 nonRosterPresenceMap.put(entity, nonRosterEntityPresences);
  466.                 entityPresences = nonRosterEntityPresences;
  467.             }
  468.         }
  469.         return entityPresences;
  470.     }

  471.     /**
  472.      * Returns the subscription processing mode, which dictates what action
  473.      * Smack will take when subscription requests from other users are made.
  474.      * The default subscription mode is {@link SubscriptionMode#reject_all}.
  475.      * <p>
  476.      * If using the manual mode, a PacketListener should be registered that
  477.      * listens for Presence packets that have a type of
  478.      * {@link org.jivesoftware.smack.packet.Presence.Type#subscribe}.
  479.      * </p>
  480.      *
  481.      * @return the subscription mode.
  482.      */
  483.     public SubscriptionMode getSubscriptionMode() {
  484.         return subscriptionMode;
  485.     }

  486.     /**
  487.      * Sets the subscription processing mode, which dictates what action
  488.      * Smack will take when subscription requests from other users are made.
  489.      * The default subscription mode is {@link SubscriptionMode#reject_all}.
  490.      * <p>
  491.      * If using the manual mode, a PacketListener should be registered that
  492.      * listens for Presence packets that have a type of
  493.      * {@link org.jivesoftware.smack.packet.Presence.Type#subscribe}.
  494.      * </p>
  495.      *
  496.      * @param subscriptionMode the subscription mode.
  497.      */
  498.     public void setSubscriptionMode(SubscriptionMode subscriptionMode) {
  499.         this.subscriptionMode = subscriptionMode;
  500.     }

  501.     /**
  502.      * Reloads the entire roster from the server. This is an asynchronous operation,
  503.      * which means the method will return immediately, and the roster will be
  504.      * reloaded at a later point when the server responds to the reload request.
  505.      * @throws NotLoggedInException If not logged in.
  506.      * @throws NotConnectedException if the XMPP connection is not connected.
  507.      * @throws InterruptedException if the calling thread was interrupted.
  508.      */
  509.     public void reload() throws NotLoggedInException, NotConnectedException, InterruptedException {
  510.         final XMPPConnection connection = getAuthenticatedConnectionOrThrow();

  511.         RosterPacket packet = new RosterPacket();
  512.         if (rosterStore != null && isRosterVersioningSupported()) {
  513.             packet.setVersion(rosterStore.getRosterVersion());
  514.         }
  515.         rosterState = RosterState.loading;

  516.         SmackFuture<IQ, Exception> future = connection.sendIqRequestAsync(packet);

  517.         future.onSuccess(new RosterResultListener()).onError(new ExceptionCallback<Exception>() {

  518.             @Override
  519.             public void processException(Exception exception) {
  520.                 rosterState = RosterState.uninitialized;
  521.                 Level logLevel = Level.SEVERE;
  522.                 if (exception instanceof NotConnectedException) {
  523.                     logLevel = Level.FINE;
  524.                 } else if (exception instanceof XMPPErrorException) {
  525.                     Condition condition = ((XMPPErrorException) exception).getStanzaError().getCondition();
  526.                     if (condition == Condition.feature_not_implemented || condition == Condition.service_unavailable) {
  527.                         logLevel = Level.FINE;
  528.                     }
  529.                 }
  530.                 LOGGER.log(logLevel, "Exception reloading roster", exception);
  531.                 for (RosterLoadedListener listener : rosterLoadedListeners) {
  532.                     listener.onRosterLoadingFailed(exception);
  533.                 }
  534.             }

  535.         });
  536.     }

  537.     /**
  538.      * Reload the roster and block until it is reloaded.
  539.      *
  540.      * @throws NotLoggedInException if the XMPP connection is not authenticated.
  541.      * @throws NotConnectedException if the XMPP connection is not connected.
  542.      * @throws InterruptedException if the calling thread was interrupted.
  543.      * @since 4.1
  544.      */
  545.     public void reloadAndWait() throws NotLoggedInException, NotConnectedException, InterruptedException {
  546.         reload();
  547.         waitUntilLoaded();
  548.     }

  549.     /**
  550.      * Set the roster store, may cause a roster reload.
  551.      *
  552.      * @param rosterStore TODO javadoc me please
  553.      * @return true if the roster reload was initiated, false otherwise.
  554.      * @since 4.1
  555.      */
  556.     public boolean setRosterStore(RosterStore rosterStore) {
  557.         this.rosterStore = rosterStore;
  558.         try {
  559.             reload();
  560.         }
  561.         catch (InterruptedException | NotLoggedInException | NotConnectedException e) {
  562.             LOGGER.log(Level.FINER, "Could not reload roster", e);
  563.             return false;
  564.         }
  565.         return true;
  566.     }

  567.     boolean waitUntilLoaded() throws InterruptedException {
  568.         long waitTime = connection().getReplyTimeout();
  569.         long start = System.currentTimeMillis();
  570.         while (!isLoaded()) {
  571.             if (waitTime <= 0) {
  572.                 break;
  573.             }
  574.             synchronized (this) {
  575.                 if (!isLoaded()) {
  576.                     wait(waitTime);
  577.                 }
  578.             }
  579.             long now = System.currentTimeMillis();
  580.             waitTime -= now - start;
  581.             start = now;
  582.         }
  583.         return isLoaded();
  584.     }

  585.     /**
  586.      * Check if the roster is loaded.
  587.      *
  588.      * @return true if the roster is loaded.
  589.      * @since 4.1
  590.      */
  591.     public boolean isLoaded() {
  592.         return rosterState == RosterState.loaded;
  593.     }

  594.     /**
  595.      * Adds a listener to this roster. The listener will be fired anytime one or more
  596.      * changes to the roster are pushed from the server.
  597.      *
  598.      * @param rosterListener a roster listener.
  599.      * @return true if the listener was not already added.
  600.      * @see #getEntriesAndAddListener(RosterListener, RosterEntries)
  601.      */
  602.     public boolean addRosterListener(RosterListener rosterListener) {
  603.         synchronized (rosterListenersAndEntriesLock) {
  604.             return rosterListeners.add(rosterListener);
  605.         }
  606.     }

  607.     /**
  608.      * Removes a listener from this roster. The listener will be fired anytime one or more
  609.      * changes to the roster are pushed from the server.
  610.      *
  611.      * @param rosterListener a roster listener.
  612.      * @return true if the listener was active and got removed.
  613.      */
  614.     public boolean removeRosterListener(RosterListener rosterListener) {
  615.         synchronized (rosterListenersAndEntriesLock) {
  616.             return rosterListeners.remove(rosterListener);
  617.         }
  618.     }

  619.     /**
  620.      * Add a roster loaded listener. Roster loaded listeners are invoked once the {@link Roster}
  621.      * was successfully loaded.
  622.      *
  623.      * @param rosterLoadedListener the listener to add.
  624.      * @return true if the listener was not already added.
  625.      * @see RosterLoadedListener
  626.      * @since 4.1
  627.      */
  628.     public boolean addRosterLoadedListener(RosterLoadedListener rosterLoadedListener) {
  629.         synchronized (rosterLoadedListener) {
  630.             return rosterLoadedListeners.add(rosterLoadedListener);
  631.         }
  632.     }

  633.     /**
  634.      * Remove a roster loaded listener.
  635.      *
  636.      * @param rosterLoadedListener the listener to remove.
  637.      * @return true if the listener was active and got removed.
  638.      * @see RosterLoadedListener
  639.      * @since 4.1
  640.      */
  641.     public boolean removeRosterLoadedListener(RosterLoadedListener rosterLoadedListener) {
  642.         synchronized (rosterLoadedListener) {
  643.             return rosterLoadedListeners.remove(rosterLoadedListener);
  644.         }
  645.     }

  646.     /**
  647.      * Add a {@link PresenceEventListener}. Such a listener will be fired whenever certain
  648.      * presence events happen.<p>
  649.      * Among those events are:
  650.      * <ul>
  651.      * <li> 'available' presence received
  652.      * <li> 'unavailable' presence received
  653.      * <li> 'error' presence received
  654.      * <li> 'subscribed' presence received
  655.      * <li> 'unsubscribed' presence received
  656.      * </ul>
  657.      * @param presenceEventListener listener to add.
  658.      * @return true if the listener was not already added.
  659.      */
  660.     public boolean addPresenceEventListener(PresenceEventListener presenceEventListener) {
  661.         return presenceEventListeners.add(presenceEventListener);
  662.     }

  663.     public boolean removePresenceEventListener(PresenceEventListener presenceEventListener) {
  664.         return presenceEventListeners.remove(presenceEventListener);
  665.     }

  666.     /**
  667.      * Creates a new group.
  668.      * <p>
  669.      * Note: you must add at least one entry to the group for the group to be kept
  670.      * after a logout/login. This is due to the way that XMPP stores group information.
  671.      * </p>
  672.      *
  673.      * @param name the name of the group.
  674.      * @return a new group, or null if the group already exists
  675.      */
  676.     public RosterGroup createGroup(String name) {
  677.         final XMPPConnection connection = connection();
  678.         if (groups.containsKey(name)) {
  679.             return groups.get(name);
  680.         }

  681.         RosterGroup group = new RosterGroup(name, connection);
  682.         groups.put(name, group);
  683.         return group;
  684.     }

  685.     /**
  686.      * Creates a new roster item. The server will asynchronously update the roster with the subscription status.
  687.      * <p>
  688.      * There will be no presence subscription request. Consider using
  689.      * {@link #createItemAndRequestSubscription(BareJid, String, String[])} if you also want to request a presence
  690.      * subscription from the contact.
  691.      * </p>
  692.      *
  693.      * @param jid the XMPP address of the contact (e.g. johndoe@jabber.org)
  694.      * @param name the nickname of the user.
  695.      * @param groups the list of group names the entry will belong to, or <code>null</code> if the roster entry won't
  696.      *        belong to a group.
  697.      * @throws NoResponseException if there was no response from the server.
  698.      * @throws XMPPErrorException if an XMPP exception occurs.
  699.      * @throws NotLoggedInException If not logged in.
  700.      * @throws NotConnectedException if the XMPP connection is not connected.
  701.      * @throws InterruptedException if the calling thread was interrupted.
  702.      * @since 4.4.0
  703.      */
  704.     public void createItem(BareJid jid, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
  705.         final XMPPConnection connection = getAuthenticatedConnectionOrThrow();

  706.         // Create and send roster entry creation packet.
  707.         RosterPacket rosterPacket = new RosterPacket();
  708.         rosterPacket.setType(IQ.Type.set);
  709.         RosterPacket.Item item = new RosterPacket.Item(jid, name);
  710.         if (groups != null) {
  711.             for (String group : groups) {
  712.                 if (group != null && group.trim().length() > 0) {
  713.                     item.addGroupName(group);
  714.                 }
  715.             }
  716.         }
  717.         rosterPacket.addRosterItem(item);
  718.         connection.sendIqRequestAndWaitForResponse(rosterPacket);
  719.     }

  720.     /**
  721.      * Creates a new roster entry and presence subscription. The server will asynchronously
  722.      * update the roster with the subscription status.
  723.      *
  724.      * @param jid the XMPP address of the contact (e.g. johndoe@jabber.org)
  725.      * @param name   the nickname of the user.
  726.      * @param groups the list of group names the entry will belong to, or <code>null</code> if
  727.      *               the roster entry won't belong to a group.
  728.      * @throws NoResponseException if there was no response from the server.
  729.      * @throws XMPPErrorException if an XMPP exception occurs.
  730.      * @throws NotLoggedInException If not logged in.
  731.      * @throws NotConnectedException if the XMPP connection is not connected.
  732.      * @throws InterruptedException if the calling thread was interrupted.
  733.      * @since 4.4.0
  734.      */
  735.     public void createItemAndRequestSubscription(BareJid jid, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
  736.         createItem(jid, name, groups);

  737.         sendSubscriptionRequest(jid);
  738.     }

  739.     /**
  740.      * Creates a new pre-approved roster entry and presence subscription. The server will
  741.      * asynchronously update the roster with the subscription status.
  742.      *
  743.      * @param user   the user. (e.g. johndoe@jabber.org)
  744.      * @param name   the nickname of the user.
  745.      * @param groups the list of group names the entry will belong to, or <code>null</code> if
  746.      *               the roster entry won't belong to a group.
  747.      * @throws NoResponseException if there was no response from the server.
  748.      * @throws XMPPErrorException if an XMPP exception occurs.
  749.      * @throws NotLoggedInException if not logged in.
  750.      * @throws NotConnectedException if the XMPP connection is not connected.
  751.      * @throws InterruptedException if the calling thread was interrupted.
  752.      * @throws FeatureNotSupportedException if pre-approving is not supported.
  753.      * @since 4.2
  754.      */
  755.     public void preApproveAndCreateEntry(BareJid user, String name, String[] groups) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, FeatureNotSupportedException {
  756.         preApprove(user);
  757.         createItemAndRequestSubscription(user, name, groups);
  758.     }

  759.     /**
  760.      * Pre-approve user presence subscription.
  761.      *
  762.      * @param user the user. (e.g. johndoe@jabber.org)
  763.      * @throws NotLoggedInException if not logged in.
  764.      * @throws NotConnectedException if the XMPP connection is not connected.
  765.      * @throws InterruptedException if the calling thread was interrupted.
  766.      * @throws FeatureNotSupportedException if pre-approving is not supported.
  767.      * @since 4.2
  768.      */
  769.     public void preApprove(BareJid user) throws NotLoggedInException, NotConnectedException, InterruptedException, FeatureNotSupportedException {
  770.         final XMPPConnection connection = connection();
  771.         if (!isSubscriptionPreApprovalSupported()) {
  772.             throw new FeatureNotSupportedException("Pre-approving");
  773.         }

  774.         Presence presencePacket = connection.getStanzaFactory().buildPresenceStanza()
  775.             .ofType(Presence.Type.subscribed)
  776.             .to(user)
  777.             .build();
  778.         connection.sendStanza(presencePacket);
  779.     }

  780.     /**
  781.      * Check for subscription pre-approval support.
  782.      *
  783.      * @return true if subscription pre-approval is supported by the server.
  784.      * @throws NotLoggedInException if not logged in.
  785.      * @since 4.2
  786.      */
  787.     public boolean isSubscriptionPreApprovalSupported() throws NotLoggedInException {
  788.         final XMPPConnection connection = getAuthenticatedConnectionOrThrow();
  789.         return connection.hasFeature(SubscriptionPreApproval.ELEMENT, SubscriptionPreApproval.NAMESPACE);
  790.     }

  791.     public void sendSubscriptionRequest(BareJid jid) throws NotLoggedInException, NotConnectedException, InterruptedException {
  792.         final XMPPConnection connection = getAuthenticatedConnectionOrThrow();

  793.         // Create a presence subscription packet and send.
  794.         Presence presencePacket = connection.getStanzaFactory().buildPresenceStanza()
  795.                 .ofType(Presence.Type.subscribe)
  796.                 .to(jid)
  797.                 .build();
  798.         connection.sendStanza(presencePacket);
  799.     }

  800.     /**
  801.      * Add a subscribe listener, which is invoked on incoming subscription requests and if
  802.      * {@link SubscriptionMode} is set to {@link SubscriptionMode#manual}. This also sets subscription
  803.      * mode to {@link SubscriptionMode#manual}.
  804.      *
  805.      * @param subscribeListener the subscribe listener to add.
  806.      * @return <code>true</code> if the listener was not already added.
  807.      * @since 4.2
  808.      */
  809.     public boolean addSubscribeListener(SubscribeListener subscribeListener) {
  810.         Objects.requireNonNull(subscribeListener, "SubscribeListener argument must not be null");
  811.         if (subscriptionMode != SubscriptionMode.manual) {
  812.             previousSubscriptionMode = subscriptionMode;
  813.             subscriptionMode = SubscriptionMode.manual;
  814.         }
  815.         return subscribeListeners.add(subscribeListener);
  816.     }

  817.     /**
  818.      * Remove a subscribe listener. Also restores the previous subscription mode
  819.      * state, if the last listener got removed.
  820.      *
  821.      * @param subscribeListener TODO javadoc me please
  822.      *            the subscribe listener to remove.
  823.      * @return <code>true</code> if the listener registered and got removed.
  824.      * @since 4.2
  825.      */
  826.     public boolean removeSubscribeListener(SubscribeListener subscribeListener) {
  827.         boolean removed = subscribeListeners.remove(subscribeListener);
  828.         if (removed && subscribeListeners.isEmpty()) {
  829.             setSubscriptionMode(previousSubscriptionMode);
  830.         }
  831.         return removed;
  832.     }

  833.     /**
  834.      * Removes a roster entry from the roster. The roster entry will also be removed from the
  835.      * unfiled entries or from any roster group where it could belong and will no longer be part
  836.      * of the roster. Note that this is a synchronous call -- Smack must wait for the server
  837.      * to send an updated subscription status.
  838.      *
  839.      * @param entry a roster entry.
  840.      * @throws XMPPErrorException if an XMPP error occurs.
  841.      * @throws NotLoggedInException if not logged in.
  842.      * @throws NoResponseException SmackException if there was no response from the server.
  843.      * @throws NotConnectedException if the XMPP connection is not connected.
  844.      * @throws InterruptedException if the calling thread was interrupted.
  845.      */
  846.     public void removeEntry(RosterEntry entry) throws NotLoggedInException, NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
  847.         final XMPPConnection connection = getAuthenticatedConnectionOrThrow();

  848.         // Only remove the entry if it's in the entry list.
  849.         // The actual removal logic takes place in RosterPacketListenerProcess>>Packet(Packet)
  850.         if (!entries.containsKey(entry.getJid())) {
  851.             return;
  852.         }
  853.         RosterPacket packet = new RosterPacket();
  854.         packet.setType(IQ.Type.set);
  855.         RosterPacket.Item item = RosterEntry.toRosterItem(entry);
  856.         // Set the item type as REMOVE so that the server will delete the entry
  857.         item.setItemType(RosterPacket.ItemType.remove);
  858.         packet.addRosterItem(item);
  859.         connection.sendIqRequestAndWaitForResponse(packet);
  860.     }

  861.     /**
  862.      * Returns a count of the entries in the roster.
  863.      *
  864.      * @return the number of entries in the roster.
  865.      */
  866.     public int getEntryCount() {
  867.         return getEntries().size();
  868.     }

  869.     /**
  870.      * Add a roster listener and invoke the roster entries with all entries of the roster.
  871.      * <p>
  872.      * The method guarantees that the listener is only invoked after
  873.      * {@link RosterEntries#rosterEntries(Collection)} has been invoked, and that all roster events
  874.      * that happen while <code>rosterEntries(Collection) </code> is called are queued until the
  875.      * method returns.
  876.      * </p>
  877.      * <p>
  878.      * This guarantee makes this the ideal method to e.g. populate a UI element with the roster while
  879.      * installing a {@link RosterListener} to listen for subsequent roster events.
  880.      * </p>
  881.      *
  882.      * @param rosterListener the listener to install
  883.      * @param rosterEntries the roster entries callback interface
  884.      * @since 4.1
  885.      */
  886.     public void getEntriesAndAddListener(RosterListener rosterListener, RosterEntries rosterEntries) {
  887.         Objects.requireNonNull(rosterListener, "listener must not be null");
  888.         Objects.requireNonNull(rosterEntries, "rosterEntries must not be null");

  889.         synchronized (rosterListenersAndEntriesLock) {
  890.             rosterEntries.rosterEntries(entries.values());
  891.             addRosterListener(rosterListener);
  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.      * Returns a count of the unfiled entries in the roster. An unfiled entry is
  912.      * an entry that doesn't belong to any groups.
  913.      *
  914.      * @return the number of unfiled entries in the roster.
  915.      */
  916.     public int getUnfiledEntryCount() {
  917.         return unfiledEntries.size();
  918.     }

  919.     /**
  920.      * Returns an unmodifiable set for the unfiled roster entries. An unfiled entry is
  921.      * an entry that doesn't belong to any groups.
  922.      *
  923.      * @return the unfiled roster entries.
  924.      */
  925.     public Set<RosterEntry> getUnfiledEntries() {
  926.         return Collections.unmodifiableSet(unfiledEntries);
  927.     }

  928.     /**
  929.      * Returns the roster entry associated with the given XMPP address or
  930.      * <code>null</code> if the user is not an entry in the roster.
  931.      *
  932.      * @param jid the XMPP address of the user (e.g."jsmith@example.com"). The address could be
  933.      *             in any valid format (e.g. "domain/resource", "user@domain" or "user@domain/resource").
  934.      * @return the roster entry or <code>null</code> if it does not exist.
  935.      */
  936.     public RosterEntry getEntry(BareJid jid) {
  937.         if (jid == null) {
  938.             return null;
  939.         }
  940.         return entries.get(jid);
  941.     }

  942.     /**
  943.      * Returns true if the specified XMPP address is an entry in the roster.
  944.      *
  945.      * @param jid the XMPP address of the user (e.g."jsmith@example.com"). The
  946.      *             address must be a bare JID e.g. "domain/resource" or
  947.      *             "user@domain".
  948.      * @return true if the XMPP address is an entry in the roster.
  949.      */
  950.     public boolean contains(BareJid jid) {
  951.         return getEntry(jid) != null;
  952.     }

  953.     /**
  954.      * Returns the roster group with the specified name, or <code>null</code> if the
  955.      * group doesn't exist.
  956.      *
  957.      * @param name the name of the group.
  958.      * @return the roster group with the specified name.
  959.      */
  960.     public RosterGroup getGroup(String name) {
  961.         return groups.get(name);
  962.     }

  963.     /**
  964.      * Returns the number of the groups in the roster.
  965.      *
  966.      * @return the number of groups in the roster.
  967.      */
  968.     public int getGroupCount() {
  969.         return groups.size();
  970.     }

  971.     /**
  972.      * Returns an unmodifiable collections of all the roster groups.
  973.      *
  974.      * @return an iterator for all roster groups.
  975.      */
  976.     public Collection<RosterGroup> getGroups() {
  977.         return Collections.unmodifiableCollection(groups.values());
  978.     }

  979.     /**
  980.      * Returns the presence info for a particular user. If the user is offline, or
  981.      * if no presence data is available (such as when you are not subscribed to the
  982.      * user's presence updates), unavailable presence will be returned.
  983.      *
  984.      * If the user has several presences (one for each resource), then the presence with
  985.      * highest priority will be returned. If multiple presences have the same priority,
  986.      * the one with the "most available" presence mode will be returned. In order,
  987.      * that's {@link org.jivesoftware.smack.packet.Presence.Mode#chat free to chat},
  988.      * {@link org.jivesoftware.smack.packet.Presence.Mode#available available},
  989.      * {@link org.jivesoftware.smack.packet.Presence.Mode#away away},
  990.      * {@link org.jivesoftware.smack.packet.Presence.Mode#xa extended away}, and
  991.      * {@link org.jivesoftware.smack.packet.Presence.Mode#dnd do not disturb}.
  992.      *
  993.      * <p>
  994.      * Note that presence information is received asynchronously. So, just after logging
  995.      * in to the server, presence values for users in the roster may be unavailable
  996.      * even if they are actually online. In other words, the value returned by this
  997.      * method should only be treated as a snapshot in time, and may not accurately reflect
  998.      * other user's presence instant by instant. If you need to track presence over time,
  999.      * such as when showing a visual representation of the roster, consider using a
  1000.      * {@link RosterListener}.
  1001.      * </p>
  1002.      *
  1003.      * @param jid the XMPP address of the user (e.g."jsmith@example.com"). The
  1004.      *             address must be a bare JID e.g. "domain/resource" or
  1005.      *             "user@domain".
  1006.      * @return the user's current presence, or unavailable presence if the user is offline
  1007.      *         or if no presence information is available.
  1008.      */
  1009.     public Presence getPresence(BareJid jid) {
  1010.         Map<Resourcepart, Presence> userPresences = getPresencesInternal(jid);
  1011.         if (userPresences == null) {
  1012.             Presence presence = synthesizeUnvailablePresence(jid);
  1013.             return presence;
  1014.         }
  1015.         else {
  1016.             // Find the resource with the highest priority
  1017.             // Might be changed to use the resource with the highest availability instead.
  1018.             Presence presence = null;
  1019.             // This is used in case no available presence is found
  1020.             Presence unavailable = null;

  1021.             for (Presence p : userPresences.values()) {
  1022.                 if (!p.isAvailable()) {
  1023.                     unavailable = p;
  1024.                     continue;
  1025.                 }
  1026.                 // Chose presence with highest priority first.
  1027.                 if (presence == null || p.getPriority() > presence.getPriority()) {
  1028.                     presence = p;
  1029.                 }
  1030.                 // If equal priority, choose "most available" by the mode value.
  1031.                 else if (p.getPriority() == presence.getPriority()) {
  1032.                     Presence.Mode pMode = p.getMode();
  1033.                     // Default to presence mode of available.
  1034.                     if (pMode == null) {
  1035.                         pMode = Presence.Mode.available;
  1036.                     }
  1037.                     Presence.Mode presenceMode = presence.getMode();
  1038.                     // Default to presence mode of available.
  1039.                     if (presenceMode == null) {
  1040.                         presenceMode = Presence.Mode.available;
  1041.                     }
  1042.                     if (pMode.compareTo(presenceMode) < 0) {
  1043.                         presence = p;
  1044.                     }
  1045.                 }
  1046.             }
  1047.             if (presence == null) {
  1048.                 if (unavailable != null) {
  1049.                     return unavailable;
  1050.                 }
  1051.                 else {
  1052.                     presence = synthesizeUnvailablePresence(jid);
  1053.                     return presence;
  1054.                 }
  1055.             }
  1056.             else {
  1057.                 return presence;
  1058.             }
  1059.         }
  1060.     }

  1061.     /**
  1062.      * Returns the presence info for a particular user's resource, or unavailable presence
  1063.      * if the user is offline or if no presence information is available, such as
  1064.      * when you are not subscribed to the user's presence updates.
  1065.      *
  1066.      * @param userWithResource a fully qualified XMPP ID including a resource (user@domain/resource).
  1067.      * @return the user's current presence, or unavailable presence if the user is offline
  1068.      *         or if no presence information is available.
  1069.      */
  1070.     public Presence getPresenceResource(FullJid userWithResource) {
  1071.         BareJid key = userWithResource.asBareJid();
  1072.         Resourcepart resource = userWithResource.getResourcepart();
  1073.         Map<Resourcepart, Presence> userPresences = getPresencesInternal(key);
  1074.         if (userPresences == null) {
  1075.             Presence presence = synthesizeUnvailablePresence(userWithResource);
  1076.             return presence;
  1077.         }
  1078.         else {
  1079.             Presence presence = userPresences.get(resource);
  1080.             if (presence == null) {
  1081.                 presence = synthesizeUnvailablePresence(userWithResource);
  1082.                 return presence;
  1083.             }
  1084.             else {
  1085.                 return presence;
  1086.             }
  1087.         }
  1088.     }

  1089.     /**
  1090.      * Returns a List of Presence objects for all of a user's current presences if no presence information is available,
  1091.      * such as when you are not subscribed to the user's presence updates.
  1092.      *
  1093.      * @param bareJid an XMPP ID, e.g. jdoe@example.com.
  1094.      * @return a List of Presence objects for all the user's current presences, or an unavailable presence if no
  1095.      *         presence information is available.
  1096.      */
  1097.     public List<Presence> getAllPresences(BareJid bareJid) {
  1098.         Map<Resourcepart, Presence> userPresences = getPresencesInternal(bareJid);
  1099.         List<Presence> res;
  1100.         if (userPresences == null) {
  1101.             // Create an unavailable presence if none was found
  1102.             Presence unavailable = synthesizeUnvailablePresence(bareJid);
  1103.             res = new ArrayList<>(Arrays.asList(unavailable));
  1104.         } else {
  1105.             res = new ArrayList<>(userPresences.values().size());
  1106.             for (Presence presence : userPresences.values()) {
  1107.                 res.add(presence);
  1108.             }
  1109.         }
  1110.         return res;
  1111.     }

  1112.     /**
  1113.      * Returns a List of all <b>available</b> Presence Objects for the given bare JID. If there are no available
  1114.      * presences, then the empty list will be returned.
  1115.      *
  1116.      * @param bareJid the bare JID from which the presences should be retrieved.
  1117.      * @return available presences for the bare JID.
  1118.      */
  1119.     public List<Presence> getAvailablePresences(BareJid bareJid) {
  1120.         List<Presence> allPresences = getAllPresences(bareJid);
  1121.         List<Presence> res = new ArrayList<>(allPresences.size());
  1122.         for (Presence presence : allPresences) {
  1123.             if (presence.isAvailable()) {
  1124.                 // No need to clone presence here, getAllPresences already returns clones
  1125.                 res.add(presence);
  1126.             }
  1127.         }
  1128.         return res;
  1129.     }

  1130.     /**
  1131.      * Returns a List of Presence objects for all of a user's current presences
  1132.      * or an unavailable presence if the user is unavailable (offline) or if no presence
  1133.      * information is available, such as when you are not subscribed to the user's presence
  1134.      * updates.
  1135.      *
  1136.      * @param jid an XMPP ID, e.g. jdoe@example.com.
  1137.      * @return a List of Presence objects for all the user's current presences,
  1138.      *         or an unavailable presence if the user is offline or if no presence information
  1139.      *         is available.
  1140.      */
  1141.     public List<Presence> getPresences(BareJid jid) {
  1142.         List<Presence> res;
  1143.         Map<Resourcepart, Presence> userPresences = getPresencesInternal(jid);
  1144.         if (userPresences == null) {
  1145.             Presence presence = synthesizeUnvailablePresence(jid);
  1146.             res = Arrays.asList(presence);
  1147.         }
  1148.         else {
  1149.             List<Presence> answer = new ArrayList<>();
  1150.             // Used in case no available presence is found
  1151.             Presence unavailable = null;
  1152.             for (Presence presence : userPresences.values()) {
  1153.                 if (presence.isAvailable()) {
  1154.                     answer.add(presence);
  1155.                 }
  1156.                 else {
  1157.                     unavailable = presence;
  1158.                 }
  1159.             }
  1160.             if (!answer.isEmpty()) {
  1161.                 res = answer;
  1162.             }
  1163.             else if (unavailable != null) {
  1164.                 res = Arrays.asList(unavailable);
  1165.             }
  1166.             else {
  1167.                 Presence presence = synthesizeUnvailablePresence(jid);
  1168.                 res = Arrays.asList(presence);
  1169.             }
  1170.         }
  1171.         return res;
  1172.     }

  1173.     /**
  1174.      * Check if the given JID is subscribed to the user's presence.
  1175.      * <p>
  1176.      * If the JID is subscribed to the user's presence then it is allowed to see the presence and
  1177.      * will get notified about presence changes. Also returns true, if the JID is the service
  1178.      * name of the XMPP connection (the "XMPP domain"), i.e. the XMPP service is treated like
  1179.      * having an implicit subscription to the users presence.
  1180.      * </p>
  1181.      * Note that if the roster is not loaded, then this method will always return false.
  1182.      *
  1183.      * @param jid TODO javadoc me please
  1184.      * @return true if the given JID is allowed to see the users presence.
  1185.      * @since 4.1
  1186.      */
  1187.     public boolean isSubscribedToMyPresence(Jid jid) {
  1188.         if (jid == null) {
  1189.             return false;
  1190.         }
  1191.         BareJid bareJid = jid.asBareJid();
  1192.         if (connection().getXMPPServiceDomain().equals(bareJid)) {
  1193.             return true;
  1194.         }
  1195.         RosterEntry entry = getEntry(bareJid);
  1196.         if (entry == null) {
  1197.             return false;
  1198.         }
  1199.         return entry.canSeeMyPresence();
  1200.     }

  1201.     /**
  1202.      * Check if the XMPP entity this roster belongs to is subscribed to the presence of the given JID.
  1203.      *
  1204.      * @param jid the jid to check.
  1205.      * @return <code>true</code> if we are subscribed to the presence of the given jid.
  1206.      * @since 4.2
  1207.      */
  1208.     public boolean iAmSubscribedTo(Jid jid) {
  1209.         if (jid == null) {
  1210.             return false;
  1211.         }
  1212.         BareJid bareJid = jid.asBareJid();
  1213.         RosterEntry entry = getEntry(bareJid);
  1214.         if (entry == null) {
  1215.             return false;
  1216.         }
  1217.         return entry.canSeeHisPresence();
  1218.     }

  1219.     /**
  1220.      * Sets if the roster will be loaded from the server when logging in for newly created instances
  1221.      * of {@link Roster}.
  1222.      *
  1223.      * @param rosterLoadedAtLoginDefault if the roster will be loaded from the server when logging in.
  1224.      * @see #setRosterLoadedAtLogin(boolean)
  1225.      * @since 4.1.7
  1226.      */
  1227.     public static void setRosterLoadedAtLoginDefault(boolean rosterLoadedAtLoginDefault) {
  1228.         Roster.rosterLoadedAtLoginDefault = rosterLoadedAtLoginDefault;
  1229.     }

  1230.     /**
  1231.      * Sets if the roster will be loaded from the server when logging in. This
  1232.      * is the common behaviour for clients but sometimes clients may want to differ this
  1233.      * or just never do it if not interested in rosters.
  1234.      *
  1235.      * @param rosterLoadedAtLogin if the roster will be loaded from the server when logging in.
  1236.      */
  1237.     public void setRosterLoadedAtLogin(boolean rosterLoadedAtLogin) {
  1238.         this.rosterLoadedAtLogin = rosterLoadedAtLogin;
  1239.     }

  1240.     /**
  1241.      * Returns true if the roster will be loaded from the server when logging in. This
  1242.      * is the common behavior for clients but sometimes clients may want to differ this
  1243.      * or just never do it if not interested in rosters.
  1244.      *
  1245.      * @return true if the roster will be loaded from the server when logging in.
  1246.      * @see <a href="http://xmpp.org/rfcs/rfc6121.html#roster-login">RFC 6121 2.2 - Retrieving the Roster on Login</a>
  1247.      */
  1248.     public boolean isRosterLoadedAtLogin() {
  1249.         return rosterLoadedAtLogin;
  1250.     }

  1251.     RosterStore getRosterStore() {
  1252.         return rosterStore;
  1253.     }

  1254.     /**
  1255.      * Changes the presence of available contacts offline by simulating an unavailable
  1256.      * presence sent from the server.
  1257.      */
  1258.     private void setOfflinePresences() {
  1259.         outerloop: for (Jid user : presenceMap.keySet()) {
  1260.             Map<Resourcepart, Presence> resources = presenceMap.get(user);
  1261.             if (resources != null) {
  1262.                 for (Resourcepart resource : resources.keySet()) {
  1263.                     PresenceBuilder presenceBuilder = StanzaBuilder.buildPresence()
  1264.                             .ofType(Presence.Type.unavailable);
  1265.                     EntityBareJid bareUserJid = user.asEntityBareJidIfPossible();
  1266.                     if (bareUserJid == null) {
  1267.                         LOGGER.warning("Can not transform user JID to bare JID: '" + user + "'");
  1268.                         continue;
  1269.                     }
  1270.                     presenceBuilder.from(JidCreate.fullFrom(bareUserJid, resource));
  1271.                     try {
  1272.                         presencePacketListener.processStanza(presenceBuilder.build());
  1273.                     }
  1274.                     catch (NotConnectedException e) {
  1275.                         throw new IllegalStateException(
  1276.                                         "presencePacketListener should never throw a NotConnectedException when processStanza is called with a presence of type unavailable",
  1277.                                         e);
  1278.                     }
  1279.                     catch (InterruptedException e) {
  1280.                         break outerloop;
  1281.                     }
  1282.                 }
  1283.             }
  1284.         }
  1285.     }

  1286.     /**
  1287.      * Changes the presence of available contacts offline by simulating an unavailable
  1288.      * presence sent from the server. After a disconnection, every Presence is set
  1289.      * to offline.
  1290.      */
  1291.     private void setOfflinePresencesAndResetLoaded() {
  1292.         setOfflinePresences();
  1293.         rosterState = RosterState.uninitialized;
  1294.     }

  1295.     /**
  1296.      * Fires roster changed event to roster listeners indicating that the
  1297.      * specified collections of contacts have been added, updated or deleted
  1298.      * from the roster.
  1299.      *
  1300.      * @param addedEntries   the collection of address of the added contacts.
  1301.      * @param updatedEntries the collection of address of the updated contacts.
  1302.      * @param deletedEntries the collection of address of the deleted contacts.
  1303.      */
  1304.     private void fireRosterChangedEvent(final Collection<Jid> addedEntries, final Collection<Jid> updatedEntries,
  1305.                     final Collection<Jid> deletedEntries) {
  1306.         synchronized (rosterListenersAndEntriesLock) {
  1307.             for (RosterListener listener : rosterListeners) {
  1308.                 if (!addedEntries.isEmpty()) {
  1309.                     listener.entriesAdded(addedEntries);
  1310.                 }
  1311.                 if (!updatedEntries.isEmpty()) {
  1312.                     listener.entriesUpdated(updatedEntries);
  1313.                 }
  1314.                 if (!deletedEntries.isEmpty()) {
  1315.                     listener.entriesDeleted(deletedEntries);
  1316.                 }
  1317.             }
  1318.         }
  1319.     }

  1320.     /**
  1321.      * Fires roster presence changed event to roster listeners.
  1322.      *
  1323.      * @param presence the presence change.
  1324.      */
  1325.     private void fireRosterPresenceEvent(final Presence presence) {
  1326.         synchronized (rosterListenersAndEntriesLock) {
  1327.             for (RosterListener listener : rosterListeners) {
  1328.                 listener.presenceChanged(presence);
  1329.             }
  1330.         }
  1331.     }

  1332.     private void addUpdateEntry(Collection<Jid> addedEntries, Collection<Jid> updatedEntries,
  1333.                     Collection<Jid> unchangedEntries, RosterPacket.Item item, RosterEntry entry) {
  1334.         RosterEntry oldEntry;
  1335.         synchronized (rosterListenersAndEntriesLock) {
  1336.             oldEntry = entries.put(item.getJid(), entry);
  1337.         }
  1338.         if (oldEntry == null) {
  1339.             BareJid jid = item.getJid();
  1340.             addedEntries.add(jid);
  1341.             // Move the eventually existing presences from nonRosterPresenceMap to presenceMap.
  1342.             move(jid, nonRosterPresenceMap, presenceMap);
  1343.         }
  1344.         else {
  1345.             RosterPacket.Item oldItem = RosterEntry.toRosterItem(oldEntry);
  1346.             if (!oldEntry.equalsDeep(entry) || !item.getGroupNames().equals(oldItem.getGroupNames())) {
  1347.                 updatedEntries.add(item.getJid());
  1348.                 oldEntry.updateItem(item);
  1349.             } else {
  1350.                 // Record the entry as unchanged, so that it doesn't end up as deleted entry
  1351.                 unchangedEntries.add(item.getJid());
  1352.             }
  1353.         }

  1354.         // Mark the entry as unfiled if it does not belong to any groups.
  1355.         if (item.getGroupNames().isEmpty()) {
  1356.             unfiledEntries.add(entry);
  1357.         }
  1358.         else {
  1359.             unfiledEntries.remove(entry);
  1360.         }

  1361.         // Add the entry/user to the groups
  1362.         List<String> newGroupNames = new ArrayList<>();
  1363.         for (String groupName : item.getGroupNames()) {
  1364.             // Add the group name to the list.
  1365.             newGroupNames.add(groupName);

  1366.             // Add the entry to the group.
  1367.             RosterGroup group = getGroup(groupName);
  1368.             if (group == null) {
  1369.                 group = createGroup(groupName);
  1370.                 groups.put(groupName, group);
  1371.             }
  1372.             // Add the entry.
  1373.             group.addEntryLocal(entry);
  1374.         }

  1375.         // Remove user from the remaining groups.
  1376.         List<String> oldGroupNames = new ArrayList<>();
  1377.         for (RosterGroup group : getGroups()) {
  1378.             oldGroupNames.add(group.getName());
  1379.         }
  1380.         oldGroupNames.removeAll(newGroupNames);

  1381.         for (String groupName : oldGroupNames) {
  1382.             RosterGroup group = getGroup(groupName);
  1383.             group.removeEntryLocal(entry);
  1384.             if (group.getEntryCount() == 0) {
  1385.                 groups.remove(groupName);
  1386.             }
  1387.         }
  1388.     }

  1389.     private void deleteEntry(Collection<Jid> deletedEntries, RosterEntry entry) {
  1390.         BareJid user = entry.getJid();
  1391.         entries.remove(user);
  1392.         unfiledEntries.remove(entry);
  1393.         // Move the presences from the presenceMap to the nonRosterPresenceMap.
  1394.         move(user, presenceMap, nonRosterPresenceMap);
  1395.         deletedEntries.add(user);

  1396.         for (Map.Entry<String, RosterGroup> e : groups.entrySet()) {
  1397.             RosterGroup group = e.getValue();
  1398.             group.removeEntryLocal(entry);
  1399.             if (group.getEntryCount() == 0) {
  1400.                 groups.remove(e.getKey());
  1401.             }
  1402.         }
  1403.     }

  1404.     /**
  1405.      * Removes all the groups with no entries.
  1406.      *
  1407.      * This is used by {@link RosterPushListener} and {@link RosterResultListener} to
  1408.      * cleanup groups after removing contacts.
  1409.      */
  1410.     private void removeEmptyGroups() {
  1411.         // We have to do this because RosterGroup.removeEntry removes the entry immediately
  1412.         // (locally) and the group could remain empty.
  1413.         // TODO Check the performance/logic for rosters with large number of groups
  1414.         for (RosterGroup group : getGroups()) {
  1415.             if (group.getEntryCount() == 0) {
  1416.                 groups.remove(group.getName());
  1417.             }
  1418.         }
  1419.     }

  1420.     /**
  1421.      * Move presences from 'entity' from one presence map to another.
  1422.      *
  1423.      * @param entity the entity
  1424.      * @param from the map to move presences from
  1425.      * @param to the map to move presences to
  1426.      */
  1427.     private static void move(BareJid entity, Map<BareJid, Map<Resourcepart, Presence>> from, Map<BareJid, Map<Resourcepart, Presence>> to) {
  1428.         Map<Resourcepart, Presence> presences = from.remove(entity);
  1429.         if (presences != null && !presences.isEmpty()) {
  1430.             to.put(entity, presences);
  1431.         }
  1432.     }

  1433.     /**
  1434.      * Ignore ItemTypes as of RFC 6121, 2.1.2.5.
  1435.      *
  1436.      * This is used by {@link RosterPushListener} and {@link RosterResultListener}.
  1437.      * */
  1438.     private static boolean hasValidSubscriptionType(RosterPacket.Item item) {
  1439.         switch (item.getItemType()) {
  1440.             case none:
  1441.             case from:
  1442.             case to:
  1443.             case both:
  1444.                 return true;
  1445.             default:
  1446.                 return false;
  1447.         }
  1448.     }

  1449.     private static Presence synthesizeUnvailablePresence(Jid from) {
  1450.         return StanzaBuilder.buildPresence()
  1451.                 .ofType(Presence.Type.unavailable)
  1452.                 .from(from)
  1453.                 .build();
  1454.     }

  1455.     /**
  1456.      * Check if the server supports roster versioning.
  1457.      *
  1458.      * @return true if the server supports roster versioning, false otherwise.
  1459.      */
  1460.     public boolean isRosterVersioningSupported() {
  1461.         return connection().hasFeature(RosterVer.ELEMENT, RosterVer.NAMESPACE);
  1462.     }

  1463.     /**
  1464.      * An enumeration for the subscription mode options.
  1465.      */
  1466.     public enum SubscriptionMode {

  1467.         /**
  1468.          * Automatically accept all subscription and unsubscription requests.
  1469.          * This is suitable for simple clients. More complex clients will
  1470.          * likely wish to handle subscription requests manually.
  1471.          */
  1472.         accept_all,

  1473.         /**
  1474.          * Automatically reject all subscription requests. This is the default mode.
  1475.          */
  1476.         reject_all,

  1477.         /**
  1478.          * Subscription requests are ignored, which means they must be manually
  1479.          * processed by registering a listener for presence packets and then looking
  1480.          * for any presence requests that have the type Presence.Type.SUBSCRIBE or
  1481.          * Presence.Type.UNSUBSCRIBE.
  1482.          */
  1483.         manual
  1484.     }

  1485.     /**
  1486.      * Listens for all presence packets and processes them.
  1487.      */
  1488.     private class PresencePacketListener implements StanzaListener {

  1489.         @Override
  1490.         public void processStanza(Stanza packet) throws NotConnectedException, InterruptedException {
  1491.             // Try to ensure that the roster is loaded when processing presence stanzas. While the
  1492.             // presence listener is synchronous, the roster result listener is not, which means that
  1493.             // the presence listener may be invoked with a not yet loaded roster.
  1494.             if (rosterState == RosterState.loading) {
  1495.                 try {
  1496.                     waitUntilLoaded();
  1497.                 }
  1498.                 catch (InterruptedException e) {
  1499.                     LOGGER.log(Level.INFO, "Presence listener was interrupted", e);

  1500.                 }
  1501.             }

  1502.             final Jid from = packet.getFrom();

  1503.             if (!isLoaded() && rosterLoadedAtLogin) {
  1504.                 XMPPConnection connection = connection();

  1505.                 // Only log the warning, if this is not the reflected self-presence. Otherwise,
  1506.                 // the reflected self-presence may cause a spurious warning in case the
  1507.                 // connection got quickly shut down. See SMACK-941.
  1508.                 if (connection != null && from != null && !from.equals(connection.getUser())) {
  1509.                     LOGGER.warning("Roster not loaded while processing " + packet);
  1510.                 }
  1511.             }
  1512.             final Presence presence = (Presence) packet;

  1513.             final BareJid key;
  1514.             if (from != null) {
  1515.                 key = from.asBareJid();
  1516.             } else {
  1517.                 XMPPConnection connection = connection();
  1518.                 if (connection == null) {
  1519.                     LOGGER.finest("Connection was null while trying to handle exotic presence stanza: " + presence);
  1520.                     return;
  1521.                 }
  1522.                 // Assume the presence come "from the users account on the server" since no from was set (RFC 6120 ยง
  1523.                 // 8.1.2.1 4.). Note that getUser() may return null, but should never return null in this case as where
  1524.                 // connected.
  1525.                 EntityFullJid myJid = connection.getUser();
  1526.                 if (myJid == null) {
  1527.                     LOGGER.info(
  1528.                             "Connection had no local address in Roster's presence listener."
  1529.                             + " Possibly we received a presence without from before being authenticated."
  1530.                             + " Presence: " + presence);
  1531.                     return;
  1532.                 }
  1533.                 LOGGER.info("Exotic presence stanza without from received: " + presence);
  1534.                 key = myJid.asBareJid();
  1535.             }

  1536.             asyncButOrdered.performAsyncButOrdered(key, new Runnable() {
  1537.                 @Override
  1538.                 public void run() {
  1539.                     Resourcepart fromResource = Resourcepart.EMPTY;
  1540.                     BareJid bareFrom = null;
  1541.                     FullJid fullFrom = null;
  1542.                     if (from != null) {
  1543.                         fromResource = from.getResourceOrNull();
  1544.                         if (fromResource == null) {
  1545.                             fromResource = Resourcepart.EMPTY;
  1546.                             bareFrom = from.asBareJid();
  1547.                         }
  1548.                         else {
  1549.                             fullFrom = from.asFullJidIfPossible();
  1550.                             // We know that this must be a full JID in this case.
  1551.                             assert fullFrom != null;
  1552.                         }
  1553.                     }
  1554.                     Map<Resourcepart, Presence> userPresences;
  1555.                     // If an "available" presence, add it to the presence map. Each presence
  1556.                     // map will hold for a particular user a map with the presence
  1557.                     // packets saved for each resource.
  1558.                     switch (presence.getType()) {
  1559.                     case available:
  1560.                         // Get the user presence map
  1561.                         userPresences = getOrCreatePresencesInternal(key);
  1562.                         // See if an offline presence was being stored in the map. If so, remove
  1563.                         // it since we now have an online presence.
  1564.                         userPresences.remove(Resourcepart.EMPTY);
  1565.                         // Add the new presence, using the resources as a key.
  1566.                         userPresences.put(fromResource, presence);
  1567.                         // If the user is in the roster, fire an event.
  1568.                         if (contains(key)) {
  1569.                             fireRosterPresenceEvent(presence);
  1570.                         }
  1571.                         for (PresenceEventListener presenceEventListener : presenceEventListeners) {
  1572.                             presenceEventListener.presenceAvailable(fullFrom, presence);
  1573.                         }
  1574.                         break;
  1575.                     // If an "unavailable" packet.
  1576.                     case unavailable:
  1577.                         // If no resource, this is likely an offline presence as part of
  1578.                         // a roster presence flood. In that case, we store it.
  1579.                         userPresences = getOrCreatePresencesInternal(key);
  1580.                         if (from.hasNoResource()) {
  1581.                             // Get the user presence map
  1582.                             userPresences.put(Resourcepart.EMPTY, presence);
  1583.                         }
  1584.                         // Otherwise, this is a normal offline presence.
  1585.                         else {
  1586.                             // Store the offline presence, as it may include extra information
  1587.                             // such as the user being on vacation.
  1588.                             userPresences.put(fromResource, presence);
  1589.                         }
  1590.                         // If the user is in the roster, fire an event.
  1591.                         if (contains(key)) {
  1592.                             fireRosterPresenceEvent(presence);
  1593.                         }

  1594.                         // Ensure that 'from' is a full JID before invoking the presence unavailable
  1595.                         // listeners. Usually unavailable presences always have a resourcepart, i.e. are
  1596.                         // full JIDs, but RFC 6121 ยง 4.5.4 has an implementation note that unavailable
  1597.                         // presences from a bare JID SHOULD be treated as applying to all resources. I don't
  1598.                         // think any client or server ever implemented that, I do think that this
  1599.                         // implementation note is a terrible idea since it adds another corner case in
  1600.                         // client code, instead of just having the invariant
  1601.                         // "unavailable presences are always from the full JID".
  1602.                         if (fullFrom != null) {
  1603.                             for (PresenceEventListener presenceEventListener : presenceEventListeners) {
  1604.                                 presenceEventListener.presenceUnavailable(fullFrom, presence);
  1605.                             }
  1606.                         } else {
  1607.                             LOGGER.fine("Unavailable presence from bare JID: " + presence);
  1608.                         }

  1609.                         break;
  1610.                     // Error presence packets from a bare JID mean we invalidate all existing
  1611.                     // presence info for the user.
  1612.                     case error:
  1613.                         // No need to act on error presences send without from, i.e.
  1614.                         // directly send from the users XMPP service, or where the from
  1615.                         // address is not a bare JID
  1616.                         if (from == null || !from.isEntityBareJid()) {
  1617.                             break;
  1618.                         }
  1619.                         userPresences = getOrCreatePresencesInternal(key);
  1620.                         // Any other presence data is invalidated by the error packet.
  1621.                         userPresences.clear();

  1622.                         // Set the new presence using the empty resource as a key.
  1623.                         userPresences.put(Resourcepart.EMPTY, presence);
  1624.                         // If the user is in the roster, fire an event.
  1625.                         if (contains(key)) {
  1626.                             fireRosterPresenceEvent(presence);
  1627.                         }
  1628.                         for (PresenceEventListener presenceEventListener : presenceEventListeners) {
  1629.                             presenceEventListener.presenceError(from, presence);
  1630.                         }
  1631.                         break;
  1632.                     case subscribed:
  1633.                         for (PresenceEventListener presenceEventListener : presenceEventListeners) {
  1634.                             presenceEventListener.presenceSubscribed(bareFrom, presence);
  1635.                         }
  1636.                         break;
  1637.                     case unsubscribed:
  1638.                         for (PresenceEventListener presenceEventListener : presenceEventListeners) {
  1639.                             presenceEventListener.presenceUnsubscribed(bareFrom, presence);
  1640.                         }
  1641.                         break;
  1642.                     default:
  1643.                         break;
  1644.                     }
  1645.                 }
  1646.             });
  1647.         }
  1648.     }

  1649.     /**
  1650.      * Handles Roster results as described in <a href="https://tools.ietf.org/html/rfc6121#section-2.1.4">RFC 6121 2.1.4</a>.
  1651.      */
  1652.     private class RosterResultListener implements SuccessCallback<IQ> {

  1653.         @Override
  1654.         public void onSuccess(IQ packet) {
  1655.             final XMPPConnection connection = connection();
  1656.             LOGGER.log(Level.FINE, "RosterResultListener received {0}", packet);
  1657.             Collection<Jid> addedEntries = new ArrayList<>();
  1658.             Collection<Jid> updatedEntries = new ArrayList<>();
  1659.             Collection<Jid> deletedEntries = new ArrayList<>();
  1660.             Collection<Jid> unchangedEntries = new ArrayList<>();

  1661.             if (packet instanceof RosterPacket) {
  1662.                 // Non-empty roster result. This stanza contains all the roster elements.
  1663.                 RosterPacket rosterPacket = (RosterPacket) packet;

  1664.                 // Ignore items without valid subscription type
  1665.                 ArrayList<Item> validItems = new ArrayList<>();
  1666.                 for (RosterPacket.Item item : rosterPacket.getRosterItems()) {
  1667.                     if (hasValidSubscriptionType(item)) {
  1668.                         validItems.add(item);
  1669.                     }
  1670.                 }

  1671.                 for (RosterPacket.Item item : validItems) {
  1672.                     RosterEntry entry = new RosterEntry(item, Roster.this, connection);
  1673.                     addUpdateEntry(addedEntries, updatedEntries, unchangedEntries, item, entry);
  1674.                 }

  1675.                 // Delete all entries which where not added or updated
  1676.                 Set<Jid> toDelete = new HashSet<>();
  1677.                 for (RosterEntry entry : entries.values()) {
  1678.                     toDelete.add(entry.getJid());
  1679.                 }
  1680.                 toDelete.removeAll(addedEntries);
  1681.                 toDelete.removeAll(updatedEntries);
  1682.                 toDelete.removeAll(unchangedEntries);
  1683.                 for (Jid user : toDelete) {
  1684.                     deleteEntry(deletedEntries, entries.get(user));
  1685.                 }

  1686.                 if (rosterStore != null) {
  1687.                     String version = rosterPacket.getVersion();
  1688.                     rosterStore.resetEntries(validItems, version);
  1689.                 }

  1690.                 removeEmptyGroups();
  1691.             }
  1692.             else {
  1693.                 // Empty roster result as defined in RFC6121 2.6.3. An empty roster result basically
  1694.                 // means that rosterver was used and the roster hasn't changed (much) since the
  1695.                 // version we presented the server. So we simply load the roster from the store and
  1696.                 // await possible further roster pushes.
  1697.                 List<RosterPacket.Item> storedItems = rosterStore.getEntries();
  1698.                 if (storedItems == null) {
  1699.                     // The roster store was corrupted. Reset the store and reload the roster without using a roster version.
  1700.                     rosterStore.resetStore();
  1701.                     try {
  1702.                         reload();
  1703.                     } catch (NotLoggedInException | NotConnectedException
  1704.                             | InterruptedException e) {
  1705.                         LOGGER.log(Level.FINE,
  1706.                                 "Exception while trying to load the roster after the roster store was corrupted",
  1707.                                 e);
  1708.                     }
  1709.                     return;
  1710.                 }
  1711.                 for (RosterPacket.Item item : storedItems) {
  1712.                     RosterEntry entry = new RosterEntry(item, Roster.this, connection);
  1713.                     addUpdateEntry(addedEntries, updatedEntries, unchangedEntries, item, entry);
  1714.                 }
  1715.             }

  1716.             rosterState = RosterState.loaded;
  1717.             synchronized (Roster.this) {
  1718.                 Roster.this.notifyAll();
  1719.             }
  1720.             // Fire event for roster listeners.
  1721.             fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries);

  1722.             // Call the roster loaded listeners after the roster events have been fired. This is
  1723.             // important because the user may call getEntriesAndAddListener() in onRosterLoaded(),
  1724.             // and if the order would be the other way around, the roster listener added by
  1725.             // getEntriesAndAddListener() would be invoked with information that was already
  1726.             // available at the time getEntriesAndAddListener() was called.
  1727.             try {
  1728.                 synchronized (rosterLoadedListeners) {
  1729.                     for (RosterLoadedListener rosterLoadedListener : rosterLoadedListeners) {
  1730.                         rosterLoadedListener.onRosterLoaded(Roster.this);
  1731.                     }
  1732.                 }
  1733.             }
  1734.             catch (Exception e) {
  1735.                 LOGGER.log(Level.WARNING, "RosterLoadedListener threw exception", e);
  1736.             }
  1737.         }
  1738.     }

  1739.     /**
  1740.      * Listens for all roster pushes and processes them.
  1741.      */
  1742.     private final class RosterPushListener extends AbstractIqRequestHandler {

  1743.         private RosterPushListener() {
  1744.             super(RosterPacket.ELEMENT, RosterPacket.NAMESPACE, IQ.Type.set, Mode.sync);
  1745.         }

  1746.         @Override
  1747.         public IQ handleIQRequest(IQ iqRequest) {
  1748.             final XMPPConnection connection = connection();
  1749.             RosterPacket rosterPacket = (RosterPacket) iqRequest;

  1750.             EntityFullJid ourFullJid = connection.getUser();
  1751.             if (ourFullJid == null) {
  1752.                 LOGGER.warning("Ignoring roster push " + iqRequest + " while " + connection
  1753.                                 + " has no bound resource. This may be a server bug.");
  1754.                 return null;
  1755.             }

  1756.             // Roster push (RFC 6121, 2.1.6)
  1757.             // A roster push with a non-empty from not matching our address MUST be ignored
  1758.             EntityBareJid ourBareJid = ourFullJid.asEntityBareJid();
  1759.             Jid from = rosterPacket.getFrom();
  1760.             if (from != null) {
  1761.                 if (from.equals(ourFullJid)) {
  1762.                     // Since RFC 6121 roster pushes are no longer allowed to
  1763.                     // origin from the full JID as it was the case with RFC
  1764.                     // 3921. Log a warning an continue processing the push.
  1765.                     // See also SMACK-773.
  1766.                     LOGGER.warning(
  1767.                             "Received roster push from full JID. This behavior is since RFC 6121 not longer standard compliant. "
  1768.                                     + "Please ask your server vendor to fix this and comply to RFC 6121 ยง 2.1.6. IQ roster push stanza: "
  1769.                                     + iqRequest);
  1770.                 } else if (!from.equals(ourBareJid)) {
  1771.                     LOGGER.warning("Ignoring roster push with a non matching 'from' ourJid='" + ourBareJid + "' from='"
  1772.                             + from + "'");
  1773.                     return IQ.createErrorResponse(iqRequest, Condition.service_unavailable);
  1774.                 }
  1775.             }

  1776.             // A roster push must contain exactly one entry
  1777.             Collection<Item> items = rosterPacket.getRosterItems();
  1778.             if (items.size() != 1) {
  1779.                 LOGGER.warning("Ignoring roster push with not exactly one entry. size=" + items.size());
  1780.                 return IQ.createErrorResponse(iqRequest, Condition.bad_request);
  1781.             }

  1782.             Collection<Jid> addedEntries = new ArrayList<>();
  1783.             Collection<Jid> updatedEntries = new ArrayList<>();
  1784.             Collection<Jid> deletedEntries = new ArrayList<>();
  1785.             Collection<Jid> unchangedEntries = new ArrayList<>();

  1786.             // We assured above that the size of items is exactly 1, therefore we are able to
  1787.             // safely retrieve this single item here.
  1788.             Item item = items.iterator().next();
  1789.             RosterEntry entry = new RosterEntry(item, Roster.this, connection);
  1790.             String version = rosterPacket.getVersion();

  1791.             if (item.getItemType().equals(RosterPacket.ItemType.remove)) {
  1792.                 deleteEntry(deletedEntries, entry);
  1793.                 if (rosterStore != null) {
  1794.                     rosterStore.removeEntry(entry.getJid(), version);
  1795.                 }
  1796.             }
  1797.             else if (hasValidSubscriptionType(item)) {
  1798.                 addUpdateEntry(addedEntries, updatedEntries, unchangedEntries, item, entry);
  1799.                 if (rosterStore != null) {
  1800.                     rosterStore.addEntry(item, version);
  1801.                 }
  1802.             }

  1803.             removeEmptyGroups();

  1804.             // Fire event for roster listeners.
  1805.             fireRosterChangedEvent(addedEntries, updatedEntries, deletedEntries);

  1806.             return IQ.createResultIQ(rosterPacket);
  1807.         }
  1808.     }

  1809.     /**
  1810.      * Set the default maximum size of the non-Roster presence map.
  1811.      * <p>
  1812.      * The roster will only store this many presence entries for entities non in the Roster. The
  1813.      * default is {@value #INITIAL_DEFAULT_NON_ROSTER_PRESENCE_MAP_SIZE}.
  1814.      * </p>
  1815.      *
  1816.      * @param maximumSize the maximum size
  1817.      * @since 4.2
  1818.      */
  1819.     public static void setDefaultNonRosterPresenceMapMaxSize(int maximumSize) {
  1820.         defaultNonRosterPresenceMapMaxSize = maximumSize;
  1821.     }

  1822.     /**
  1823.      * Set the maximum size of the non-Roster presence map.
  1824.      *
  1825.      * @param maximumSize TODO javadoc me please
  1826.      * @since 4.2
  1827.      * @see #setDefaultNonRosterPresenceMapMaxSize(int)
  1828.      */
  1829.     public void setNonRosterPresenceMapMaxSize(int maximumSize) {
  1830.         nonRosterPresenceMap.setMaxCacheSize(maximumSize);
  1831.     }

  1832. }