001/**
002 *
003 * Copyright 2003-2007 Jive Software. 2020-2021 Florian Schmaus
004 *
005 * Licensed under the Apache License, Version 2.0 (the "License");
006 * you may not use this file except in compliance with the License.
007 * You may obtain a copy of the License at
008 *
009 *     http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.jivesoftware.smackx.muc;
019
020import java.util.ArrayList;
021import java.util.Collection;
022import java.util.List;
023import java.util.Map;
024import java.util.Set;
025import java.util.concurrent.ConcurrentHashMap;
026import java.util.concurrent.CopyOnWriteArrayList;
027import java.util.concurrent.CopyOnWriteArraySet;
028import java.util.logging.Level;
029import java.util.logging.Logger;
030
031import org.jivesoftware.smack.MessageListener;
032import org.jivesoftware.smack.PresenceListener;
033import org.jivesoftware.smack.SmackException;
034import org.jivesoftware.smack.SmackException.NoResponseException;
035import org.jivesoftware.smack.SmackException.NotConnectedException;
036import org.jivesoftware.smack.StanzaCollector;
037import org.jivesoftware.smack.StanzaListener;
038import org.jivesoftware.smack.XMPPConnection;
039import org.jivesoftware.smack.XMPPException;
040import org.jivesoftware.smack.XMPPException.XMPPErrorException;
041import org.jivesoftware.smack.chat.ChatMessageListener;
042import org.jivesoftware.smack.filter.AndFilter;
043import org.jivesoftware.smack.filter.FromMatchesFilter;
044import org.jivesoftware.smack.filter.MessageTypeFilter;
045import org.jivesoftware.smack.filter.MessageWithBodiesFilter;
046import org.jivesoftware.smack.filter.MessageWithSubjectFilter;
047import org.jivesoftware.smack.filter.MessageWithThreadFilter;
048import org.jivesoftware.smack.filter.NotFilter;
049import org.jivesoftware.smack.filter.OrFilter;
050import org.jivesoftware.smack.filter.PossibleFromTypeFilter;
051import org.jivesoftware.smack.filter.PresenceTypeFilter;
052import org.jivesoftware.smack.filter.StanzaExtensionFilter;
053import org.jivesoftware.smack.filter.StanzaFilter;
054import org.jivesoftware.smack.filter.StanzaIdFilter;
055import org.jivesoftware.smack.filter.StanzaTypeFilter;
056import org.jivesoftware.smack.filter.ToMatchesFilter;
057import org.jivesoftware.smack.packet.IQ;
058import org.jivesoftware.smack.packet.Message;
059import org.jivesoftware.smack.packet.MessageBuilder;
060import org.jivesoftware.smack.packet.MessageView;
061import org.jivesoftware.smack.packet.Presence;
062import org.jivesoftware.smack.packet.Stanza;
063import org.jivesoftware.smack.util.Objects;
064
065import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
066import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
067import org.jivesoftware.smackx.iqregister.packet.Registration;
068import org.jivesoftware.smackx.muc.MultiUserChatException.MissingMucCreationAcknowledgeException;
069import org.jivesoftware.smackx.muc.MultiUserChatException.MucAlreadyJoinedException;
070import org.jivesoftware.smackx.muc.MultiUserChatException.MucNotJoinedException;
071import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException;
072import org.jivesoftware.smackx.muc.filter.MUCUserStatusCodeFilter;
073import org.jivesoftware.smackx.muc.packet.Destroy;
074import org.jivesoftware.smackx.muc.packet.MUCAdmin;
075import org.jivesoftware.smackx.muc.packet.MUCInitialPresence;
076import org.jivesoftware.smackx.muc.packet.MUCItem;
077import org.jivesoftware.smackx.muc.packet.MUCOwner;
078import org.jivesoftware.smackx.muc.packet.MUCUser;
079import org.jivesoftware.smackx.muc.packet.MUCUser.Status;
080import org.jivesoftware.smackx.xdata.FormField;
081import org.jivesoftware.smackx.xdata.TextSingleFormField;
082import org.jivesoftware.smackx.xdata.form.FillableForm;
083import org.jivesoftware.smackx.xdata.form.Form;
084import org.jivesoftware.smackx.xdata.packet.DataForm;
085
086import org.jxmpp.jid.DomainBareJid;
087import org.jxmpp.jid.EntityBareJid;
088import org.jxmpp.jid.EntityFullJid;
089import org.jxmpp.jid.EntityJid;
090import org.jxmpp.jid.Jid;
091import org.jxmpp.jid.impl.JidCreate;
092import org.jxmpp.jid.parts.Resourcepart;
093
094/**
095 * A MultiUserChat room (XEP-45), created with {@link MultiUserChatManager#getMultiUserChat(EntityBareJid)}.
096 * <p>
097 * A MultiUserChat is a conversation that takes place among many users in a virtual
098 * room. A room could have many occupants with different affiliation and roles.
099 * Possible affiliations are "owner", "admin", "member", and "outcast". Possible roles
100 * are "moderator", "participant", and "visitor". Each role and affiliation guarantees
101 * different privileges (e.g. Send messages to all occupants, Kick participants and visitors,
102 * Grant voice, Edit member list, etc.).
103 * </p>
104 * <p>
105 * <b>Note:</b> Make sure to leave the MUC ({@link #leave()}) when you don't need it anymore or
106 * otherwise you may leak the instance.
107 * </p>
108 *
109 * @author Gaston Dombiak
110 * @author Larry Kirschner
111 * @author Florian Schmaus
112 */
113public class MultiUserChat {
114    private static final Logger LOGGER = Logger.getLogger(MultiUserChat.class.getName());
115
116    private final XMPPConnection connection;
117    private final EntityBareJid room;
118    private final MultiUserChatManager multiUserChatManager;
119    private final Map<EntityFullJid, Presence> occupantsMap = new ConcurrentHashMap<>();
120
121    private final Set<InvitationRejectionListener> invitationRejectionListeners = new CopyOnWriteArraySet<InvitationRejectionListener>();
122    private final Set<SubjectUpdatedListener> subjectUpdatedListeners = new CopyOnWriteArraySet<SubjectUpdatedListener>();
123    private final Set<UserStatusListener> userStatusListeners = new CopyOnWriteArraySet<UserStatusListener>();
124    private final Set<ParticipantStatusListener> participantStatusListeners = new CopyOnWriteArraySet<ParticipantStatusListener>();
125    private final Set<MessageListener> messageListeners = new CopyOnWriteArraySet<MessageListener>();
126    private final Set<PresenceListener> presenceListeners = new CopyOnWriteArraySet<PresenceListener>();
127    private final Set<PresenceListener> presenceInterceptors = new CopyOnWriteArraySet<PresenceListener>();
128
129    /**
130     * This filter will match all stanzas send from the groupchat or from one if
131     * the groupchat participants, i.e. it filters only the bare JID of the from
132     * attribute against the JID of the MUC.
133     */
134    private final StanzaFilter fromRoomFilter;
135
136    /**
137     * Same as {@link #fromRoomFilter} together with {@link MessageTypeFilter#GROUPCHAT}.
138     */
139    private final StanzaFilter fromRoomGroupchatFilter;
140
141    private final StanzaListener presenceInterceptor;
142    private final StanzaListener messageListener;
143    private final StanzaListener presenceListener;
144    private final StanzaListener subjectListener;
145
146    private static final StanzaFilter DECLINE_FILTER = new AndFilter(MessageTypeFilter.NORMAL,
147                    new StanzaExtensionFilter(MUCUser.ELEMENT, MUCUser.NAMESPACE));
148    private final StanzaListener declinesListener;
149
150    private String subject;
151    private EntityFullJid myRoomJid;
152    private StanzaCollector messageCollector;
153
154    private DiscoverInfo mucServiceDiscoInfo;
155
156    /**
157     * Used to signal that the reflected self-presence was received <b>and</b> processed by us.
158     */
159    private volatile boolean processedReflectedSelfPresence;
160
161    private CopyOnWriteArrayList<MucMessageInterceptor> messageInterceptors;
162
163    MultiUserChat(XMPPConnection connection, EntityBareJid room, MultiUserChatManager multiUserChatManager) {
164        this.connection = connection;
165        this.room = room;
166        this.multiUserChatManager = multiUserChatManager;
167        this.messageInterceptors = MultiUserChatManager.getMessageInterceptors();
168
169        fromRoomFilter = FromMatchesFilter.create(room);
170        fromRoomGroupchatFilter = new AndFilter(fromRoomFilter, MessageTypeFilter.GROUPCHAT);
171
172        messageListener = new StanzaListener() {
173            @Override
174            public void processStanza(Stanza packet) throws NotConnectedException {
175                final Message message = (Message) packet;
176
177                for (MessageListener listener : messageListeners) {
178                            listener.processMessage(message);
179                }
180            }
181        };
182
183        // Create a listener for subject updates.
184        subjectListener = new StanzaListener() {
185            @Override
186            public void processStanza(Stanza packet) {
187                final Message msg = (Message) packet;
188                final EntityFullJid from = msg.getFrom().asEntityFullJidIfPossible();
189                // Update the room subject
190                subject = msg.getSubject();
191
192                // Fire event for subject updated listeners
193                for (SubjectUpdatedListener listener : subjectUpdatedListeners) {
194                    listener.subjectUpdated(msg.getSubject(), from);
195                }
196            }
197        };
198
199        // Create a listener for all presence updates.
200        presenceListener = new StanzaListener() {
201            @Override
202            public void processStanza(final Stanza packet) {
203                final Presence presence = (Presence) packet;
204                final EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible();
205                if (from == null) {
206                    return;
207                }
208                final EntityFullJid myRoomJID = myRoomJid;
209                final boolean isUserStatusModification = presence.getFrom().equals(myRoomJID);
210                final MUCUser mucUser = MUCUser.from(packet);
211
212                switch (presence.getType()) {
213                case available:
214                    if (!processedReflectedSelfPresence
215                                    && mucUser.getStatus().contains(MUCUser.Status.PRESENCE_TO_SELF_110)) {
216                        processedReflectedSelfPresence = true;
217                        synchronized (this) {
218                            notify();
219                        }
220                    }
221
222                    Presence oldPresence = occupantsMap.put(from, presence);
223                    if (oldPresence != null) {
224                        // Get the previous occupant's affiliation & role
225                        MUCUser mucExtension = MUCUser.from(oldPresence);
226                        MUCAffiliation oldAffiliation = mucExtension.getItem().getAffiliation();
227                        MUCRole oldRole = mucExtension.getItem().getRole();
228                        // Get the new occupant's affiliation & role
229                        MUCAffiliation newAffiliation = mucUser.getItem().getAffiliation();
230                        MUCRole newRole = mucUser.getItem().getRole();
231                        // Fire role modification events
232                        checkRoleModifications(oldRole, newRole, isUserStatusModification, from);
233                        // Fire affiliation modification events
234                        checkAffiliationModifications(
235                            oldAffiliation,
236                            newAffiliation,
237                            isUserStatusModification,
238                            from);
239                    } else {
240                        // A new occupant has joined the room
241                        for (ParticipantStatusListener listener : participantStatusListeners) {
242                            listener.joined(from);
243                        }
244                    }
245                    break;
246                case unavailable:
247                    occupantsMap.remove(from);
248                    if (mucUser != null && mucUser.hasStatus()) {
249                        if (isUserStatusModification) {
250                            userHasLeft();
251                        }
252                        // Fire events according to the received presence code
253                        checkPresenceCode(
254                            mucUser.getStatus(),
255                            isUserStatusModification,
256                            mucUser,
257                            from);
258                    } else {
259                        // An occupant has left the room
260                        if (!isUserStatusModification) {
261                            for (ParticipantStatusListener listener : participantStatusListeners) {
262                                listener.left(from);
263                            }
264                        }
265                    }
266
267                    Destroy destroy = mucUser.getDestroy();
268                    // The room has been destroyed.
269                    if (destroy != null) {
270                        EntityBareJid alternateMucJid = destroy.getJid();
271                        final MultiUserChat alternateMuc;
272                        if (alternateMucJid == null) {
273                            alternateMuc = null;
274                        } else {
275                            alternateMuc = multiUserChatManager.getMultiUserChat(alternateMucJid);
276                        }
277
278                        for (UserStatusListener listener : userStatusListeners) {
279                            listener.roomDestroyed(alternateMuc, destroy.getReason());
280                        }
281                    }
282
283                    if (isUserStatusModification) {
284                        for (UserStatusListener listener : userStatusListeners) {
285                            listener.removed(mucUser, presence);
286                        }
287                    } else {
288                        for (ParticipantStatusListener listener : participantStatusListeners) {
289                            listener.parted(from);
290                        }
291                    }
292                    break;
293                default:
294                    break;
295                }
296                for (PresenceListener listener : presenceListeners) {
297                    listener.processPresence(presence);
298                }
299            }
300        };
301
302        // Listens for all messages that include a MUCUser extension and fire the invitation
303        // rejection listeners if the message includes an invitation rejection.
304        declinesListener = new StanzaListener() {
305            @Override
306            public void processStanza(Stanza packet) {
307                Message message = (Message) packet;
308                // Get the MUC User extension
309                MUCUser mucUser = MUCUser.from(packet);
310                MUCUser.Decline rejection = mucUser.getDecline();
311                // Check if the MUCUser informs that the invitee has declined the invitation
312                if (rejection == null) {
313                    return;
314                }
315                // Fire event for invitation rejection listeners
316                fireInvitationRejectionListeners(message, rejection);
317            }
318        };
319
320        presenceInterceptor = new StanzaListener() {
321            @Override
322            public void processStanza(Stanza packet) {
323                Presence presence = (Presence) packet;
324                for (PresenceListener interceptor : presenceInterceptors) {
325                    interceptor.processPresence(presence);
326                }
327            }
328        };
329    }
330
331
332    /**
333     * Returns the name of the room this MultiUserChat object represents.
334     *
335     * @return the multi user chat room name.
336     */
337    public EntityBareJid getRoom() {
338        return room;
339    }
340
341    /**
342     * Enter a room, as described in XEP-45 7.2.
343     *
344     * @param conf the configuration used to enter the room.
345     * @return the returned presence by the service after the client send the initial presence in order to enter the room.
346     * @throws NotConnectedException if the XMPP connection is not connected.
347     * @throws NoResponseException if there was no response from the remote entity.
348     * @throws XMPPErrorException if there was an XMPP error returned.
349     * @throws InterruptedException if the calling thread was interrupted.
350     * @throws NotAMucServiceException if the entity is not a MUC serivce.
351     * @see <a href="http://xmpp.org/extensions/xep-0045.html#enter">XEP-45 7.2 Entering a Room</a>
352     */
353    private Presence enter(MucEnterConfiguration conf) throws NotConnectedException, NoResponseException,
354                    XMPPErrorException, InterruptedException, NotAMucServiceException {
355        final DomainBareJid mucService = room.asDomainBareJid();
356        mucServiceDiscoInfo = multiUserChatManager.getMucServiceDiscoInfo(mucService);
357        if (mucServiceDiscoInfo == null) {
358            throw new NotAMucServiceException(this);
359        }
360        // We enter a room by sending a presence packet where the "to"
361        // field is in the form "roomName@service/nickname"
362        Presence joinPresence = conf.getJoinPresence(this);
363
364        // Setup the messageListeners and presenceListeners *before* the join presence is send.
365        connection.addStanzaListener(messageListener, fromRoomGroupchatFilter);
366        StanzaFilter presenceFromRoomFilter = new AndFilter(fromRoomFilter,
367                        StanzaTypeFilter.PRESENCE,
368                        PossibleFromTypeFilter.ENTITY_FULL_JID);
369        connection.addStanzaListener(presenceListener, presenceFromRoomFilter);
370        // @formatter:off
371        connection.addStanzaListener(subjectListener,
372                        new AndFilter(fromRoomFilter,
373                                      MessageWithSubjectFilter.INSTANCE,
374                                      new NotFilter(MessageTypeFilter.ERROR),
375                                      // According to XEP-0045 § 8.1 "A message with a <subject/> and a <body/> or a <subject/> and a <thread/> is a
376                                      // legitimate message, but it SHALL NOT be interpreted as a subject change."
377                                      new NotFilter(MessageWithBodiesFilter.INSTANCE),
378                                      new NotFilter(MessageWithThreadFilter.INSTANCE))
379                        );
380        // @formatter:on
381        connection.addStanzaListener(declinesListener, new AndFilter(fromRoomFilter, DECLINE_FILTER));
382        connection.addStanzaSendingListener(presenceInterceptor, new AndFilter(ToMatchesFilter.create(room),
383                        StanzaTypeFilter.PRESENCE));
384        messageCollector = connection.createStanzaCollector(fromRoomGroupchatFilter);
385
386        // Wait for a presence packet back from the server.
387        // @formatter:off
388        StanzaFilter responseFilter = new AndFilter(StanzaTypeFilter.PRESENCE,
389                        new OrFilter(
390                            // We use a bare JID filter for positive responses, since the MUC service/room may rewrite the nickname.
391                            new AndFilter(FromMatchesFilter.createBare(getRoom()), MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
392                            // In case there is an error reply, we match on an error presence with the same stanza id and from the full
393                            // JID we send the join presence to.
394                            new AndFilter(FromMatchesFilter.createFull(joinPresence.getTo()), new StanzaIdFilter(joinPresence), PresenceTypeFilter.ERROR)
395                        )
396                    );
397        // @formatter:on
398        processedReflectedSelfPresence = false;
399        StanzaCollector presenceStanzaCollector = null;
400        final Presence reflectedSelfPresence;
401        try {
402            // This stanza collector will collect the final self presence from the MUC, which also signals that we have successful entered the MUC.
403            StanzaCollector selfPresenceCollector = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
404            StanzaCollector.Configuration presenceStanzaCollectorConfguration = StanzaCollector.newConfiguration().setCollectorToReset(
405                            selfPresenceCollector).setStanzaFilter(presenceFromRoomFilter);
406            // This stanza collector is used to reset the timeout of the selfPresenceCollector.
407            presenceStanzaCollector = connection.createStanzaCollector(presenceStanzaCollectorConfguration);
408            reflectedSelfPresence = selfPresenceCollector.nextResultOrThrow(conf.getTimeout());
409        }
410        catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) {
411            // Ensure that all callbacks are removed if there is an exception
412            removeConnectionCallbacks();
413            throw e;
414        }
415        finally {
416            if (presenceStanzaCollector != null) {
417                presenceStanzaCollector.cancel();
418            }
419        }
420
421        synchronized (presenceListener) {
422            // Only continue after we have received *and* processed the reflected self-presence. Since presences are
423            // handled in an extra listener, we may return from enter() without having processed all presences of the
424            // participants, resulting in a e.g. to low participant counter after enter(). Hence we wait here until the
425            // processing is done.
426            while (!processedReflectedSelfPresence) {
427                presenceListener.wait();
428            }
429        }
430
431        // This presence must be send from a full JID. We use the resourcepart of this JID as nick, since the room may
432        // performed roomnick rewriting
433        Resourcepart receivedNickname = reflectedSelfPresence.getFrom().getResourceOrThrow();
434        setNickname(receivedNickname);
435
436        // Update the list of joined rooms
437        multiUserChatManager.addJoinedRoom(room);
438        return reflectedSelfPresence;
439    }
440
441    private void setNickname(Resourcepart nickname) {
442        this.myRoomJid = JidCreate.entityFullFrom(room, nickname);
443    }
444
445    /**
446     * Get a new MUC enter configuration builder.
447     *
448     * @param nickname the nickname used when entering the MUC room.
449     * @return a new MUC enter configuration builder.
450     * @since 4.2
451     */
452    public MucEnterConfiguration.Builder getEnterConfigurationBuilder(Resourcepart nickname) {
453        return new MucEnterConfiguration.Builder(nickname, connection);
454    }
455
456    /**
457     * Creates the room according to some default configuration, assign the requesting user as the
458     * room owner, and add the owner to the room but not allow anyone else to enter the room
459     * (effectively "locking" the room). The requesting user will join the room under the specified
460     * nickname as soon as the room has been created.
461     * <p>
462     * To create an "Instant Room", that means a room with some default configuration that is
463     * available for immediate access, the room's owner should send an empty form after creating the
464     * room. Simply call {@link MucCreateConfigFormHandle#makeInstant()} on the returned {@link MucCreateConfigFormHandle}.
465     * </p>
466     * <p>
467     * To create a "Reserved Room", that means a room manually configured by the room creator before
468     * anyone is allowed to enter, the room's owner should complete and send a form after creating
469     * the room. Once the completed configuration form is sent to the server, the server will unlock
470     * the room. You can use the returned {@link MucCreateConfigFormHandle} to configure the room.
471     * </p>
472     *
473     * @param nickname the nickname to use.
474     * @return a handle to the MUC create configuration form API.
475     * @throws XMPPErrorException if the room couldn't be created for some reason (e.g. 405 error if
476     *         the user is not allowed to create the room)
477     * @throws NoResponseException if there was no response from the server.
478     * @throws InterruptedException if the calling thread was interrupted.
479     * @throws NotConnectedException if the XMPP connection is not connected.
480     * @throws MucAlreadyJoinedException if already joined the Multi-User Chat.7y
481     * @throws MissingMucCreationAcknowledgeException if there MUC creation was not acknowledged by the service.
482     * @throws NotAMucServiceException if the entity is not a MUC serivce.
483     */
484    public synchronized MucCreateConfigFormHandle create(Resourcepart nickname) throws NoResponseException,
485                    XMPPErrorException, InterruptedException, MucAlreadyJoinedException,
486                    NotConnectedException, MissingMucCreationAcknowledgeException, NotAMucServiceException {
487        if (isJoined()) {
488            throw new MucAlreadyJoinedException();
489        }
490
491        MucCreateConfigFormHandle mucCreateConfigFormHandle = createOrJoin(nickname);
492        if (mucCreateConfigFormHandle != null) {
493            // We successfully created a new room
494            return mucCreateConfigFormHandle;
495        }
496        // We need to leave the room since it seems that the room already existed
497        try {
498            leave();
499        }
500        catch (MucNotJoinedException e) {
501            LOGGER.log(Level.INFO, "Unexpected MucNotJoinedException", e);
502        }
503        throw new MissingMucCreationAcknowledgeException();
504    }
505
506    /**
507     * Create or join the MUC room with the given nickname.
508     *
509     * @param nickname the nickname to use in the MUC room.
510     * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
511     * @throws NoResponseException if there was no response from the remote entity.
512     * @throws XMPPErrorException if there was an XMPP error returned.
513     * @throws InterruptedException if the calling thread was interrupted.
514     * @throws NotConnectedException if the XMPP connection is not connected.
515     * @throws MucAlreadyJoinedException if already joined the Multi-User Chat.7y
516     * @throws NotAMucServiceException if the entity is not a MUC serivce.
517     */
518    public synchronized MucCreateConfigFormHandle createOrJoin(Resourcepart nickname) throws NoResponseException, XMPPErrorException,
519                    InterruptedException, MucAlreadyJoinedException, NotConnectedException, NotAMucServiceException {
520        MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).build();
521        return createOrJoin(mucEnterConfiguration);
522    }
523
524    /**
525     * Like {@link #create(Resourcepart)}, but will return a {@link MucCreateConfigFormHandle} if the room creation was acknowledged by
526     * the service (with an 201 status code). It's up to the caller to decide, based on the return
527     * value, if he needs to continue sending the room configuration. If {@code null} is returned, the room
528     * already existed and the user is able to join right away, without sending a form.
529     *
530     * @param mucEnterConfiguration the configuration used to enter the MUC.
531     * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
532     * @throws XMPPErrorException if the room couldn't be created for some reason (e.g. 405 error if
533     *         the user is not allowed to create the room)
534     * @throws NoResponseException if there was no response from the server.
535     * @throws InterruptedException if the calling thread was interrupted.
536     * @throws MucAlreadyJoinedException if the MUC is already joined
537     * @throws NotConnectedException if the XMPP connection is not connected.
538     * @throws NotAMucServiceException if the entity is not a MUC serivce.
539     */
540    public synchronized MucCreateConfigFormHandle createOrJoin(MucEnterConfiguration mucEnterConfiguration)
541                    throws NoResponseException, XMPPErrorException, InterruptedException, MucAlreadyJoinedException, NotConnectedException, NotAMucServiceException {
542        if (isJoined()) {
543            throw new MucAlreadyJoinedException();
544        }
545
546        Presence presence = enter(mucEnterConfiguration);
547
548        // Look for confirmation of room creation from the server
549        MUCUser mucUser = MUCUser.from(presence);
550        if (mucUser != null && mucUser.getStatus().contains(Status.ROOM_CREATED_201)) {
551            // Room was created and the user has joined the room
552            return new MucCreateConfigFormHandle();
553        }
554        return null;
555    }
556
557    /**
558     * A handle used to configure a newly created room. As long as the room is not configured it will be locked, which
559     * means that no one is able to join. The room will become unlocked as soon it got configured. In order to create an
560     * instant room, use {@link #makeInstant()}.
561     * <p>
562     * For advanced configuration options, use {@link MultiUserChat#getConfigurationForm()}, get the answer form with
563     * {@link Form#getFillableForm()}, fill it out and send it back to the room with
564     * {@link MultiUserChat#sendConfigurationForm(FillableForm)}.
565     * </p>
566     */
567    public class MucCreateConfigFormHandle {
568
569        /**
570         * Create an instant room. The default configuration will be accepted and the room will become unlocked, i.e.
571         * other users are able to join.
572         *
573         * @throws NoResponseException if there was no response from the remote entity.
574         * @throws XMPPErrorException if there was an XMPP error returned.
575         * @throws NotConnectedException if the XMPP connection is not connected.
576         * @throws InterruptedException if the calling thread was interrupted.
577         * @see <a href="http://www.xmpp.org/extensions/xep-0045.html#createroom-instant">XEP-45 § 10.1.2 Creating an
578         *      Instant Room</a>
579         */
580        public void makeInstant() throws NoResponseException, XMPPErrorException, NotConnectedException,
581                        InterruptedException {
582            sendConfigurationForm(null);
583        }
584
585        /**
586         * Alias for {@link MultiUserChat#getConfigFormManager()}.
587         *
588         * @return a MUC configuration form manager for this room.
589         * @throws NoResponseException if there was no response from the remote entity.
590         * @throws XMPPErrorException if there was an XMPP error returned.
591         * @throws NotConnectedException if the XMPP connection is not connected.
592         * @throws InterruptedException if the calling thread was interrupted.
593         * @see MultiUserChat#getConfigFormManager()
594         */
595        public MucConfigFormManager getConfigFormManager() throws NoResponseException,
596                        XMPPErrorException, NotConnectedException, InterruptedException {
597            return MultiUserChat.this.getConfigFormManager();
598        }
599    }
600
601    /**
602     * Create or join a MUC if it is necessary, i.e. if not the MUC is not already joined.
603     *
604     * @param nickname the required nickname to use.
605     * @param password the optional password required to join
606     * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
607     * @throws NoResponseException if there was no response from the remote entity.
608     * @throws XMPPErrorException if there was an XMPP error returned.
609     * @throws NotConnectedException if the XMPP connection is not connected.
610     * @throws InterruptedException if the calling thread was interrupted.
611     * @throws NotAMucServiceException if the entity is not a MUC serivce.
612     */
613    public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException,
614                    XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException {
615        if (isJoined()) {
616            return null;
617        }
618        MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword(
619                        password).build();
620        try {
621            return createOrJoin(mucEnterConfiguration);
622        }
623        catch (MucAlreadyJoinedException e) {
624            return null;
625        }
626    }
627
628    /**
629     * Joins the chat room using the specified nickname. If already joined
630     * using another nickname, this method will first leave the room and then
631     * re-join using the new nickname. The default connection timeout for a reply
632     * from the group chat server that the join succeeded will be used. After
633     * joining the room, the room will decide the amount of history to send.
634     *
635     * @param nickname the nickname to use.
636     * @return the leave self-presence as reflected by the MUC.
637     * @throws NoResponseException if there was no response from the remote entity.
638     * @throws XMPPErrorException if an error occurs joining the room. In particular, a
639     *      401 error can occur if no password was provided and one is required; or a
640     *      403 error can occur if the user is banned; or a
641     *      404 error can occur if the room does not exist or is locked; or a
642     *      407 error can occur if user is not on the member list; or a
643     *      409 error can occur if someone is already in the group chat with the same nickname.
644     * @throws NoResponseException if there was no response from the server.
645     * @throws NotConnectedException if the XMPP connection is not connected.
646     * @throws InterruptedException if the calling thread was interrupted.
647     * @throws NotAMucServiceException if the entity is not a MUC serivce.
648     */
649    public Presence join(Resourcepart nickname) throws NoResponseException, XMPPErrorException,
650                    NotConnectedException, InterruptedException, NotAMucServiceException {
651        MucEnterConfiguration.Builder builder = getEnterConfigurationBuilder(nickname);
652        Presence reflectedJoinPresence = join(builder.build());
653        return reflectedJoinPresence;
654    }
655
656    /**
657     * Joins the chat room using the specified nickname and password. If already joined
658     * using another nickname, this method will first leave the room and then
659     * re-join using the new nickname. The default connection timeout for a reply
660     * from the group chat server that the join succeeded will be used. After
661     * joining the room, the room will decide the amount of history to send.<p>
662     *
663     * A password is required when joining password protected rooms. If the room does
664     * not require a password there is no need to provide one.
665     *
666     * @param nickname the nickname to use.
667     * @param password the password to use.
668     * @throws XMPPErrorException if an error occurs joining the room. In particular, a
669     *      401 error can occur if no password was provided and one is required; or a
670     *      403 error can occur if the user is banned; or a
671     *      404 error can occur if the room does not exist or is locked; or a
672     *      407 error can occur if user is not on the member list; or a
673     *      409 error can occur if someone is already in the group chat with the same nickname.
674     * @throws InterruptedException if the calling thread was interrupted.
675     * @throws NotConnectedException if the XMPP connection is not connected.
676     * @throws NoResponseException if there was no response from the server.
677     * @throws NotAMucServiceException if the entity is not a MUC serivce.
678     */
679    public void join(Resourcepart nickname, String password) throws XMPPErrorException, InterruptedException, NoResponseException, NotConnectedException, NotAMucServiceException {
680        MucEnterConfiguration.Builder builder = getEnterConfigurationBuilder(nickname).withPassword(
681                        password);
682        join(builder.build());
683    }
684
685    /**
686     * Joins the chat room using the specified nickname and password. If already joined
687     * using another nickname, this method will first leave the room and then
688     * re-join using the new nickname.<p>
689     *
690     * To control the amount of history to receive while joining a room you will need to provide
691     * a configured DiscussionHistory object.<p>
692     *
693     * A password is required when joining password protected rooms. If the room does
694     * not require a password there is no need to provide one.<p>
695     *
696     * If the room does not already exist when the user seeks to enter it, the server will
697     * decide to create a new room or not.
698     *
699     * @param mucEnterConfiguration the configuration used to enter the MUC.
700     * @return the join self-presence as reflected by the MUC.
701     * @throws XMPPErrorException if an error occurs joining the room. In particular, a
702     *      401 error can occur if no password was provided and one is required; or a
703     *      403 error can occur if the user is banned; or a
704     *      404 error can occur if the room does not exist or is locked; or a
705     *      407 error can occur if user is not on the member list; or a
706     *      409 error can occur if someone is already in the group chat with the same nickname.
707     * @throws NoResponseException if there was no response from the server.
708     * @throws NotConnectedException if the XMPP connection is not connected.
709     * @throws InterruptedException if the calling thread was interrupted.
710     * @throws NotAMucServiceException if the entity is not a MUC serivce.
711     */
712    public synchronized Presence join(MucEnterConfiguration mucEnterConfiguration)
713        throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException, NotAMucServiceException {
714        // If we've already joined the room, leave it before joining under a new
715        // nickname.
716        if (isJoined()) {
717            try {
718                leaveSync();
719            }
720            catch (XMPPErrorException | NoResponseException | MucNotJoinedException e) {
721                LOGGER.log(Level.WARNING, "Could not leave MUC prior joining, assuming we are not joined", e);
722            }
723        }
724        Presence reflectedJoinPresence = enter(mucEnterConfiguration);
725        return reflectedJoinPresence;
726    }
727
728    /**
729     * Returns true if currently in the multi user chat (after calling the {@link
730     * #join(Resourcepart)} method).
731     *
732     * @return true if currently in the multi user chat room.
733     */
734    public boolean isJoined() {
735        return myRoomJid != null;
736    }
737
738    /**
739     * Leave the chat room.
740     *
741     * @return the leave presence as reflected by the MUC.
742     * @throws NotConnectedException if the XMPP connection is not connected.
743     * @throws InterruptedException if the calling thread was interrupted.
744     * @throws XMPPErrorException if there was an XMPP error returned.
745     * @throws NoResponseException if there was no response from the remote entity.
746     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
747     * @deprecated use {@link #leave()} instead.
748     */
749    @Deprecated
750    // TODO: Remove in Smack 4.5.
751    public synchronized Presence leaveSync() throws NotConnectedException, InterruptedException, MucNotJoinedException, NoResponseException, XMPPErrorException {
752        return leave();
753    }
754
755    /**
756     * Leave the chat room.
757     *
758     * @return the leave presence as reflected by the MUC.
759     * @throws NotConnectedException if the XMPP connection is not connected.
760     * @throws InterruptedException if the calling thread was interrupted.
761     * @throws XMPPErrorException if there was an XMPP error returned.
762     * @throws NoResponseException if there was no response from the remote entity.
763     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
764     */
765    public synchronized Presence leave()
766                    throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException, MucNotJoinedException {
767        //  Note that this method is intentionally not guarded by
768        // "if  (!joined) return" because it should be always be possible to leave the room in case the instance's
769        // state does not reflect the actual state.
770
771        final EntityFullJid myRoomJid = this.myRoomJid;
772        if (myRoomJid == null) {
773            throw new MucNotJoinedException(this);
774        }
775
776        // TODO: Consider adding a origin-id to the presence, once it is moved form smack-experimental into
777        // smack-extensions, in case the MUC service does not support stable IDs, and modify
778        // reflectedLeavePresenceFilters accordingly.
779
780        // We leave a room by sending a presence packet where the "to"
781        // field is in the form "roomName@service/nickname"
782        Presence leavePresence = connection.getStanzaFactory().buildPresenceStanza()
783                .ofType(Presence.Type.unavailable)
784                .to(myRoomJid)
785                .build();
786
787        List<StanzaFilter> reflectedLeavePresenceFilters = new ArrayList<>(3);
788        reflectedLeavePresenceFilters.add(StanzaTypeFilter.PRESENCE);
789        reflectedLeavePresenceFilters.add(new OrFilter(
790                        new AndFilter(FromMatchesFilter.createFull(myRoomJid), PresenceTypeFilter.UNAVAILABLE,
791                                        MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
792                        new AndFilter(fromRoomFilter, PresenceTypeFilter.ERROR)));
793
794        if (serviceSupportsStableIds()) {
795            reflectedLeavePresenceFilters.add(new StanzaIdFilter(leavePresence));
796        }
797
798        StanzaFilter reflectedLeavePresenceFilter = new AndFilter(reflectedLeavePresenceFilters);
799
800        Presence reflectedLeavePresence;
801        try {
802            reflectedLeavePresence = connection.createStanzaCollectorAndSend(reflectedLeavePresenceFilter, leavePresence).nextResultOrThrow();
803        } finally {
804            // Reset occupant information after we send the leave presence. This ensures that we only call userHasLeft()
805            // and reset the local MUC state after we successfully left the MUC (or if an exception occurred).
806            userHasLeft();
807        }
808
809        return reflectedLeavePresence;
810    }
811
812    /**
813     * Get a {@link MucConfigFormManager} to configure this room.
814     * <p>
815     * Only room owners are able to configure a room.
816     * </p>
817     *
818     * @return a MUC configuration form manager for this room.
819     * @throws NoResponseException if there was no response from the remote entity.
820     * @throws XMPPErrorException if there was an XMPP error returned.
821     * @throws NotConnectedException if the XMPP connection is not connected.
822     * @throws InterruptedException if the calling thread was interrupted.
823     * @see <a href="http://xmpp.org/extensions/xep-0045.html#roomconfig">XEP-45 § 10.2 Subsequent Room Configuration</a>
824     * @since 4.2
825     */
826    public MucConfigFormManager getConfigFormManager() throws NoResponseException,
827                    XMPPErrorException, NotConnectedException, InterruptedException {
828        return new MucConfigFormManager(this);
829    }
830
831    /**
832     * Returns the room's configuration form that the room's owner can use.
833     * The configuration form allows to set the room's language,
834     * enable logging, specify room's type, etc..
835     *
836     * @return the Form that contains the fields to complete together with the instrucions or
837     * <code>null</code> if no configuration is possible.
838     * @throws XMPPErrorException if an error occurs asking the configuration form for the room.
839     * @throws NoResponseException if there was no response from the server.
840     * @throws NotConnectedException if the XMPP connection is not connected.
841     * @throws InterruptedException if the calling thread was interrupted.
842     */
843    public Form getConfigurationForm() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
844        MUCOwner iq = new MUCOwner();
845        iq.setTo(room);
846        iq.setType(IQ.Type.get);
847
848        IQ answer = connection.sendIqRequestAndWaitForResponse(iq);
849        DataForm dataForm = DataForm.from(answer, MucConfigFormManager.FORM_TYPE);
850        return new Form(dataForm);
851    }
852
853    /**
854     * Sends the completed configuration form to the server. The room will be configured
855     * with the new settings defined in the form.
856     *
857     * @param form the form with the new settings.
858     * @throws XMPPErrorException if an error occurs setting the new rooms' configuration.
859     * @throws NoResponseException if there was no response from the server.
860     * @throws NotConnectedException if the XMPP connection is not connected.
861     * @throws InterruptedException if the calling thread was interrupted.
862     */
863    public void sendConfigurationForm(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
864        final DataForm dataForm;
865        if (form != null) {
866            dataForm = form.getDataFormToSubmit();
867        } else {
868            // Instant room, cf. XEP-0045 § 10.1.2
869            dataForm = DataForm.builder().build();
870        }
871
872        MUCOwner iq = new MUCOwner();
873        iq.setTo(room);
874        iq.setType(IQ.Type.set);
875        iq.addExtension(dataForm);
876
877        connection.sendIqRequestAndWaitForResponse(iq);
878    }
879
880    /**
881     * Returns the room's registration form that an unaffiliated user, can use to become a member
882     * of the room or <code>null</code> if no registration is possible. Some rooms may restrict the
883     * privilege to register members and allow only room admins to add new members.<p>
884     *
885     * If the user requesting registration requirements is not allowed to register with the room
886     * (e.g. because that privilege has been restricted), the room will return a "Not Allowed"
887     * error to the user (error code 405).
888     *
889     * @return the registration Form that contains the fields to complete together with the
890     * instrucions or <code>null</code> if no registration is possible.
891     * @throws XMPPErrorException if an error occurs asking the registration form for the room or a
892     * 405 error if the user is not allowed to register with the room.
893     * @throws NoResponseException if there was no response from the server.
894     * @throws NotConnectedException if the XMPP connection is not connected.
895     * @throws InterruptedException if the calling thread was interrupted.
896     */
897    public Form getRegistrationForm() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
898        Registration reg = new Registration();
899        reg.setType(IQ.Type.get);
900        reg.setTo(room);
901
902        IQ result = connection.sendIqRequestAndWaitForResponse(reg);
903        DataForm dataForm = DataForm.from(result);
904        return new Form(dataForm);
905    }
906
907    /**
908     * Sends the completed registration form to the server. After the user successfully submits
909     * the form, the room may queue the request for review by the room admins or may immediately
910     * add the user to the member list by changing the user's affiliation from "none" to "member.<p>
911     *
912     * If the desired room nickname is already reserved for that room, the room will return a
913     * "Conflict" error to the user (error code 409). If the room does not support registration,
914     * it will return a "Service Unavailable" error to the user (error code 503).
915     *
916     * @param form the completed registration form.
917     * @throws XMPPErrorException if an error occurs submitting the registration form. In particular, a
918     *      409 error can occur if the desired room nickname is already reserved for that room;
919     *      or a 503 error can occur if the room does not support registration.
920     * @throws NoResponseException if there was no response from the server.
921     * @throws NotConnectedException if the XMPP connection is not connected.
922     * @throws InterruptedException if the calling thread was interrupted.
923     */
924    public void sendRegistrationForm(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
925        Registration reg = new Registration();
926        reg.setType(IQ.Type.set);
927        reg.setTo(room);
928        reg.addExtension(form.getDataFormToSubmit());
929
930        connection.sendIqRequestAndWaitForResponse(reg);
931    }
932
933    /**
934     * Sends a request to destroy the room.
935     *
936     * @throws XMPPErrorException if an error occurs while trying to destroy the room.
937     *      An error can occur which will be wrapped by an XMPPException --
938     *      XMPP error code 403. The error code can be used to present more
939     *      appropriate error messages to end-users.
940     * @throws NoResponseException if there was no response from the server.
941     * @throws NotConnectedException if the XMPP connection is not connected.
942     * @throws InterruptedException if the calling thread was interrupted.
943     * @see #destroy(String, EntityBareJid)
944     * @since 4.5
945     */
946    public void destroy() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
947        destroy(null, null);
948    }
949
950    /**
951     * Sends a request to the server to destroy the room. The sender of the request
952     * should be the room's owner. If the sender of the destroy request is not the room's owner
953     * then the server will answer a "Forbidden" error (403).
954     *
955     * @param reason an optional reason for the room destruction.
956     * @param alternateJID an optional JID of an alternate location.
957     * @throws XMPPErrorException if an error occurs while trying to destroy the room.
958     *      An error can occur which will be wrapped by an XMPPException --
959     *      XMPP error code 403. The error code can be used to present more
960     *      appropriate error messages to end-users.
961     * @throws NoResponseException if there was no response from the server.
962     * @throws NotConnectedException if the XMPP connection is not connected.
963     * @throws InterruptedException if the calling thread was interrupted.
964     */
965    public void destroy(String reason, EntityBareJid alternateJID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
966        MUCOwner iq = new MUCOwner();
967        iq.setTo(room);
968        iq.setType(IQ.Type.set);
969
970        // Create the reason for the room destruction
971        Destroy destroy = new Destroy(alternateJID, reason);
972        iq.setDestroy(destroy);
973
974        try {
975            connection.sendIqRequestAndWaitForResponse(iq);
976        }
977        catch (XMPPErrorException e) {
978            // Note that we do not call userHasLeft() here because an XMPPErrorException would usually indicate that the
979            // room was not destroyed and we therefore we also did not leave the room.
980            throw e;
981        }
982        catch (NoResponseException | NotConnectedException | InterruptedException e) {
983            // Reset occupant information.
984            userHasLeft();
985            throw e;
986        }
987
988        // Reset occupant information.
989        userHasLeft();
990    }
991
992    /**
993     * Invites another user to the room in which one is an occupant. The invitation
994     * will be sent to the room which in turn will forward the invitation to the invitee.<p>
995     *
996     * If the room is password-protected, the invitee will receive a password to use to join
997     * the room. If the room is members-only, the the invitee may be added to the member list.
998     *
999     * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
1000     * @param reason the reason why the user is being invited.
1001     * @throws NotConnectedException if the XMPP connection is not connected.
1002     * @throws InterruptedException if the calling thread was interrupted.
1003     */
1004    public void invite(EntityBareJid user, String reason) throws NotConnectedException, InterruptedException {
1005        invite(connection.getStanzaFactory().buildMessageStanza(), user, reason);
1006    }
1007
1008    /**
1009     * Invites another user to the room in which one is an occupant using a given Message. The invitation
1010     * will be sent to the room which in turn will forward the invitation to the invitee.<p>
1011     *
1012     * If the room is password-protected, the invitee will receive a password to use to join
1013     * the room. If the room is members-only, the the invitee may be added to the member list.
1014     *
1015     * @param message the message to use for sending the invitation.
1016     * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
1017     * @param reason the reason why the user is being invited.
1018     * @throws NotConnectedException if the XMPP connection is not connected.
1019     * @throws InterruptedException if the calling thread was interrupted.
1020     * @deprecated use {@link #invite(MessageBuilder, EntityBareJid, String)} instead.
1021     */
1022    @Deprecated
1023    // TODO: Remove in Smack 4.5.
1024    public void invite(Message message, EntityBareJid user, String reason) throws NotConnectedException, InterruptedException {
1025        // TODO listen for 404 error code when inviter supplies a non-existent JID
1026        message.setTo(room);
1027
1028        // Create the MUCUser packet that will include the invitation
1029        MUCUser mucUser = new MUCUser();
1030        MUCUser.Invite invite = new MUCUser.Invite(reason, user);
1031        mucUser.setInvite(invite);
1032        // Add the MUCUser packet that includes the invitation to the message
1033        message.addExtension(mucUser);
1034
1035        connection.sendStanza(message);
1036    }
1037
1038    /**
1039     * Invites another user to the room in which one is an occupant using a given Message. The invitation
1040     * will be sent to the room which in turn will forward the invitation to the invitee.<p>
1041     *
1042     * If the room is password-protected, the invitee will receive a password to use to join
1043     * the room. If the room is members-only, the the invitee may be added to the member list.
1044     *
1045     * @param messageBuilder the message to use for sending the invitation.
1046     * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
1047     * @param reason the reason why the user is being invited.
1048     * @throws NotConnectedException if the XMPP connection is not connected.
1049     * @throws InterruptedException if the calling thread was interrupted.
1050     */
1051    public void invite(MessageBuilder messageBuilder, EntityBareJid user, String reason) throws NotConnectedException, InterruptedException {
1052        // TODO listen for 404 error code when inviter supplies a non-existent JID
1053        messageBuilder.to(room);
1054
1055        // Create the MUCUser packet that will include the invitation
1056        MUCUser mucUser = new MUCUser();
1057        MUCUser.Invite invite = new MUCUser.Invite(reason, user);
1058        mucUser.setInvite(invite);
1059        // Add the MUCUser packet that includes the invitation to the message
1060        messageBuilder.addExtension(mucUser);
1061
1062        Message message = messageBuilder.build();
1063        connection.sendStanza(message);
1064    }
1065
1066    /**
1067     * Adds a listener to invitation rejections notifications. The listener will be fired anytime
1068     * an invitation is declined.
1069     *
1070     * @param listener an invitation rejection listener.
1071     * @return true if the listener was not already added.
1072     */
1073    public boolean addInvitationRejectionListener(InvitationRejectionListener listener) {
1074         return invitationRejectionListeners.add(listener);
1075    }
1076
1077    /**
1078     * Removes a listener from invitation rejections notifications. The listener will be fired
1079     * anytime an invitation is declined.
1080     *
1081     * @param listener an invitation rejection listener.
1082     * @return true if the listener was registered and is now removed.
1083     */
1084    public boolean removeInvitationRejectionListener(InvitationRejectionListener listener) {
1085        return invitationRejectionListeners.remove(listener);
1086    }
1087
1088    /**
1089     * Fires invitation rejection listeners.
1090     *
1091     * @param message the message.
1092     * @param rejection the information about the rejection.
1093     */
1094    private void fireInvitationRejectionListeners(Message message, MUCUser.Decline rejection) {
1095        EntityBareJid invitee = rejection.getFrom();
1096        String reason = rejection.getReason();
1097        InvitationRejectionListener[] listeners;
1098        synchronized (invitationRejectionListeners) {
1099            listeners = new InvitationRejectionListener[invitationRejectionListeners.size()];
1100            invitationRejectionListeners.toArray(listeners);
1101        }
1102        for (InvitationRejectionListener listener : listeners) {
1103            listener.invitationDeclined(invitee, reason, message, rejection);
1104        }
1105    }
1106
1107    /**
1108     * Adds a listener to subject change notifications. The listener will be fired anytime
1109     * the room's subject changes.
1110     *
1111     * @param listener a subject updated listener.
1112     * @return true if the listener was not already added.
1113     */
1114    public boolean addSubjectUpdatedListener(SubjectUpdatedListener listener) {
1115        return subjectUpdatedListeners.add(listener);
1116    }
1117
1118    /**
1119     * Removes a listener from subject change notifications. The listener will be fired
1120     * anytime the room's subject changes.
1121     *
1122     * @param listener a subject updated listener.
1123     * @return true if the listener was registered and is now removed.
1124     */
1125    public boolean removeSubjectUpdatedListener(SubjectUpdatedListener listener) {
1126        return subjectUpdatedListeners.remove(listener);
1127    }
1128
1129    /**
1130     * Adds a new {@link StanzaListener} that will be invoked every time a new presence
1131     * is going to be sent by this MultiUserChat to the server. Stanza interceptors may
1132     * add new extensions to the presence that is going to be sent to the MUC service.
1133     *
1134     * @param presenceInterceptor the new stanza interceptor that will intercept presence packets.
1135     */
1136    public void addPresenceInterceptor(PresenceListener presenceInterceptor) {
1137        presenceInterceptors.add(presenceInterceptor);
1138    }
1139
1140    /**
1141     * Removes a {@link StanzaListener} that was being invoked every time a new presence
1142     * was being sent by this MultiUserChat to the server. Stanza interceptors may
1143     * add new extensions to the presence that is going to be sent to the MUC service.
1144     *
1145     * @param presenceInterceptor the stanza interceptor to remove.
1146     */
1147    public void removePresenceInterceptor(PresenceListener presenceInterceptor) {
1148        presenceInterceptors.remove(presenceInterceptor);
1149    }
1150
1151    /**
1152     * Returns the last known room's subject or <code>null</code> if the user hasn't joined the room
1153     * or the room does not have a subject yet. In case the room has a subject, as soon as the
1154     * user joins the room a message with the current room's subject will be received.<p>
1155     *
1156     * To be notified every time the room's subject change you should add a listener
1157     * to this room. {@link #addSubjectUpdatedListener(SubjectUpdatedListener)}<p>
1158     *
1159     * To change the room's subject use {@link #changeSubject(String)}.
1160     *
1161     * @return the room's subject or <code>null</code> if the user hasn't joined the room or the
1162     * room does not have a subject yet.
1163     */
1164    public String getSubject() {
1165        return subject;
1166    }
1167
1168    /**
1169     * Returns the reserved room nickname for the user in the room. A user may have a reserved
1170     * nickname, for example through explicit room registration or database integration. In such
1171     * cases it may be desirable for the user to discover the reserved nickname before attempting
1172     * to enter the room.
1173     *
1174     * @return the reserved room nickname or <code>null</code> if none.
1175     * @throws SmackException if there was no response from the server.
1176     * @throws InterruptedException if the calling thread was interrupted.
1177     */
1178    public String getReservedNickname() throws SmackException, InterruptedException {
1179        try {
1180            DiscoverInfo result =
1181                ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(
1182                    room,
1183                    "x-roomuser-item");
1184            // Look for an Identity that holds the reserved nickname and return its name
1185            for (DiscoverInfo.Identity identity : result.getIdentities()) {
1186                return identity.getName();
1187            }
1188        }
1189        catch (XMPPException e) {
1190            LOGGER.log(Level.SEVERE, "Error retrieving room nickname", e);
1191        }
1192        // If no Identity was found then the user does not have a reserved room nickname
1193        return null;
1194    }
1195
1196    /**
1197     * Returns the nickname that was used to join the room, or <code>null</code> if not
1198     * currently joined.
1199     *
1200     * @return the nickname currently being used.
1201     */
1202    public Resourcepart getNickname() {
1203        final EntityFullJid myRoomJid = this.myRoomJid;
1204        if (myRoomJid == null) {
1205            return null;
1206        }
1207        return myRoomJid.getResourcepart();
1208    }
1209
1210    /**
1211     * Changes the occupant's nickname to a new nickname within the room. Each room occupant
1212     * will receive two presence packets. One of type "unavailable" for the old nickname and one
1213     * indicating availability for the new nickname. The unavailable presence will contain the new
1214     * nickname and an appropriate status code (namely 303) as extended presence information. The
1215     * status code 303 indicates that the occupant is changing his/her nickname.
1216     *
1217     * @param nickname the new nickname within the room.
1218     * @throws XMPPErrorException if the new nickname is already in use by another occupant.
1219     * @throws NoResponseException if there was no response from the server.
1220     * @throws NotConnectedException if the XMPP connection is not connected.
1221     * @throws InterruptedException if the calling thread was interrupted.
1222     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
1223     */
1224    public synchronized void changeNickname(Resourcepart nickname) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, MucNotJoinedException  {
1225        Objects.requireNonNull(nickname, "Nickname must not be null or blank.");
1226        // Check that we already have joined the room before attempting to change the
1227        // nickname.
1228        if (!isJoined()) {
1229            throw new MucNotJoinedException(this);
1230        }
1231        final EntityFullJid jid = JidCreate.entityFullFrom(room, nickname);
1232        // We change the nickname by sending a presence packet where the "to"
1233        // field is in the form "roomName@service/nickname"
1234        // We don't have to signal the MUC support again
1235        Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza()
1236                .to(jid)
1237                .ofType(Presence.Type.available)
1238                .build();
1239
1240        // Wait for a presence packet back from the server.
1241        StanzaFilter responseFilter =
1242            new AndFilter(
1243                FromMatchesFilter.createFull(jid),
1244                new StanzaTypeFilter(Presence.class));
1245        StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
1246        // Wait up to a certain number of seconds for a reply. If there is a negative reply, an
1247        // exception will be thrown
1248        response.nextResultOrThrow();
1249
1250        // TODO: Shouldn't this handle nickname rewriting by the MUC service?
1251        setNickname(nickname);
1252    }
1253
1254    /**
1255     * Changes the occupant's availability status within the room. The presence type
1256     * will remain available but with a new status that describes the presence update and
1257     * a new presence mode (e.g. Extended away).
1258     *
1259     * @param status a text message describing the presence update.
1260     * @param mode the mode type for the presence update.
1261     * @throws NotConnectedException if the XMPP connection is not connected.
1262     * @throws InterruptedException if the calling thread was interrupted.
1263     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
1264     */
1265    public void changeAvailabilityStatus(String status, Presence.Mode mode) throws NotConnectedException, InterruptedException, MucNotJoinedException {
1266        final EntityFullJid myRoomJid = this.myRoomJid;
1267        if (myRoomJid == null) {
1268            throw new MucNotJoinedException(this);
1269        }
1270
1271        // We change the availability status by sending a presence packet to the room with the
1272        // new presence status and mode
1273        Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza()
1274                .to(myRoomJid)
1275                .ofType(Presence.Type.available)
1276                .setStatus(status)
1277                .setMode(mode)
1278                .build();
1279
1280        // Send join packet.
1281        connection.sendStanza(joinPresence);
1282    }
1283
1284    /**
1285     * Kicks a visitor or participant from the room. The kicked occupant will receive a presence
1286     * of type "unavailable" including a status code 307 and optionally along with the reason
1287     * (if provided) and the bare JID of the user who initiated the kick. After the occupant
1288     * was kicked from the room, the rest of the occupants will receive a presence of type
1289     * "unavailable". The presence will include a status code 307 which means that the occupant
1290     * was kicked from the room.
1291     *
1292     * @param nickname the nickname of the participant or visitor to kick from the room
1293     * (e.g. "john").
1294     * @param reason the reason why the participant or visitor is being kicked from the room.
1295     * @throws XMPPErrorException if an error occurs kicking the occupant. In particular, a
1296     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1297     *      was intended to be kicked (i.e. Not Allowed error); or a
1298     *      403 error can occur if the occupant that intended to kick another occupant does
1299     *      not have kicking privileges (i.e. Forbidden error); or a
1300     *      400 error can occur if the provided nickname is not present in the room.
1301     * @throws NoResponseException if there was no response from the server.
1302     * @throws NotConnectedException if the XMPP connection is not connected.
1303     * @throws InterruptedException if the calling thread was interrupted.
1304     */
1305    public void kickParticipant(Resourcepart nickname, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1306        changeRole(nickname, MUCRole.none, reason);
1307    }
1308
1309    /**
1310     * Sends a voice request to the MUC. The room moderators usually need to approve this request.
1311     *
1312     * @throws NotConnectedException if the XMPP connection is not connected.
1313     * @throws InterruptedException if the calling thread was interrupted.
1314     * @see <a href="http://xmpp.org/extensions/xep-0045.html#requestvoice">XEP-45 § 7.13 Requesting
1315     *      Voice</a>
1316     * @since 4.1
1317     */
1318    public void requestVoice() throws NotConnectedException, InterruptedException {
1319        DataForm.Builder form = DataForm.builder()
1320                        .setFormType(MUCInitialPresence.NAMESPACE + "#request");
1321
1322        TextSingleFormField.Builder requestVoiceField = FormField.textSingleBuilder("muc#role");
1323        requestVoiceField.setLabel("Requested role");
1324        requestVoiceField.setValue("participant");
1325        form.addField(requestVoiceField.build());
1326
1327        Message message = connection.getStanzaFactory().buildMessageStanza()
1328                .to(room)
1329                .addExtension(form.build())
1330                .build();
1331        connection.sendStanza(message);
1332    }
1333
1334    /**
1335     * Grants voice to visitors in the room. In a moderated room, a moderator may want to manage
1336     * who does and does not have "voice" in the room. To have voice means that a room occupant
1337     * is able to send messages to the room occupants.
1338     *
1339     * @param nicknames the nicknames of the visitors to grant voice in the room (e.g. "john").
1340     * @throws XMPPErrorException if an error occurs granting voice to a visitor. In particular, a
1341     *      403 error can occur if the occupant that intended to grant voice is not
1342     *      a moderator in this room (i.e. Forbidden error); or a
1343     *      400 error can occur if the provided nickname is not present in the room.
1344     * @throws NoResponseException if there was no response from the server.
1345     * @throws NotConnectedException if the XMPP connection is not connected.
1346     * @throws InterruptedException if the calling thread was interrupted.
1347     */
1348    public void grantVoice(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1349        changeRole(nicknames, MUCRole.participant);
1350    }
1351
1352    /**
1353     * Grants voice to a visitor in the room. In a moderated room, a moderator may want to manage
1354     * who does and does not have "voice" in the room. To have voice means that a room occupant
1355     * is able to send messages to the room occupants.
1356     *
1357     * @param nickname the nickname of the visitor to grant voice in the room (e.g. "john").
1358     * @throws XMPPErrorException if an error occurs granting voice to a visitor. In particular, a
1359     *      403 error can occur if the occupant that intended to grant voice is not
1360     *      a moderator in this room (i.e. Forbidden error); or a
1361     *      400 error can occur if the provided nickname is not present in the room.
1362     * @throws NoResponseException if there was no response from the server.
1363     * @throws NotConnectedException if the XMPP connection is not connected.
1364     * @throws InterruptedException if the calling thread was interrupted.
1365     */
1366    public void grantVoice(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1367        changeRole(nickname, MUCRole.participant, null);
1368    }
1369
1370    /**
1371     * Revokes voice from participants in the room. In a moderated room, a moderator may want to
1372     * revoke an occupant's privileges to speak. To have voice means that a room occupant
1373     * is able to send messages to the room occupants.
1374     *
1375     * @param nicknames the nicknames of the participants to revoke voice (e.g. "john").
1376     * @throws XMPPErrorException if an error occurs revoking voice from a participant. In particular, a
1377     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1378     *      was tried to revoke his voice (i.e. Not Allowed error); or a
1379     *      400 error can occur if the provided nickname is not present in the room.
1380     * @throws NoResponseException if there was no response from the server.
1381     * @throws NotConnectedException if the XMPP connection is not connected.
1382     * @throws InterruptedException if the calling thread was interrupted.
1383     */
1384    public void revokeVoice(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1385        changeRole(nicknames, MUCRole.visitor);
1386    }
1387
1388    /**
1389     * Revokes voice from a participant in the room. In a moderated room, a moderator may want to
1390     * revoke an occupant's privileges to speak. To have voice means that a room occupant
1391     * is able to send messages to the room occupants.
1392     *
1393     * @param nickname the nickname of the participant to revoke voice (e.g. "john").
1394     * @throws XMPPErrorException if an error occurs revoking voice from a participant. In particular, a
1395     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1396     *      was tried to revoke his voice (i.e. Not Allowed error); or a
1397     *      400 error can occur if the provided nickname is not present in the room.
1398     * @throws NoResponseException if there was no response from the server.
1399     * @throws NotConnectedException if the XMPP connection is not connected.
1400     * @throws InterruptedException if the calling thread was interrupted.
1401     */
1402    public void revokeVoice(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1403        changeRole(nickname, MUCRole.visitor, null);
1404    }
1405
1406    /**
1407     * Bans users from the room. An admin or owner of the room can ban users from a room. This
1408     * means that the banned user will no longer be able to join the room unless the ban has been
1409     * removed. If the banned user was present in the room then he/she will be removed from the
1410     * room and notified that he/she was banned along with the reason (if provided) and the bare
1411     * XMPP user ID of the user who initiated the ban.
1412     *
1413     * @param jids the bare XMPP user IDs of the users to ban.
1414     * @throws XMPPErrorException if an error occurs banning a user. In particular, a
1415     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1416     *      was tried to be banned (i.e. Not Allowed error).
1417     * @throws NoResponseException if there was no response from the server.
1418     * @throws NotConnectedException if the XMPP connection is not connected.
1419     * @throws InterruptedException if the calling thread was interrupted.
1420     */
1421    public void banUsers(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1422        changeAffiliationByAdmin(jids, MUCAffiliation.outcast);
1423    }
1424
1425    /**
1426     * Bans a user from the room. An admin or owner of the room can ban users from a room. This
1427     * means that the banned user will no longer be able to join the room unless the ban has been
1428     * removed. If the banned user was present in the room then he/she will be removed from the
1429     * room and notified that he/she was banned along with the reason (if provided) and the bare
1430     * XMPP user ID of the user who initiated the ban.
1431     *
1432     * @param jid the bare XMPP user ID of the user to ban (e.g. "user@host.org").
1433     * @param reason the optional reason why the user was banned.
1434     * @throws XMPPErrorException if an error occurs banning a user. In particular, a
1435     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1436     *      was tried to be banned (i.e. Not Allowed error).
1437     * @throws NoResponseException if there was no response from the server.
1438     * @throws NotConnectedException if the XMPP connection is not connected.
1439     * @throws InterruptedException if the calling thread was interrupted.
1440     */
1441    public void banUser(Jid jid, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1442        changeAffiliationByAdmin(jid, MUCAffiliation.outcast, reason);
1443    }
1444
1445    /**
1446     * Grants membership to other users. Only administrators are able to grant membership. A user
1447     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1448     * that a user cannot enter without being on the member list).
1449     *
1450     * @param jids the XMPP user IDs of the users to grant membership.
1451     * @throws XMPPErrorException if an error occurs granting membership to a user.
1452     * @throws NoResponseException if there was no response from the server.
1453     * @throws NotConnectedException if the XMPP connection is not connected.
1454     * @throws InterruptedException if the calling thread was interrupted.
1455     */
1456    public void grantMembership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1457        changeAffiliationByAdmin(jids, MUCAffiliation.member);
1458    }
1459
1460    /**
1461     * Grants membership to a user. Only administrators are able to grant membership. A user
1462     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1463     * that a user cannot enter without being on the member list).
1464     *
1465     * @param jid the XMPP user ID of the user to grant membership (e.g. "user@host.org").
1466     * @throws XMPPErrorException if an error occurs granting membership to a user.
1467     * @throws NoResponseException if there was no response from the server.
1468     * @throws NotConnectedException if the XMPP connection is not connected.
1469     * @throws InterruptedException if the calling thread was interrupted.
1470     */
1471    public void grantMembership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1472        changeAffiliationByAdmin(jid, MUCAffiliation.member, null);
1473    }
1474
1475    /**
1476     * Revokes users' membership. Only administrators are able to revoke membership. A user
1477     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1478     * that a user cannot enter without being on the member list). If the user is in the room and
1479     * the room is of type members-only then the user will be removed from the room.
1480     *
1481     * @param jids the bare XMPP user IDs of the users to revoke membership.
1482     * @throws XMPPErrorException if an error occurs revoking membership to a user.
1483     * @throws NoResponseException if there was no response from the server.
1484     * @throws NotConnectedException if the XMPP connection is not connected.
1485     * @throws InterruptedException if the calling thread was interrupted.
1486     */
1487    public void revokeMembership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1488        changeAffiliationByAdmin(jids, MUCAffiliation.none);
1489    }
1490
1491    /**
1492     * Revokes a user's membership. Only administrators are able to revoke membership. A user
1493     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1494     * that a user cannot enter without being on the member list). If the user is in the room and
1495     * the room is of type members-only then the user will be removed from the room.
1496     *
1497     * @param jid the bare XMPP user ID of the user to revoke membership (e.g. "user@host.org").
1498     * @throws XMPPErrorException if an error occurs revoking membership to a user.
1499     * @throws NoResponseException if there was no response from the server.
1500     * @throws NotConnectedException if the XMPP connection is not connected.
1501     * @throws InterruptedException if the calling thread was interrupted.
1502     */
1503    public void revokeMembership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1504        changeAffiliationByAdmin(jid, MUCAffiliation.none, null);
1505    }
1506
1507    /**
1508     * Grants moderator privileges to participants or visitors. Room administrators may grant
1509     * moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite
1510     * other users, modify room's subject plus all the partcipants privileges.
1511     *
1512     * @param nicknames the nicknames of the occupants to grant moderator privileges.
1513     * @throws XMPPErrorException if an error occurs granting moderator privileges to a user.
1514     * @throws NoResponseException if there was no response from the server.
1515     * @throws NotConnectedException if the XMPP connection is not connected.
1516     * @throws InterruptedException if the calling thread was interrupted.
1517     */
1518    public void grantModerator(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1519        changeRole(nicknames, MUCRole.moderator);
1520    }
1521
1522    /**
1523     * Grants moderator privileges to a participant or visitor. Room administrators may grant
1524     * moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite
1525     * other users, modify room's subject plus all the partcipants privileges.
1526     *
1527     * @param nickname the nickname of the occupant to grant moderator privileges.
1528     * @throws XMPPErrorException if an error occurs granting moderator privileges to a user.
1529     * @throws NoResponseException if there was no response from the server.
1530     * @throws NotConnectedException if the XMPP connection is not connected.
1531     * @throws InterruptedException if the calling thread was interrupted.
1532     */
1533    public void grantModerator(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1534        changeRole(nickname, MUCRole.moderator, null);
1535    }
1536
1537    /**
1538     * Revokes moderator privileges from other users. The occupant that loses moderator
1539     * privileges will become a participant. Room administrators may revoke moderator privileges
1540     * only to occupants whose affiliation is member or none. This means that an administrator is
1541     * not allowed to revoke moderator privileges from other room administrators or owners.
1542     *
1543     * @param nicknames the nicknames of the occupants to revoke moderator privileges.
1544     * @throws XMPPErrorException if an error occurs revoking moderator privileges from a user.
1545     * @throws NoResponseException if there was no response from the server.
1546     * @throws NotConnectedException if the XMPP connection is not connected.
1547     * @throws InterruptedException if the calling thread was interrupted.
1548     */
1549    public void revokeModerator(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1550        changeRole(nicknames, MUCRole.participant);
1551    }
1552
1553    /**
1554     * Revokes moderator privileges from another user. The occupant that loses moderator
1555     * privileges will become a participant. Room administrators may revoke moderator privileges
1556     * only to occupants whose affiliation is member or none. This means that an administrator is
1557     * not allowed to revoke moderator privileges from other room administrators or owners.
1558     *
1559     * @param nickname the nickname of the occupant to revoke moderator privileges.
1560     * @throws XMPPErrorException if an error occurs revoking moderator privileges from a user.
1561     * @throws NoResponseException if there was no response from the server.
1562     * @throws NotConnectedException if the XMPP connection is not connected.
1563     * @throws InterruptedException if the calling thread was interrupted.
1564     */
1565    public void revokeModerator(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1566        changeRole(nickname, MUCRole.participant, null);
1567    }
1568
1569    /**
1570     * Grants ownership privileges to other users. Room owners may grant ownership privileges.
1571     * Some room implementations will not allow to grant ownership privileges to other users.
1572     * An owner is allowed to change defining room features as well as perform all administrative
1573     * functions.
1574     *
1575     * @param jids the collection of bare XMPP user IDs of the users to grant ownership.
1576     * @throws XMPPErrorException if an error occurs granting ownership privileges to a user.
1577     * @throws NoResponseException if there was no response from the server.
1578     * @throws NotConnectedException if the XMPP connection is not connected.
1579     * @throws InterruptedException if the calling thread was interrupted.
1580     */
1581    public void grantOwnership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1582        changeAffiliationByAdmin(jids, MUCAffiliation.owner);
1583    }
1584
1585    /**
1586     * Grants ownership privileges to another user. Room owners may grant ownership privileges.
1587     * Some room implementations will not allow to grant ownership privileges to other users.
1588     * An owner is allowed to change defining room features as well as perform all administrative
1589     * functions.
1590     *
1591     * @param jid the bare XMPP user ID of the user to grant ownership (e.g. "user@host.org").
1592     * @throws XMPPErrorException if an error occurs granting ownership privileges to a user.
1593     * @throws NoResponseException if there was no response from the server.
1594     * @throws NotConnectedException if the XMPP connection is not connected.
1595     * @throws InterruptedException if the calling thread was interrupted.
1596     */
1597    public void grantOwnership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1598        changeAffiliationByAdmin(jid, MUCAffiliation.owner, null);
1599    }
1600
1601    /**
1602     * Revokes ownership privileges from other users. The occupant that loses ownership
1603     * privileges will become an administrator. Room owners may revoke ownership privileges.
1604     * Some room implementations will not allow to grant ownership privileges to other users.
1605     *
1606     * @param jids the bare XMPP user IDs of the users to revoke ownership.
1607     * @throws XMPPErrorException if an error occurs revoking ownership privileges from a user.
1608     * @throws NoResponseException if there was no response from the server.
1609     * @throws NotConnectedException if the XMPP connection is not connected.
1610     * @throws InterruptedException if the calling thread was interrupted.
1611     */
1612    public void revokeOwnership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1613        changeAffiliationByAdmin(jids, MUCAffiliation.admin);
1614    }
1615
1616    /**
1617     * Revokes ownership privileges from another user. The occupant that loses ownership
1618     * privileges will become an administrator. Room owners may revoke ownership privileges.
1619     * Some room implementations will not allow to grant ownership privileges to other users.
1620     *
1621     * @param jid the bare XMPP user ID of the user to revoke ownership (e.g. "user@host.org").
1622     * @throws XMPPErrorException if an error occurs revoking ownership privileges from a user.
1623     * @throws NoResponseException if there was no response from the server.
1624     * @throws NotConnectedException if the XMPP connection is not connected.
1625     * @throws InterruptedException if the calling thread was interrupted.
1626     */
1627    public void revokeOwnership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1628        changeAffiliationByAdmin(jid, MUCAffiliation.admin, null);
1629    }
1630
1631    /**
1632     * Grants administrator privileges to other users. Room owners may grant administrator
1633     * privileges to a member or unaffiliated user. An administrator is allowed to perform
1634     * administrative functions such as banning users and edit moderator list.
1635     *
1636     * @param jids the bare XMPP user IDs of the users to grant administrator privileges.
1637     * @throws XMPPErrorException if an error occurs granting administrator privileges to a user.
1638     * @throws NoResponseException if there was no response from the server.
1639     * @throws NotConnectedException if the XMPP connection is not connected.
1640     * @throws InterruptedException if the calling thread was interrupted.
1641     */
1642    public void grantAdmin(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1643        changeAffiliationByAdmin(jids, MUCAffiliation.admin);
1644    }
1645
1646    /**
1647     * Grants administrator privileges to another user. Room owners may grant administrator
1648     * privileges to a member or unaffiliated user. An administrator is allowed to perform
1649     * administrative functions such as banning users and edit moderator list.
1650     *
1651     * @param jid the bare XMPP user ID of the user to grant administrator privileges
1652     * (e.g. "user@host.org").
1653     * @throws XMPPErrorException if an error occurs granting administrator privileges to a user.
1654     * @throws NoResponseException if there was no response from the server.
1655     * @throws NotConnectedException if the XMPP connection is not connected.
1656     * @throws InterruptedException if the calling thread was interrupted.
1657     */
1658    public void grantAdmin(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1659        changeAffiliationByAdmin(jid, MUCAffiliation.admin);
1660    }
1661
1662    /**
1663     * Revokes administrator privileges from users. The occupant that loses administrator
1664     * privileges will become a member. Room owners may revoke administrator privileges from
1665     * a member or unaffiliated user.
1666     *
1667     * @param jids the bare XMPP user IDs of the user to revoke administrator privileges.
1668     * @throws XMPPErrorException if an error occurs revoking administrator privileges from a user.
1669     * @throws NoResponseException if there was no response from the server.
1670     * @throws NotConnectedException if the XMPP connection is not connected.
1671     * @throws InterruptedException if the calling thread was interrupted.
1672     */
1673    public void revokeAdmin(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1674        changeAffiliationByAdmin(jids, MUCAffiliation.admin);
1675    }
1676
1677    /**
1678     * Revokes administrator privileges from a user. The occupant that loses administrator
1679     * privileges will become a member. Room owners may revoke administrator privileges from
1680     * a member or unaffiliated user.
1681     *
1682     * @param jid the bare XMPP user ID of the user to revoke administrator privileges
1683     * (e.g. "user@host.org").
1684     * @throws XMPPErrorException if an error occurs revoking administrator privileges from a user.
1685     * @throws NoResponseException if there was no response from the server.
1686     * @throws NotConnectedException if the XMPP connection is not connected.
1687     * @throws InterruptedException if the calling thread was interrupted.
1688     */
1689    public void revokeAdmin(EntityJid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1690        changeAffiliationByAdmin(jid, MUCAffiliation.member);
1691    }
1692
1693    /**
1694     * Tries to change the affiliation with an 'muc#admin' namespace
1695     *
1696     * @param jid TODO javadoc me please
1697     * @param affiliation TODO javadoc me please
1698     * @throws XMPPErrorException if there was an XMPP error returned.
1699     * @throws NoResponseException if there was no response from the remote entity.
1700     * @throws NotConnectedException if the XMPP connection is not connected.
1701     * @throws InterruptedException if the calling thread was interrupted.
1702     */
1703    private void changeAffiliationByAdmin(Jid jid, MUCAffiliation affiliation)
1704                    throws NoResponseException, XMPPErrorException,
1705                    NotConnectedException, InterruptedException {
1706        changeAffiliationByAdmin(jid, affiliation, null);
1707    }
1708
1709    /**
1710     * Tries to change the affiliation with an 'muc#admin' namespace
1711     *
1712     * @param jid TODO javadoc me please
1713     * @param affiliation TODO javadoc me please
1714     * @param reason the reason for the affiliation change (optional)
1715     * @throws XMPPErrorException if there was an XMPP error returned.
1716     * @throws NoResponseException if there was no response from the remote entity.
1717     * @throws NotConnectedException if the XMPP connection is not connected.
1718     * @throws InterruptedException if the calling thread was interrupted.
1719     */
1720    private void changeAffiliationByAdmin(Jid jid, MUCAffiliation affiliation, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1721        MUCAdmin iq = new MUCAdmin();
1722        iq.setTo(room);
1723        iq.setType(IQ.Type.set);
1724        // Set the new affiliation.
1725        MUCItem item = new MUCItem(affiliation, jid, reason);
1726        iq.addItem(item);
1727
1728        connection.sendIqRequestAndWaitForResponse(iq);
1729    }
1730
1731    private void changeAffiliationByAdmin(Collection<? extends Jid> jids, MUCAffiliation affiliation)
1732                    throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1733        MUCAdmin iq = new MUCAdmin();
1734        iq.setTo(room);
1735        iq.setType(IQ.Type.set);
1736        for (Jid jid : jids) {
1737            // Set the new affiliation.
1738            MUCItem item = new MUCItem(affiliation, jid);
1739            iq.addItem(item);
1740        }
1741
1742        connection.sendIqRequestAndWaitForResponse(iq);
1743    }
1744
1745    private void changeRole(Resourcepart nickname, MUCRole role, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1746        MUCAdmin iq = new MUCAdmin();
1747        iq.setTo(room);
1748        iq.setType(IQ.Type.set);
1749        // Set the new role.
1750        MUCItem item = new MUCItem(role, nickname, reason);
1751        iq.addItem(item);
1752
1753        connection.sendIqRequestAndWaitForResponse(iq);
1754    }
1755
1756    private void changeRole(Collection<Resourcepart> nicknames, MUCRole role) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException  {
1757        MUCAdmin iq = new MUCAdmin();
1758        iq.setTo(room);
1759        iq.setType(IQ.Type.set);
1760        for (Resourcepart nickname : nicknames) {
1761            // Set the new role.
1762            MUCItem item = new MUCItem(role, nickname);
1763            iq.addItem(item);
1764        }
1765
1766        connection.sendIqRequestAndWaitForResponse(iq);
1767    }
1768
1769    /**
1770     * Returns the number of occupants in the group chat.<p>
1771     *
1772     * Note: this value will only be accurate after joining the group chat, and
1773     * may fluctuate over time. If you query this value directly after joining the
1774     * group chat it may not be accurate, as it takes a certain amount of time for
1775     * the server to send all presence packets to this client.
1776     *
1777     * @return the number of occupants in the group chat.
1778     */
1779    public int getOccupantsCount() {
1780        return occupantsMap.size();
1781    }
1782
1783    /**
1784     * Returns an List  for the list of fully qualified occupants
1785     * in the group chat. For example, "conference@chat.jivesoftware.com/SomeUser".
1786     * Typically, a client would only display the nickname of the occupant. To
1787     * get the nickname from the fully qualified name, use the
1788     * {@link org.jxmpp.util.XmppStringUtils#parseResource(String)} method.
1789     * Note: this value will only be accurate after joining the group chat, and may
1790     * fluctuate over time.
1791     *
1792     * @return a List of the occupants in the group chat.
1793     */
1794    public List<EntityFullJid> getOccupants() {
1795        return new ArrayList<>(occupantsMap.keySet());
1796    }
1797
1798    /**
1799     * Returns the presence info for a particular user, or <code>null</code> if the user
1800     * is not in the room.<p>
1801     *
1802     * @param user the room occupant to search for his presence. The format of user must
1803     * be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch).
1804     * @return the occupant's current presence, or <code>null</code> if the user is unavailable
1805     *      or if no presence information is available.
1806     */
1807    public Presence getOccupantPresence(EntityFullJid user) {
1808        return occupantsMap.get(user);
1809    }
1810
1811    /**
1812     * Returns the Occupant information for a particular occupant, or <code>null</code> if the
1813     * user is not in the room. The Occupant object may include information such as full
1814     * JID of the user as well as the role and affiliation of the user in the room.<p>
1815     *
1816     * @param user the room occupant to search for his presence. The format of user must
1817     * be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch).
1818     * @return the Occupant or <code>null</code> if the user is unavailable (i.e. not in the room).
1819     */
1820    public Occupant getOccupant(EntityFullJid user) {
1821        Presence presence = getOccupantPresence(user);
1822        if (presence != null) {
1823            return new Occupant(presence);
1824        }
1825        return null;
1826    }
1827
1828    /**
1829     * Adds a stanza listener that will be notified of any new Presence packets
1830     * sent to the group chat. Using a listener is a suitable way to know when the list
1831     * of occupants should be re-loaded due to any changes.
1832     *
1833     * @param listener a stanza listener that will be notified of any presence packets
1834     *      sent to the group chat.
1835     * @return true if the listener was not already added.
1836     */
1837    public boolean addParticipantListener(PresenceListener listener) {
1838        return presenceListeners.add(listener);
1839    }
1840
1841    /**
1842     * Removes a stanza listener that was being notified of any new Presence packets
1843     * sent to the group chat.
1844     *
1845     * @param listener a stanza listener that was being notified of any presence packets
1846     *      sent to the group chat.
1847     * @return true if the listener was removed, otherwise the listener was not added previously.
1848     */
1849    public boolean removeParticipantListener(PresenceListener listener) {
1850        return presenceListeners.remove(listener);
1851    }
1852
1853    /**
1854     * Returns a list of <code>Affiliate</code> with the room owners.
1855     *
1856     * @return a list of <code>Affiliate</code> with the room owners.
1857     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1858     * @throws NoResponseException if there was no response from the server.
1859     * @throws NotConnectedException if the XMPP connection is not connected.
1860     * @throws InterruptedException if the calling thread was interrupted.
1861     */
1862    public List<Affiliate> getOwners() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1863        return getAffiliatesByAdmin(MUCAffiliation.owner);
1864    }
1865
1866    /**
1867     * Returns a list of <code>Affiliate</code> with the room administrators.
1868     *
1869     * @return a list of <code>Affiliate</code> with the room administrators.
1870     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1871     * @throws NoResponseException if there was no response from the server.
1872     * @throws NotConnectedException if the XMPP connection is not connected.
1873     * @throws InterruptedException if the calling thread was interrupted.
1874     */
1875    public List<Affiliate> getAdmins() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1876        return getAffiliatesByAdmin(MUCAffiliation.admin);
1877    }
1878
1879    /**
1880     * Returns a list of <code>Affiliate</code> with the room members.
1881     *
1882     * @return a list of <code>Affiliate</code> with the room members.
1883     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1884     * @throws NoResponseException if there was no response from the server.
1885     * @throws NotConnectedException if the XMPP connection is not connected.
1886     * @throws InterruptedException if the calling thread was interrupted.
1887     */
1888    public List<Affiliate> getMembers() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException  {
1889        return getAffiliatesByAdmin(MUCAffiliation.member);
1890    }
1891
1892    /**
1893     * Returns a list of <code>Affiliate</code> with the room outcasts.
1894     *
1895     * @return a list of <code>Affiliate</code> with the room outcasts.
1896     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1897     * @throws NoResponseException if there was no response from the server.
1898     * @throws NotConnectedException if the XMPP connection is not connected.
1899     * @throws InterruptedException if the calling thread was interrupted.
1900     */
1901    public List<Affiliate> getOutcasts() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1902        return getAffiliatesByAdmin(MUCAffiliation.outcast);
1903    }
1904
1905    /**
1906     * Returns a collection of <code>Affiliate</code> that have the specified room affiliation
1907     * sending a request in the admin namespace.
1908     *
1909     * @param affiliation the affiliation of the users in the room.
1910     * @return a collection of <code>Affiliate</code> that have the specified room affiliation.
1911     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1912     * @throws NoResponseException if there was no response from the server.
1913     * @throws NotConnectedException if the XMPP connection is not connected.
1914     * @throws InterruptedException if the calling thread was interrupted.
1915     */
1916    private List<Affiliate> getAffiliatesByAdmin(MUCAffiliation affiliation) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1917        MUCAdmin iq = new MUCAdmin();
1918        iq.setTo(room);
1919        iq.setType(IQ.Type.get);
1920        // Set the specified affiliation. This may request the list of owners/admins/members/outcasts.
1921        MUCItem item = new MUCItem(affiliation);
1922        iq.addItem(item);
1923
1924        MUCAdmin answer = (MUCAdmin) connection.sendIqRequestAndWaitForResponse(iq);
1925
1926        // Get the list of affiliates from the server's answer
1927        List<Affiliate> affiliates = new ArrayList<Affiliate>();
1928        for (MUCItem mucadminItem : answer.getItems()) {
1929            affiliates.add(new Affiliate(mucadminItem));
1930        }
1931        return affiliates;
1932    }
1933
1934    /**
1935     * Returns a list of <code>Occupant</code> with the room moderators.
1936     *
1937     * @return a list of <code>Occupant</code> with the room moderators.
1938     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1939     * @throws NoResponseException if there was no response from the server.
1940     * @throws NotConnectedException if the XMPP connection is not connected.
1941     * @throws InterruptedException if the calling thread was interrupted.
1942     */
1943    public List<Occupant> getModerators() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1944        return getOccupants(MUCRole.moderator);
1945    }
1946
1947    /**
1948     * Returns a list of <code>Occupant</code> with the room participants.
1949     *
1950     * @return a list of <code>Occupant</code> with the room participants.
1951     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1952     * @throws NoResponseException if there was no response from the server.
1953     * @throws NotConnectedException if the XMPP connection is not connected.
1954     * @throws InterruptedException if the calling thread was interrupted.
1955     */
1956    public List<Occupant> getParticipants() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1957        return getOccupants(MUCRole.participant);
1958    }
1959
1960    /**
1961     * Returns a list of <code>Occupant</code> that have the specified room role.
1962     *
1963     * @param role the role of the occupant in the room.
1964     * @return a list of <code>Occupant</code> that have the specified room role.
1965     * @throws XMPPErrorException if an error occurred while performing the request to the server or you
1966     *         don't have enough privileges to get this information.
1967     * @throws NoResponseException if there was no response from the server.
1968     * @throws NotConnectedException if the XMPP connection is not connected.
1969     * @throws InterruptedException if the calling thread was interrupted.
1970     */
1971    private List<Occupant> getOccupants(MUCRole role) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1972        MUCAdmin iq = new MUCAdmin();
1973        iq.setTo(room);
1974        iq.setType(IQ.Type.get);
1975        // Set the specified role. This may request the list of moderators/participants.
1976        MUCItem item = new MUCItem(role);
1977        iq.addItem(item);
1978
1979        MUCAdmin answer = (MUCAdmin) connection.sendIqRequestAndWaitForResponse(iq);
1980        // Get the list of participants from the server's answer
1981        List<Occupant> participants = new ArrayList<Occupant>();
1982        for (MUCItem mucadminItem : answer.getItems()) {
1983            participants.add(new Occupant(mucadminItem));
1984        }
1985        return participants;
1986    }
1987
1988    /**
1989     * Sends a message to the chat room.
1990     *
1991     * @param text the text of the message to send.
1992     * @throws NotConnectedException if the XMPP connection is not connected.
1993     * @throws InterruptedException if the calling thread was interrupted.
1994     */
1995    public void sendMessage(String text) throws NotConnectedException, InterruptedException {
1996        Message message = buildMessage()
1997                .setBody(text)
1998                .build();
1999        connection.sendStanza(message);
2000    }
2001
2002    /**
2003     * Returns a new Chat for sending private messages to a given room occupant.
2004     * The Chat's occupant address is the room's JID (i.e. roomName@service/nick). The server
2005     * service will change the 'from' address to the sender's room JID and delivering the message
2006     * to the intended recipient's full JID.
2007     *
2008     * @param occupant occupant unique room JID (e.g. 'darkcave@macbeth.shakespeare.lit/Paul').
2009     * @param listener the listener is a message listener that will handle messages for the newly
2010     * created chat.
2011     * @return new Chat for sending private messages to a given room occupant.
2012     */
2013    // TODO This should be made new not using chat.Chat. Private MUC chats are different from XMPP-IM 1:1 chats in to many ways.
2014    // API sketch: PrivateMucChat createPrivateChat(Resourcepart nick)
2015    @SuppressWarnings("deprecation")
2016    public org.jivesoftware.smack.chat.Chat createPrivateChat(EntityFullJid occupant, ChatMessageListener listener) {
2017        return org.jivesoftware.smack.chat.ChatManager.getInstanceFor(connection).createChat(occupant, listener);
2018    }
2019
2020    /**
2021     * Creates a new Message to send to the chat room.
2022     *
2023     * @return a new Message addressed to the chat room.
2024     * @deprecated use {@link #buildMessage()} instead.
2025     */
2026    @Deprecated
2027    // TODO: Remove when stanza builder is ready.
2028    public Message createMessage() {
2029        return connection.getStanzaFactory().buildMessageStanza()
2030                .ofType(Message.Type.groupchat)
2031                .to(room)
2032                .build();
2033    }
2034
2035    /**
2036     * Constructs a new message builder for messages send to this MUC room.
2037     *
2038     * @return a new message builder.
2039     */
2040    public MessageBuilder buildMessage() {
2041        return connection.getStanzaFactory()
2042                .buildMessageStanza()
2043                .ofType(Message.Type.groupchat)
2044                .to(room)
2045                ;
2046    }
2047
2048    /**
2049     * Sends a Message to the chat room.
2050     *
2051     * @param message the message.
2052     * @throws NotConnectedException if the XMPP connection is not connected.
2053     * @throws InterruptedException if the calling thread was interrupted.
2054     * @deprecated use {@link #sendMessage(MessageBuilder)} instead.
2055     */
2056    @Deprecated
2057    // TODO: Remove in Smack 4.5.
2058    public void sendMessage(Message message) throws NotConnectedException, InterruptedException {
2059        sendMessage(message.asBuilder());
2060    }
2061
2062    /**
2063     * Sends a Message to the chat room.
2064     *
2065     * @param messageBuilder the message.
2066     * @return a read-only view of the send message.
2067     * @throws NotConnectedException if the XMPP connection is not connected.
2068     * @throws InterruptedException if the calling thread was interrupted.
2069     */
2070    public MessageView sendMessage(MessageBuilder messageBuilder) throws NotConnectedException, InterruptedException {
2071        for (MucMessageInterceptor interceptor : messageInterceptors) {
2072            interceptor.intercept(messageBuilder, this);
2073        }
2074
2075        Message message = messageBuilder.to(room).ofType(Message.Type.groupchat).build();
2076        connection.sendStanza(message);
2077        return message;
2078    }
2079
2080    /**
2081    * Polls for and returns the next message, or <code>null</code> if there isn't
2082    * a message immediately available. This method provides significantly different
2083    * functionalty than the {@link #nextMessage()} method since it's non-blocking.
2084    * In other words, the method call will always return immediately, whereas the
2085    * nextMessage method will return only when a message is available (or after
2086    * a specific timeout).
2087    *
2088    * @return the next message if one is immediately available and
2089    *      <code>null</code> otherwise.
2090     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
2091    */
2092    public Message pollMessage() throws MucNotJoinedException {
2093        if (messageCollector == null) {
2094            throw new MucNotJoinedException(this);
2095        }
2096        return messageCollector.pollResult();
2097    }
2098
2099    /**
2100     * Returns the next available message in the chat. The method call will block
2101     * (not return) until a message is available.
2102     *
2103     * @return the next message.
2104     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
2105     * @throws InterruptedException if the calling thread was interrupted.
2106     */
2107    public Message nextMessage() throws MucNotJoinedException, InterruptedException {
2108        if (messageCollector == null) {
2109            throw new MucNotJoinedException(this);
2110        }
2111        return  messageCollector.nextResultBlockForever();
2112    }
2113
2114    /**
2115     * Returns the next available message in the chat. The method call will block
2116     * (not return) until a stanza is available or the <code>timeout</code> has elapased.
2117     * If the timeout elapses without a result, <code>null</code> will be returned.
2118     *
2119     * @param timeout the maximum amount of time to wait for the next message.
2120     * @return the next message, or <code>null</code> if the timeout elapses without a
2121     *      message becoming available.
2122     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
2123     * @throws InterruptedException if the calling thread was interrupted.
2124     */
2125    public Message nextMessage(long timeout) throws MucNotJoinedException, InterruptedException {
2126        if (messageCollector == null) {
2127            throw new MucNotJoinedException(this);
2128        }
2129        return messageCollector.nextResult(timeout);
2130    }
2131
2132    /**
2133     * Adds a stanza listener that will be notified of any new messages in the
2134     * group chat. Only "group chat" messages addressed to this group chat will
2135     * be delivered to the listener. If you wish to listen for other packets
2136     * that may be associated with this group chat, you should register a
2137     * PacketListener directly with the XMPPConnection with the appropriate
2138     * PacketListener.
2139     *
2140     * @param listener a stanza listener.
2141     * @return true if the listener was not already added.
2142     */
2143    public boolean addMessageListener(MessageListener listener) {
2144        return messageListeners.add(listener);
2145    }
2146
2147    /**
2148     * Removes a stanza listener that was being notified of any new messages in the
2149     * multi user chat. Only "group chat" messages addressed to this multi user chat were
2150     * being delivered to the listener.
2151     *
2152     * @param listener a stanza listener.
2153     * @return true if the listener was removed, otherwise the listener was not added previously.
2154     */
2155    public boolean removeMessageListener(MessageListener listener) {
2156        return messageListeners.remove(listener);
2157    }
2158
2159    public boolean addMessageInterceptor(MucMessageInterceptor interceptor) {
2160        return messageInterceptors.add(interceptor);
2161    }
2162
2163    public boolean removeMessageInterceptor(MucMessageInterceptor interceptor) {
2164        return messageInterceptors.remove(interceptor);
2165    }
2166
2167    /**
2168     * Changes the subject within the room. As a default, only users with a role of "moderator"
2169     * are allowed to change the subject in a room. Although some rooms may be configured to
2170     * allow a mere participant or even a visitor to change the subject.
2171     *
2172     * @param subject the new room's subject to set.
2173     * @throws XMPPErrorException if someone without appropriate privileges attempts to change the
2174     *          room subject will throw an error with code 403 (i.e. Forbidden)
2175     * @throws NoResponseException if there was no response from the server.
2176     * @throws NotConnectedException if the XMPP connection is not connected.
2177     * @throws InterruptedException if the calling thread was interrupted.
2178     */
2179    public void changeSubject(final String subject) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
2180        MessageBuilder message = buildMessage();
2181        message.setSubject(subject);
2182        // Wait for an error or confirmation message back from the server.
2183        StanzaFilter responseFilter = new AndFilter(fromRoomGroupchatFilter, new StanzaFilter() {
2184            @Override
2185            public boolean accept(Stanza packet) {
2186                Message msg = (Message) packet;
2187                return subject.equals(msg.getSubject());
2188            }
2189        });
2190        StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, message.build());
2191        // Wait up to a certain number of seconds for a reply.
2192        response.nextResultOrThrow();
2193    }
2194
2195    /**
2196     * Remove the connection callbacks (PacketListener, PacketInterceptor, StanzaCollector) used by this MUC from the
2197     * connection.
2198     */
2199    private void removeConnectionCallbacks() {
2200        connection.removeStanzaListener(messageListener);
2201        connection.removeStanzaListener(presenceListener);
2202        connection.removeStanzaListener(subjectListener);
2203        connection.removeStanzaListener(declinesListener);
2204        connection.removeStanzaSendingListener(presenceInterceptor);
2205        if (messageCollector != null) {
2206            messageCollector.cancel();
2207            messageCollector = null;
2208        }
2209    }
2210
2211    /**
2212     * Remove all callbacks and resources necessary when the user has left the room for some reason.
2213     */
2214    private synchronized void userHasLeft() {
2215        // We do not reset nickname here, in case this method has been called erroneously, it should still be possible
2216        // to call leave() in order to resync the state. And leave() requires the nickname to send the unsubscribe
2217        // presence.
2218        occupantsMap.clear();
2219        myRoomJid = null;
2220        // Update the list of joined rooms
2221        multiUserChatManager.removeJoinedRoom(room);
2222        removeConnectionCallbacks();
2223    }
2224
2225    /**
2226     * Adds a listener that will be notified of changes in your status in the room
2227     * such as the user being kicked, banned, or granted admin permissions.
2228     *
2229     * @param listener a user status listener.
2230     * @return true if the user status listener was not already added.
2231     */
2232    public boolean addUserStatusListener(UserStatusListener listener) {
2233        return userStatusListeners.add(listener);
2234    }
2235
2236    /**
2237     * Removes a listener that was being notified of changes in your status in the room
2238     * such as the user being kicked, banned, or granted admin permissions.
2239     *
2240     * @param listener a user status listener.
2241     * @return true if the listener was registered and is now removed.
2242     */
2243    public boolean removeUserStatusListener(UserStatusListener listener) {
2244        return userStatusListeners.remove(listener);
2245    }
2246
2247    /**
2248     * Adds a listener that will be notified of changes in occupants status in the room
2249     * such as the user being kicked, banned, or granted admin permissions.
2250     *
2251     * @param listener a participant status listener.
2252     * @return true if the listener was not already added.
2253     */
2254    public boolean addParticipantStatusListener(ParticipantStatusListener listener) {
2255        return participantStatusListeners.add(listener);
2256    }
2257
2258    /**
2259     * Removes a listener that was being notified of changes in occupants status in the room
2260     * such as the user being kicked, banned, or granted admin permissions.
2261     *
2262     * @param listener a participant status listener.
2263     * @return true if the listener was registered and is now removed.
2264     */
2265    public boolean removeParticipantStatusListener(ParticipantStatusListener listener) {
2266        return participantStatusListeners.remove(listener);
2267    }
2268
2269    /**
2270     * Fires notification events if the role of a room occupant has changed. If the occupant that
2271     * changed his role is your occupant then the <code>UserStatusListeners</code> added to this
2272     * <code>MultiUserChat</code> will be fired. On the other hand, if the occupant that changed
2273     * his role is not yours then the <code>ParticipantStatusListeners</code> added to this
2274     * <code>MultiUserChat</code> will be fired. The following table shows the events that will
2275     * be fired depending on the previous and new role of the occupant.
2276     *
2277     * <pre>
2278     * <table border="1">
2279     * <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr>
2280     *
2281     * <tr><td>None</td><td>Visitor</td><td>--</td></tr>
2282     * <tr><td>Visitor</td><td>Participant</td><td>voiceGranted</td></tr>
2283     * <tr><td>Participant</td><td>Moderator</td><td>moderatorGranted</td></tr>
2284     *
2285     * <tr><td>None</td><td>Participant</td><td>voiceGranted</td></tr>
2286     * <tr><td>None</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr>
2287     * <tr><td>Visitor</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr>
2288     *
2289     * <tr><td>Moderator</td><td>Participant</td><td>moderatorRevoked</td></tr>
2290     * <tr><td>Participant</td><td>Visitor</td><td>voiceRevoked</td></tr>
2291     * <tr><td>Visitor</td><td>None</td><td>kicked</td></tr>
2292     *
2293     * <tr><td>Moderator</td><td>Visitor</td><td>voiceRevoked + moderatorRevoked</td></tr>
2294     * <tr><td>Moderator</td><td>None</td><td>kicked</td></tr>
2295     * <tr><td>Participant</td><td>None</td><td>kicked</td></tr>
2296     * </table>
2297     * </pre>
2298     *
2299     * @param oldRole the previous role of the user in the room before receiving the new presence
2300     * @param newRole the new role of the user in the room after receiving the new presence
2301     * @param isUserModification whether the received presence is about your user in the room or not
2302     * @param from the occupant whose role in the room has changed
2303     * (e.g. room@conference.jabber.org/nick).
2304     */
2305    private void checkRoleModifications(
2306        MUCRole oldRole,
2307        MUCRole newRole,
2308        boolean isUserModification,
2309        EntityFullJid from) {
2310        // Voice was granted to a visitor
2311        if ((MUCRole.visitor.equals(oldRole) || MUCRole.none.equals(oldRole))
2312            && MUCRole.participant.equals(newRole)) {
2313            if (isUserModification) {
2314                for (UserStatusListener listener : userStatusListeners) {
2315                    listener.voiceGranted();
2316                }
2317            }
2318            else {
2319                for (ParticipantStatusListener listener : participantStatusListeners) {
2320                    listener.voiceGranted(from);
2321                }
2322            }
2323        }
2324        // The participant's voice was revoked from the room
2325        else if (
2326            MUCRole.participant.equals(oldRole)
2327                && (MUCRole.visitor.equals(newRole) || MUCRole.none.equals(newRole))) {
2328            if (isUserModification) {
2329                for (UserStatusListener listener : userStatusListeners) {
2330                    listener.voiceRevoked();
2331                }
2332            }
2333            else {
2334                for (ParticipantStatusListener listener : participantStatusListeners) {
2335                    listener.voiceRevoked(from);
2336                }
2337            }
2338        }
2339        // Moderator privileges were granted to a participant
2340        if (!MUCRole.moderator.equals(oldRole) && MUCRole.moderator.equals(newRole)) {
2341            if (MUCRole.visitor.equals(oldRole) || MUCRole.none.equals(oldRole)) {
2342                if (isUserModification) {
2343                    for (UserStatusListener listener : userStatusListeners) {
2344                        listener.voiceGranted();
2345                    }
2346                }
2347                else {
2348                    for (ParticipantStatusListener listener : participantStatusListeners) {
2349                        listener.voiceGranted(from);
2350                    }
2351                }
2352            }
2353            if (isUserModification) {
2354                for (UserStatusListener listener : userStatusListeners) {
2355                    listener.moderatorGranted();
2356                }
2357            }
2358            else {
2359                for (ParticipantStatusListener listener : participantStatusListeners) {
2360                    listener.moderatorGranted(from);
2361                }
2362            }
2363        }
2364        // Moderator privileges were revoked from a participant
2365        else if (MUCRole.moderator.equals(oldRole) && !MUCRole.moderator.equals(newRole)) {
2366            if (MUCRole.visitor.equals(newRole) || MUCRole.none.equals(newRole)) {
2367                if (isUserModification) {
2368                    for (UserStatusListener listener : userStatusListeners) {
2369                        listener.voiceRevoked();
2370                    }
2371                }
2372                else {
2373                    for (ParticipantStatusListener listener : participantStatusListeners) {
2374                        listener.voiceRevoked(from);
2375                    }
2376                }
2377            }
2378            if (isUserModification) {
2379                for (UserStatusListener listener : userStatusListeners) {
2380                    listener.moderatorRevoked();
2381                }
2382            }
2383            else {
2384                for (ParticipantStatusListener listener : participantStatusListeners) {
2385                    listener.moderatorRevoked(from);
2386                }
2387            }
2388        }
2389    }
2390
2391    /**
2392     * Fires notification events if the affiliation of a room occupant has changed. If the
2393     * occupant that changed his affiliation is your occupant then the
2394     * <code>UserStatusListeners</code> added to this <code>MultiUserChat</code> will be fired.
2395     * On the other hand, if the occupant that changed his affiliation is not yours then the
2396     * <code>ParticipantStatusListeners</code> added to this <code>MultiUserChat</code> will be
2397     * fired. The following table shows the events that will be fired depending on the previous
2398     * and new affiliation of the occupant.
2399     *
2400     * <pre>
2401     * <table border="1">
2402     * <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr>
2403     *
2404     * <tr><td>None</td><td>Member</td><td>membershipGranted</td></tr>
2405     * <tr><td>Member</td><td>Admin</td><td>membershipRevoked + adminGranted</td></tr>
2406     * <tr><td>Admin</td><td>Owner</td><td>adminRevoked + ownershipGranted</td></tr>
2407     *
2408     * <tr><td>None</td><td>Admin</td><td>adminGranted</td></tr>
2409     * <tr><td>None</td><td>Owner</td><td>ownershipGranted</td></tr>
2410     * <tr><td>Member</td><td>Owner</td><td>membershipRevoked + ownershipGranted</td></tr>
2411     *
2412     * <tr><td>Owner</td><td>Admin</td><td>ownershipRevoked + adminGranted</td></tr>
2413     * <tr><td>Admin</td><td>Member</td><td>adminRevoked + membershipGranted</td></tr>
2414     * <tr><td>Member</td><td>None</td><td>membershipRevoked</td></tr>
2415     *
2416     * <tr><td>Owner</td><td>Member</td><td>ownershipRevoked + membershipGranted</td></tr>
2417     * <tr><td>Owner</td><td>None</td><td>ownershipRevoked</td></tr>
2418     * <tr><td>Admin</td><td>None</td><td>adminRevoked</td></tr>
2419     * <tr><td><i>Anyone</i></td><td>Outcast</td><td>banned</td></tr>
2420     * </table>
2421     * </pre>
2422     *
2423     * @param oldAffiliation the previous affiliation of the user in the room before receiving the
2424     * new presence
2425     * @param newAffiliation the new affiliation of the user in the room after receiving the new
2426     * presence
2427     * @param isUserModification whether the received presence is about your user in the room or not
2428     * @param from the occupant whose role in the room has changed
2429     * (e.g. room@conference.jabber.org/nick).
2430     */
2431    private void checkAffiliationModifications(
2432        MUCAffiliation oldAffiliation,
2433        MUCAffiliation newAffiliation,
2434        boolean isUserModification,
2435        EntityFullJid from) {
2436        // First check for revoked affiliation and then for granted affiliations. The idea is to
2437        // first fire the "revoke" events and then fire the "grant" events.
2438
2439        // The user's ownership to the room was revoked
2440        if (MUCAffiliation.owner.equals(oldAffiliation) && !MUCAffiliation.owner.equals(newAffiliation)) {
2441            if (isUserModification) {
2442                for (UserStatusListener listener : userStatusListeners) {
2443                    listener.ownershipRevoked();
2444                }
2445            }
2446            else {
2447                for (ParticipantStatusListener listener : participantStatusListeners) {
2448                    listener.ownershipRevoked(from);
2449                }
2450            }
2451        }
2452        // The user's administrative privileges to the room were revoked
2453        else if (MUCAffiliation.admin.equals(oldAffiliation) && !MUCAffiliation.admin.equals(newAffiliation)) {
2454            if (isUserModification) {
2455                for (UserStatusListener listener : userStatusListeners) {
2456                    listener.adminRevoked();
2457                }
2458            }
2459            else {
2460                for (ParticipantStatusListener listener : participantStatusListeners) {
2461                    listener.adminRevoked(from);
2462                }
2463            }
2464        }
2465        // The user's membership to the room was revoked
2466        else if (MUCAffiliation.member.equals(oldAffiliation) && !MUCAffiliation.member.equals(newAffiliation)) {
2467            if (isUserModification) {
2468                for (UserStatusListener listener : userStatusListeners) {
2469                    listener.membershipRevoked();
2470                }
2471            }
2472            else {
2473                for (ParticipantStatusListener listener : participantStatusListeners) {
2474                    listener.membershipRevoked(from);
2475                }
2476            }
2477        }
2478
2479        // The user was granted ownership to the room
2480        if (!MUCAffiliation.owner.equals(oldAffiliation) && MUCAffiliation.owner.equals(newAffiliation)) {
2481            if (isUserModification) {
2482                for (UserStatusListener listener : userStatusListeners) {
2483                    listener.ownershipGranted();
2484                }
2485            }
2486            else {
2487                for (ParticipantStatusListener listener : participantStatusListeners) {
2488                    listener.ownershipGranted(from);
2489                }
2490            }
2491        }
2492        // The user was granted administrative privileges to the room
2493        else if (!MUCAffiliation.admin.equals(oldAffiliation) && MUCAffiliation.admin.equals(newAffiliation)) {
2494            if (isUserModification) {
2495                for (UserStatusListener listener : userStatusListeners) {
2496                    listener.adminGranted();
2497                }
2498            }
2499            else {
2500                for (ParticipantStatusListener listener : participantStatusListeners) {
2501                    listener.adminGranted(from);
2502                }
2503            }
2504        }
2505        // The user was granted membership to the room
2506        else if (!MUCAffiliation.member.equals(oldAffiliation) && MUCAffiliation.member.equals(newAffiliation)) {
2507            if (isUserModification) {
2508                for (UserStatusListener listener : userStatusListeners) {
2509                    listener.membershipGranted();
2510                }
2511            }
2512            else {
2513                for (ParticipantStatusListener listener : participantStatusListeners) {
2514                    listener.membershipGranted(from);
2515                }
2516            }
2517        }
2518    }
2519
2520    /**
2521     * Fires events according to the received presence code.
2522     *
2523     * @param statusCodes TODO javadoc me please
2524     * @param isUserModification TODO javadoc me please
2525     * @param mucUser TODO javadoc me please
2526     * @param from TODO javadoc me please
2527     */
2528    private void checkPresenceCode(
2529        Set<Status> statusCodes,
2530        boolean isUserModification,
2531        MUCUser mucUser,
2532        EntityFullJid from) {
2533        // Check if an occupant was kicked from the room
2534        if (statusCodes.contains(Status.KICKED_307)) {
2535            // Check if this occupant was kicked
2536            if (isUserModification) {
2537                for (UserStatusListener listener : userStatusListeners) {
2538                    listener.kicked(mucUser.getItem().getActor(), mucUser.getItem().getReason());
2539                }
2540            }
2541            else {
2542                for (ParticipantStatusListener listener : participantStatusListeners) {
2543                    listener.kicked(from, mucUser.getItem().getActor(), mucUser.getItem().getReason());
2544                }
2545            }
2546        }
2547        // A user was banned from the room
2548        if (statusCodes.contains(Status.BANNED_301)) {
2549            // Check if this occupant was banned
2550            if (isUserModification) {
2551                for (UserStatusListener listener : userStatusListeners) {
2552                    listener.banned(mucUser.getItem().getActor(), mucUser.getItem().getReason());
2553                }
2554            }
2555            else {
2556                for (ParticipantStatusListener listener : participantStatusListeners) {
2557                    listener.banned(from, mucUser.getItem().getActor(), mucUser.getItem().getReason());
2558                }
2559            }
2560        }
2561        // A user's membership was revoked from the room
2562        if (statusCodes.contains(Status.REMOVED_AFFIL_CHANGE_321)) {
2563            // Check if this occupant's membership was revoked
2564            if (isUserModification) {
2565                for (UserStatusListener listener : userStatusListeners) {
2566                    listener.membershipRevoked();
2567                }
2568            }
2569        }
2570        // A occupant has changed his nickname in the room
2571        if (statusCodes.contains(Status.NEW_NICKNAME_303)) {
2572            for (ParticipantStatusListener listener : participantStatusListeners) {
2573                listener.nicknameChanged(from, mucUser.getItem().getNick());
2574            }
2575        }
2576    }
2577
2578    /**
2579     * Get the XMPP connection associated with this chat instance.
2580     *
2581     * @return the associated XMPP connection.
2582     * @since 4.3.0
2583     */
2584    public XMPPConnection getXmppConnection() {
2585        return connection;
2586    }
2587
2588    public boolean serviceSupportsStableIds() {
2589        return DiscoverInfo.nullSafeContainsFeature(mucServiceDiscoInfo, MultiUserChatConstants.STABLE_ID_FEATURE);
2590    }
2591
2592    @Override
2593    public String toString() {
2594        return "MUC: " + room + "(" + connection.getUser() + ")";
2595    }
2596}