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