• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

igniterealtime / Smack / #3270

27 Aug 2024 09:52AM UTC coverage: 38.824% (+0.01%) from 38.81%
#3270

push

github

web-flow
Merge pull request #616 from guusdk/SMACK-950_MUC-destroy-password

[muc] Add support for 'password' in room destroy

0 of 16 new or added lines in 3 files covered. (0.0%)

3 existing lines in 3 files now uncovered.

16980 of 43736 relevant lines covered (38.82%)

0.39 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

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

18
package org.jivesoftware.smackx.muc;
19

20
import java.util.ArrayList;
21
import java.util.Collection;
22
import java.util.List;
23
import java.util.Map;
24
import java.util.Set;
25
import java.util.concurrent.ConcurrentHashMap;
26
import java.util.concurrent.CopyOnWriteArrayList;
27
import java.util.concurrent.CopyOnWriteArraySet;
28
import java.util.concurrent.atomic.AtomicInteger;
29
import java.util.logging.Level;
30
import java.util.logging.Logger;
31

32
import org.jivesoftware.smack.MessageListener;
33
import org.jivesoftware.smack.PresenceListener;
34
import org.jivesoftware.smack.SmackException;
35
import org.jivesoftware.smack.SmackException.NoResponseException;
36
import org.jivesoftware.smack.SmackException.NotConnectedException;
37
import org.jivesoftware.smack.StanzaCollector;
38
import org.jivesoftware.smack.StanzaListener;
39
import org.jivesoftware.smack.XMPPConnection;
40
import org.jivesoftware.smack.XMPPException;
41
import org.jivesoftware.smack.XMPPException.XMPPErrorException;
42
import org.jivesoftware.smack.chat.ChatMessageListener;
43
import org.jivesoftware.smack.filter.AndFilter;
44
import org.jivesoftware.smack.filter.FromMatchesFilter;
45
import org.jivesoftware.smack.filter.MessageTypeFilter;
46
import org.jivesoftware.smack.filter.MessageWithBodiesFilter;
47
import org.jivesoftware.smack.filter.MessageWithSubjectFilter;
48
import org.jivesoftware.smack.filter.MessageWithThreadFilter;
49
import org.jivesoftware.smack.filter.NotFilter;
50
import org.jivesoftware.smack.filter.OrFilter;
51
import org.jivesoftware.smack.filter.PossibleFromTypeFilter;
52
import org.jivesoftware.smack.filter.PresenceTypeFilter;
53
import org.jivesoftware.smack.filter.StanzaExtensionFilter;
54
import org.jivesoftware.smack.filter.StanzaFilter;
55
import org.jivesoftware.smack.filter.StanzaIdFilter;
56
import org.jivesoftware.smack.filter.StanzaTypeFilter;
57
import org.jivesoftware.smack.filter.ToMatchesFilter;
58
import org.jivesoftware.smack.packet.IQ;
59
import org.jivesoftware.smack.packet.Message;
60
import org.jivesoftware.smack.packet.MessageBuilder;
61
import org.jivesoftware.smack.packet.MessageView;
62
import org.jivesoftware.smack.packet.Presence;
63
import org.jivesoftware.smack.packet.PresenceBuilder;
64
import org.jivesoftware.smack.packet.Stanza;
65
import org.jivesoftware.smack.util.Consumer;
66
import org.jivesoftware.smack.util.Objects;
67

68
import org.jivesoftware.smackx.disco.ServiceDiscoveryManager;
69
import org.jivesoftware.smackx.disco.packet.DiscoverInfo;
70
import org.jivesoftware.smackx.iqregister.packet.Registration;
71
import org.jivesoftware.smackx.muc.MultiUserChatException.MissingMucCreationAcknowledgeException;
72
import org.jivesoftware.smackx.muc.MultiUserChatException.MucAlreadyJoinedException;
73
import org.jivesoftware.smackx.muc.MultiUserChatException.MucNotJoinedException;
74
import org.jivesoftware.smackx.muc.MultiUserChatException.NotAMucServiceException;
75
import org.jivesoftware.smackx.muc.filter.MUCUserStatusCodeFilter;
76
import org.jivesoftware.smackx.muc.packet.Destroy;
77
import org.jivesoftware.smackx.muc.packet.GroupChatInvitation;
78
import org.jivesoftware.smackx.muc.packet.MUCAdmin;
79
import org.jivesoftware.smackx.muc.packet.MUCInitialPresence;
80
import org.jivesoftware.smackx.muc.packet.MUCItem;
81
import org.jivesoftware.smackx.muc.packet.MUCOwner;
82
import org.jivesoftware.smackx.muc.packet.MUCUser;
83
import org.jivesoftware.smackx.muc.packet.MUCUser.Status;
84
import org.jivesoftware.smackx.xdata.FormField;
85
import org.jivesoftware.smackx.xdata.TextSingleFormField;
86
import org.jivesoftware.smackx.xdata.form.FillableForm;
87
import org.jivesoftware.smackx.xdata.form.Form;
88
import org.jivesoftware.smackx.xdata.packet.DataForm;
89

90
import org.jxmpp.jid.DomainBareJid;
91
import org.jxmpp.jid.EntityBareJid;
92
import org.jxmpp.jid.EntityFullJid;
93
import org.jxmpp.jid.EntityJid;
94
import org.jxmpp.jid.Jid;
95
import org.jxmpp.jid.impl.JidCreate;
96
import org.jxmpp.jid.parts.Resourcepart;
97

98
/**
99
 * A MultiUserChat room (XEP-45), created with {@link MultiUserChatManager#getMultiUserChat(EntityBareJid)}.
100
 * <p>
101
 * A MultiUserChat is a conversation that takes place among many users in a virtual
102
 * room. A room could have many occupants with different affiliation and roles.
103
 * Possible affiliations are "owner", "admin", "member", and "outcast". Possible roles
104
 * are "moderator", "participant", and "visitor". Each role and affiliation guarantees
105
 * different privileges (e.g. Send messages to all occupants, Kick participants and visitors,
106
 * Grant voice, Edit member list, etc.).
107
 * </p>
108
 * <p>
109
 * <b>Note:</b> Make sure to leave the MUC ({@link #leave()}) when you don't need it anymore or
110
 * otherwise you may leak the instance.
111
 * </p>
112
 *
113
 * @author Gaston Dombiak
114
 * @author Larry Kirschner
115
 * @author Florian Schmaus
116
 */
117
public class MultiUserChat {
118
    private static final Logger LOGGER = Logger.getLogger(MultiUserChat.class.getName());
1✔
119

120
    private final XMPPConnection connection;
121
    private final EntityBareJid room;
122
    private final MultiUserChatManager multiUserChatManager;
123
    private final Map<EntityFullJid, Presence> occupantsMap = new ConcurrentHashMap<>();
1✔
124

125
    private final Set<InvitationRejectionListener> invitationRejectionListeners = new CopyOnWriteArraySet<InvitationRejectionListener>();
1✔
126
    private final Set<SubjectUpdatedListener> subjectUpdatedListeners = new CopyOnWriteArraySet<SubjectUpdatedListener>();
1✔
127
    private final Set<UserStatusListener> userStatusListeners = new CopyOnWriteArraySet<UserStatusListener>();
1✔
128
    private final Set<ParticipantStatusListener> participantStatusListeners = new CopyOnWriteArraySet<ParticipantStatusListener>();
1✔
129
    private final Set<MessageListener> messageListeners = new CopyOnWriteArraySet<MessageListener>();
1✔
130
    private final Set<PresenceListener> presenceListeners = new CopyOnWriteArraySet<PresenceListener>();
1✔
131
    private final Set<Consumer<PresenceBuilder>> presenceInterceptors = new CopyOnWriteArraySet<>();
1✔
132

133
    /**
134
     * This filter will match all stanzas send from the groupchat or from one if
135
     * the groupchat participants, i.e. it filters only the bare JID of the from
136
     * attribute against the JID of the MUC.
137
     */
138
    private final StanzaFilter fromRoomFilter;
139

140
    /**
141
     * Same as {@link #fromRoomFilter} together with {@link MessageTypeFilter#GROUPCHAT}.
142
     */
143
    private final StanzaFilter fromRoomGroupchatFilter;
144

145
    private final AtomicInteger presenceInterceptorCount = new AtomicInteger();
1✔
146
    // We want to save the presence interceptor in a variable, using a lambda, (and not use a method reference) to be
147
    // able to dynamically add and remove it from the connection.
148
    @SuppressWarnings("UnnecessaryLambda")
1✔
149
    private final Consumer<PresenceBuilder> presenceInterceptor = presenceBuilder -> {
150
        for (Consumer<PresenceBuilder> interceptor : presenceInterceptors) {
×
151
            interceptor.accept(presenceBuilder);
×
152
        }
×
153
    };
×
154

155
    private final StanzaListener messageListener;
156
    private final StanzaListener presenceListener;
157
    private final StanzaListener subjectListener;
158

159
    private static final StanzaFilter DECLINE_FILTER = new AndFilter(MessageTypeFilter.NORMAL,
1✔
160
                    new StanzaExtensionFilter(MUCUser.ELEMENT, MUCUser.NAMESPACE));
161
    private final StanzaListener declinesListener;
162

163
    private String subject;
164
    private EntityFullJid myRoomJid;
165
    private StanzaCollector messageCollector;
166

167
    private DiscoverInfo mucServiceDiscoInfo;
168

169
    /**
170
     * Used to signal that the reflected self-presence was received <b>and</b> processed by us.
171
     */
172
    private volatile boolean processedReflectedSelfPresence;
173

174
    private CopyOnWriteArrayList<MucMessageInterceptor> messageInterceptors;
175

176
    MultiUserChat(XMPPConnection connection, EntityBareJid room, MultiUserChatManager multiUserChatManager) {
1✔
177
        this.connection = connection;
1✔
178
        this.room = room;
1✔
179
        this.multiUserChatManager = multiUserChatManager;
1✔
180
        this.messageInterceptors = MultiUserChatManager.getMessageInterceptors();
1✔
181

182
        fromRoomFilter = FromMatchesFilter.create(room);
1✔
183
        fromRoomGroupchatFilter = new AndFilter(fromRoomFilter, MessageTypeFilter.GROUPCHAT);
1✔
184

185
        messageListener = new StanzaListener() {
1✔
186
            @Override
187
            public void processStanza(Stanza packet) throws NotConnectedException {
188
                final Message message = (Message) packet;
×
189

190
                for (MessageListener listener : messageListeners) {
×
191
                            listener.processMessage(message);
×
192
                }
×
193
            }
×
194
        };
195

196
        // Create a listener for subject updates.
197
        subjectListener = new StanzaListener() {
1✔
198
            @Override
199
            public void processStanza(Stanza packet) {
200
                final Message msg = (Message) packet;
×
201
                final EntityFullJid from = msg.getFrom().asEntityFullJidIfPossible();
×
202
                // Update the room subject
203
                subject = msg.getSubject();
×
204

205
                // Fire event for subject updated listeners
206
                for (SubjectUpdatedListener listener : subjectUpdatedListeners) {
×
207
                    listener.subjectUpdated(msg.getSubject(), from);
×
208
                }
×
209
            }
×
210
        };
211

212
        // Create a listener for all presence updates.
213
        presenceListener = new StanzaListener() {
1✔
214
            @Override
215
            public void processStanza(final Stanza packet) {
216
                final Presence presence = (Presence) packet;
×
217
                final EntityFullJid from = presence.getFrom().asEntityFullJidIfPossible();
×
218
                if (from == null) {
×
219
                    return;
×
220
                }
221
                final EntityFullJid myRoomJID = getMyRoomJid();
×
222
                final boolean isUserStatusModification = presence.getFrom().equals(myRoomJID);
×
223
                final MUCUser mucUser = MUCUser.from(packet);
×
224

225
                switch (presence.getType()) {
×
226
                case available:
227
                    if (!processedReflectedSelfPresence
×
228
                                    && mucUser.getStatus().contains(MUCUser.Status.PRESENCE_TO_SELF_110)) {
×
229
                        processedReflectedSelfPresence = true;
×
230
                        synchronized (this) {
×
231
                            notify();
×
232
                        }
×
233
                    }
234

235
                    Presence oldPresence = occupantsMap.put(from, presence);
×
236
                    if (oldPresence != null) {
×
237
                        // Get the previous occupant's affiliation & role
238
                        MUCUser mucExtension = MUCUser.from(oldPresence);
×
239
                        MUCAffiliation oldAffiliation = mucExtension.getItem().getAffiliation();
×
240
                        MUCRole oldRole = mucExtension.getItem().getRole();
×
241
                        // Get the new occupant's affiliation & role
242
                        MUCAffiliation newAffiliation = mucUser.getItem().getAffiliation();
×
243
                        MUCRole newRole = mucUser.getItem().getRole();
×
244
                        // Fire role modification events
245
                        checkRoleModifications(oldRole, newRole, isUserStatusModification, from);
×
246
                        // Fire affiliation modification events
247
                        checkAffiliationModifications(
×
248
                            oldAffiliation,
249
                            newAffiliation,
250
                            isUserStatusModification,
251
                            from);
252
                    } else {
×
253
                        // A new occupant has joined the room
254
                        for (ParticipantStatusListener listener : participantStatusListeners) {
×
255
                            listener.joined(from);
×
256
                        }
×
257
                    }
258
                    break;
×
259
                case unavailable:
260
                    occupantsMap.remove(from);
×
261
                    Set<Status> status = mucUser.getStatus();
×
262
                    if (mucUser != null && !status.isEmpty()) {
×
263
                        if (isUserStatusModification && !status.contains(MUCUser.Status.NEW_NICKNAME_303)) {
×
264
                            userHasLeft();
×
265
                        }
266
                        // Fire events according to the received presence code
267
                        checkPresenceCode(
×
268
                            status,
269
                            isUserStatusModification,
270
                            mucUser,
271
                            from);
272
                    } else {
273
                        // An occupant has left the room
274
                        if (!isUserStatusModification) {
×
275
                            for (ParticipantStatusListener listener : participantStatusListeners) {
×
276
                                listener.left(from);
×
277
                            }
×
278
                        }
279
                    }
280

281
                    Destroy destroy = mucUser == null ? null : mucUser.getDestroy();
×
282
                    // The room has been destroyed.
283
                    if (destroy != null) {
×
284
                        EntityBareJid alternateMucJid = destroy.getJid();
×
285
                        final MultiUserChat alternateMuc;
286
                        if (alternateMucJid == null) {
×
287
                            alternateMuc = null;
×
288
                        } else {
289
                            alternateMuc = multiUserChatManager.getMultiUserChat(alternateMucJid);
×
290
                        }
291

292
                        for (UserStatusListener listener : userStatusListeners) {
×
NEW
293
                            listener.roomDestroyed(alternateMuc, destroy.getPassword(), destroy.getReason());
×
294
                        }
×
295
                    }
296

297
                    if (isUserStatusModification) {
×
298
                        for (UserStatusListener listener : userStatusListeners) {
×
299
                            listener.removed(mucUser, presence);
×
300
                        }
×
301
                    } else {
302
                        for (ParticipantStatusListener listener : participantStatusListeners) {
×
303
                            listener.parted(from);
×
304
                        }
×
305
                    }
306
                    break;
×
307
                default:
308
                    break;
309
                }
310
                for (PresenceListener listener : presenceListeners) {
×
311
                    listener.processPresence(presence);
×
312
                }
×
313
            }
×
314
        };
315

316
        // Listens for all messages that include a MUCUser extension and fire the invitation
317
        // rejection listeners if the message includes an invitation rejection.
318
        declinesListener = new StanzaListener() {
1✔
319
            @Override
320
            public void processStanza(Stanza packet) {
321
                Message message = (Message) packet;
×
322
                // Get the MUC User extension
323
                MUCUser mucUser = MUCUser.from(packet);
×
324
                MUCUser.Decline rejection = mucUser.getDecline();
×
325
                // Check if the MUCUser informs that the invitee has declined the invitation
326
                if (rejection == null) {
×
327
                    return;
×
328
                }
329
                // Fire event for invitation rejection listeners
330
                fireInvitationRejectionListeners(message, rejection);
×
331
            }
×
332
        };
333
    }
1✔
334

335

336
    /**
337
     * Returns the name of the room this MultiUserChat object represents.
338
     *
339
     * @return the multi user chat room name.
340
     */
341
    public EntityBareJid getRoom() {
342
        return room;
1✔
343
    }
344

345
    /**
346
     * Enter a room, as described in XEP-45 7.2.
347
     *
348
     * @param conf the configuration used to enter the room.
349
     * @return the returned presence by the service after the client send the initial presence in order to enter the room.
350
     * @throws NotConnectedException if the XMPP connection is not connected.
351
     * @throws NoResponseException if there was no response from the remote entity.
352
     * @throws XMPPErrorException if there was an XMPP error returned.
353
     * @throws InterruptedException if the calling thread was interrupted.
354
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
355
     * @see <a href="http://xmpp.org/extensions/xep-0045.html#enter">XEP-45 7.2 Entering a Room</a>
356
     */
357
    private Presence enter(MucEnterConfiguration conf) throws NotConnectedException, NoResponseException,
358
                    XMPPErrorException, InterruptedException, NotAMucServiceException {
359
        final DomainBareJid mucService = room.asDomainBareJid();
×
360
        mucServiceDiscoInfo = multiUserChatManager.getMucServiceDiscoInfo(mucService);
×
361
        if (mucServiceDiscoInfo == null) {
×
362
            throw new NotAMucServiceException(this);
×
363
        }
364
        // We enter a room by sending a presence packet where the "to"
365
        // field is in the form "roomName@service/nickname"
366
        Presence joinPresence = conf.getJoinPresence(this);
×
367

368
        // Setup the messageListeners and presenceListeners *before* the join presence is send.
369
        connection.addStanzaListener(messageListener, fromRoomGroupchatFilter);
×
370
        StanzaFilter presenceFromRoomFilter = new AndFilter(fromRoomFilter,
×
371
                        StanzaTypeFilter.PRESENCE,
372
                        PossibleFromTypeFilter.ENTITY_FULL_JID);
373
        connection.addStanzaListener(presenceListener, presenceFromRoomFilter);
×
374
        // @formatter:off
375
        connection.addStanzaListener(subjectListener,
×
376
                        new AndFilter(fromRoomFilter,
377
                                      MessageWithSubjectFilter.INSTANCE,
378
                                      new NotFilter(MessageTypeFilter.ERROR),
379
                                      // According to XEP-0045 § 8.1 "A message with a <subject/> and a <body/> or a <subject/> and a <thread/> is a
380
                                      // legitimate message, but it SHALL NOT be interpreted as a subject change."
381
                                      new NotFilter(MessageWithBodiesFilter.INSTANCE),
382
                                      new NotFilter(MessageWithThreadFilter.INSTANCE))
383
                        );
384
        // @formatter:on
385
        connection.addStanzaListener(declinesListener, new AndFilter(fromRoomFilter, DECLINE_FILTER));
×
386
        messageCollector = connection.createStanzaCollector(fromRoomGroupchatFilter);
×
387

388
        // Wait for a presence packet back from the server.
389
        // @formatter:off
390
        StanzaFilter responseFilter = new AndFilter(StanzaTypeFilter.PRESENCE,
×
391
                        new OrFilter(
392
                            // We use a bare JID filter for positive responses, since the MUC service/room may rewrite the nickname.
393
                            new AndFilter(FromMatchesFilter.createBare(getRoom()), MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
×
394
                            // In case there is an error reply, we match on an error presence with the same stanza id and from the full
395
                            // JID we send the join presence to.
396
                            new AndFilter(FromMatchesFilter.createFull(joinPresence.getTo()), new StanzaIdFilter(joinPresence), PresenceTypeFilter.ERROR)
×
397
                        )
398
                    );
399
        // @formatter:on
400
        processedReflectedSelfPresence = false;
×
401
        StanzaCollector presenceStanzaCollector = null;
×
402
        final Presence reflectedSelfPresence;
403
        try {
404
            // This stanza collector will collect the final self presence from the MUC, which also signals that we have successful entered the MUC.
405
            StanzaCollector selfPresenceCollector = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
×
406
            StanzaCollector.Configuration presenceStanzaCollectorConfguration = StanzaCollector.newConfiguration().setCollectorToReset(
×
407
                            selfPresenceCollector).setStanzaFilter(presenceFromRoomFilter);
×
408
            // This stanza collector is used to reset the timeout of the selfPresenceCollector.
409
            presenceStanzaCollector = connection.createStanzaCollector(presenceStanzaCollectorConfguration);
×
410
            reflectedSelfPresence = selfPresenceCollector.nextResultOrThrow(conf.getTimeout());
×
411
        }
412
        catch (NotConnectedException | InterruptedException | NoResponseException | XMPPErrorException e) {
×
413
            // Ensure that all callbacks are removed if there is an exception
414
            removeConnectionCallbacks();
×
415
            throw e;
×
416
        }
417
        finally {
418
            if (presenceStanzaCollector != null) {
×
419
                presenceStanzaCollector.cancel();
×
420
            }
421
        }
422

423
        synchronized (presenceListener) {
×
424
            // Only continue after we have received *and* processed the reflected self-presence. Since presences are
425
            // handled in an extra listener, we may return from enter() without having processed all presences of the
426
            // participants, resulting in a e.g. to low participant counter after enter(). Hence we wait here until the
427
            // processing is done.
428
            while (!processedReflectedSelfPresence) {
×
429
                presenceListener.wait();
×
430
            }
431
        }
×
432

433
        // This presence must be send from a full JID. We use the resourcepart of this JID as nick, since the room may
434
        // performed roomnick rewriting
435
        Resourcepart receivedNickname = reflectedSelfPresence.getFrom().getResourceOrThrow();
×
436
        setNickname(receivedNickname);
×
437

438
        // Update the list of joined rooms
439
        multiUserChatManager.addJoinedRoom(room);
×
440
        return reflectedSelfPresence;
×
441
    }
442

443
    private void setNickname(Resourcepart nickname) {
444
        this.myRoomJid = JidCreate.entityFullFrom(room, nickname);
×
445
    }
×
446

447
    /**
448
     * Get a new MUC enter configuration builder.
449
     *
450
     * @param nickname the nickname used when entering the MUC room.
451
     * @return a new MUC enter configuration builder.
452
     * @since 4.2
453
     */
454
    public MucEnterConfiguration.Builder getEnterConfigurationBuilder(Resourcepart nickname) {
455
        return new MucEnterConfiguration.Builder(nickname, connection);
×
456
    }
457

458
    /**
459
     * Creates the room according to some default configuration, assign the requesting user as the
460
     * room owner, and add the owner to the room but not allow anyone else to enter the room
461
     * (effectively "locking" the room). The requesting user will join the room under the specified
462
     * nickname as soon as the room has been created.
463
     * <p>
464
     * To create an "Instant Room", that means a room with some default configuration that is
465
     * available for immediate access, the room's owner should send an empty form after creating the
466
     * room. Simply call {@link MucCreateConfigFormHandle#makeInstant()} on the returned {@link MucCreateConfigFormHandle}.
467
     * </p>
468
     * <p>
469
     * To create a "Reserved Room", that means a room manually configured by the room creator before
470
     * anyone is allowed to enter, the room's owner should complete and send a form after creating
471
     * the room. Once the completed configuration form is sent to the server, the server will unlock
472
     * the room. You can use the returned {@link MucCreateConfigFormHandle} to configure the room.
473
     * </p>
474
     *
475
     * @param nickname the nickname to use.
476
     * @return a handle to the MUC create configuration form API.
477
     * @throws XMPPErrorException if the room couldn't be created for some reason (e.g. 405 error if
478
     *         the user is not allowed to create the room)
479
     * @throws NoResponseException if there was no response from the server.
480
     * @throws InterruptedException if the calling thread was interrupted.
481
     * @throws NotConnectedException if the XMPP connection is not connected.
482
     * @throws MucAlreadyJoinedException if already joined the Multi-User Chat.7y
483
     * @throws MissingMucCreationAcknowledgeException if there MUC creation was not acknowledged by the service.
484
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
485
     */
486
    public synchronized MucCreateConfigFormHandle create(Resourcepart nickname) throws NoResponseException,
487
                    XMPPErrorException, InterruptedException, MucAlreadyJoinedException,
488
                    NotConnectedException, MissingMucCreationAcknowledgeException, NotAMucServiceException {
489
        if (isJoined()) {
×
490
            throw new MucAlreadyJoinedException();
×
491
        }
492

493
        MucCreateConfigFormHandle mucCreateConfigFormHandle = createOrJoin(nickname);
×
494
        if (mucCreateConfigFormHandle != null) {
×
495
            // We successfully created a new room
496
            return mucCreateConfigFormHandle;
×
497
        }
498
        // We need to leave the room since it seems that the room already existed
499
        try {
500
            leave();
×
501
        }
502
        catch (MucNotJoinedException e) {
×
503
            LOGGER.log(Level.INFO, "Unexpected MucNotJoinedException", e);
×
504
        }
×
505
        throw new MissingMucCreationAcknowledgeException();
×
506
    }
507

508
    /**
509
     * Create or join the MUC room with the given nickname.
510
     *
511
     * @param nickname the nickname to use in the MUC room.
512
     * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
513
     * @throws NoResponseException if there was no response from the remote entity.
514
     * @throws XMPPErrorException if there was an XMPP error returned.
515
     * @throws InterruptedException if the calling thread was interrupted.
516
     * @throws NotConnectedException if the XMPP connection is not connected.
517
     * @throws MucAlreadyJoinedException if already joined the Multi-User Chat.7y
518
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
519
     */
520
    public synchronized MucCreateConfigFormHandle createOrJoin(Resourcepart nickname) throws NoResponseException, XMPPErrorException,
521
                    InterruptedException, MucAlreadyJoinedException, NotConnectedException, NotAMucServiceException {
522
        MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).build();
×
523
        return createOrJoin(mucEnterConfiguration);
×
524
    }
525

526
    /**
527
     * Like {@link #create(Resourcepart)}, but will return a {@link MucCreateConfigFormHandle} if the room creation was acknowledged by
528
     * the service (with an 201 status code). It's up to the caller to decide, based on the return
529
     * value, if he needs to continue sending the room configuration. If {@code null} is returned, the room
530
     * already existed and the user is able to join right away, without sending a form.
531
     *
532
     * @param mucEnterConfiguration the configuration used to enter the MUC.
533
     * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
534
     * @throws XMPPErrorException if the room couldn't be created for some reason (e.g. 405 error if
535
     *         the user is not allowed to create the room)
536
     * @throws NoResponseException if there was no response from the server.
537
     * @throws InterruptedException if the calling thread was interrupted.
538
     * @throws MucAlreadyJoinedException if the MUC is already joined
539
     * @throws NotConnectedException if the XMPP connection is not connected.
540
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
541
     */
542
    public synchronized MucCreateConfigFormHandle createOrJoin(MucEnterConfiguration mucEnterConfiguration)
543
                    throws NoResponseException, XMPPErrorException, InterruptedException, MucAlreadyJoinedException, NotConnectedException, NotAMucServiceException {
544
        if (isJoined()) {
×
545
            throw new MucAlreadyJoinedException();
×
546
        }
547

548
        Presence presence = enter(mucEnterConfiguration);
×
549

550
        // Look for confirmation of room creation from the server
551
        MUCUser mucUser = MUCUser.from(presence);
×
552
        if (mucUser != null && mucUser.getStatus().contains(Status.ROOM_CREATED_201)) {
×
553
            // Room was created and the user has joined the room
554
            return new MucCreateConfigFormHandle();
×
555
        }
556
        return null;
×
557
    }
558

559
    /**
560
     * A handle used to configure a newly created room. As long as the room is not configured it will be locked, which
561
     * means that no one is able to join. The room will become unlocked as soon it got configured. In order to create an
562
     * instant room, use {@link #makeInstant()}.
563
     * <p>
564
     * For advanced configuration options, use {@link MultiUserChat#getConfigurationForm()}, get the answer form with
565
     * {@link Form#getFillableForm()}, fill it out and send it back to the room with
566
     * {@link MultiUserChat#sendConfigurationForm(FillableForm)}.
567
     * </p>
568
     */
569
    public class MucCreateConfigFormHandle {
×
570

571
        /**
572
         * Create an instant room. The default configuration will be accepted and the room will become unlocked, i.e.
573
         * other users are able to join.
574
         *
575
         * @throws NoResponseException if there was no response from the remote entity.
576
         * @throws XMPPErrorException if there was an XMPP error returned.
577
         * @throws NotConnectedException if the XMPP connection is not connected.
578
         * @throws InterruptedException if the calling thread was interrupted.
579
         * @see <a href="http://www.xmpp.org/extensions/xep-0045.html#createroom-instant">XEP-45 § 10.1.2 Creating an
580
         *      Instant Room</a>
581
         */
582
        public void makeInstant() throws NoResponseException, XMPPErrorException, NotConnectedException,
583
                        InterruptedException {
584
            sendConfigurationForm(null);
×
585
        }
×
586

587
        /**
588
         * Alias for {@link MultiUserChat#getConfigFormManager()}.
589
         *
590
         * @return a MUC configuration form manager for this room.
591
         * @throws NoResponseException if there was no response from the remote entity.
592
         * @throws XMPPErrorException if there was an XMPP error returned.
593
         * @throws NotConnectedException if the XMPP connection is not connected.
594
         * @throws InterruptedException if the calling thread was interrupted.
595
         * @see MultiUserChat#getConfigFormManager()
596
         */
597
        public MucConfigFormManager getConfigFormManager() throws NoResponseException,
598
                        XMPPErrorException, NotConnectedException, InterruptedException {
599
            return MultiUserChat.this.getConfigFormManager();
×
600
        }
601
    }
602

603
    /**
604
     * Create or join a MUC if it is necessary, i.e. if not the MUC is not already joined.
605
     *
606
     * @param nickname the required nickname to use.
607
     * @param password the optional password required to join
608
     * @return A {@link MucCreateConfigFormHandle} if the room was created while joining, or {@code null} if the room was just joined.
609
     * @throws NoResponseException if there was no response from the remote entity.
610
     * @throws XMPPErrorException if there was an XMPP error returned.
611
     * @throws NotConnectedException if the XMPP connection is not connected.
612
     * @throws InterruptedException if the calling thread was interrupted.
613
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
614
     */
615
    public MucCreateConfigFormHandle createOrJoinIfNecessary(Resourcepart nickname, String password) throws NoResponseException,
616
                    XMPPErrorException, NotConnectedException, InterruptedException, NotAMucServiceException {
617
        if (isJoined()) {
×
618
            return null;
×
619
        }
620
        MucEnterConfiguration mucEnterConfiguration = getEnterConfigurationBuilder(nickname).withPassword(
×
621
                        password).build();
×
622
        try {
623
            return createOrJoin(mucEnterConfiguration);
×
624
        }
625
        catch (MucAlreadyJoinedException e) {
×
626
            return null;
×
627
        }
628
    }
629

630
    /**
631
     * Joins the chat room using the specified nickname. If already joined
632
     * using another nickname, this method will first leave the room and then
633
     * re-join using the new nickname. The default connection timeout for a reply
634
     * from the group chat server that the join succeeded will be used. After
635
     * joining the room, the room will decide the amount of history to send.
636
     *
637
     * @param nickname the nickname to use.
638
     * @return the leave self-presence as reflected by the MUC.
639
     * @throws NoResponseException if there was no response from the remote entity.
640
     * @throws XMPPErrorException if an error occurs joining the room. In particular, a
641
     *      401 error can occur if no password was provided and one is required; or a
642
     *      403 error can occur if the user is banned; or a
643
     *      404 error can occur if the room does not exist or is locked; or a
644
     *      407 error can occur if user is not on the member list; or a
645
     *      409 error can occur if someone is already in the group chat with the same nickname.
646
     * @throws NoResponseException if there was no response from the server.
647
     * @throws NotConnectedException if the XMPP connection is not connected.
648
     * @throws InterruptedException if the calling thread was interrupted.
649
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
650
     */
651
    public Presence join(Resourcepart nickname) throws NoResponseException, XMPPErrorException,
652
                    NotConnectedException, InterruptedException, NotAMucServiceException {
653
        MucEnterConfiguration.Builder builder = getEnterConfigurationBuilder(nickname);
×
654
        Presence reflectedJoinPresence = join(builder.build());
×
655
        return reflectedJoinPresence;
×
656
    }
657

658
    /**
659
     * Joins the chat room using the specified nickname and password. If already joined
660
     * using another nickname, this method will first leave the room and then
661
     * re-join using the new nickname. The default connection timeout for a reply
662
     * from the group chat server that the join succeeded will be used. After
663
     * joining the room, the room will decide the amount of history to send.<p>
664
     *
665
     * A password is required when joining password protected rooms. If the room does
666
     * not require a password there is no need to provide one.
667
     *
668
     * @param nickname the nickname to use.
669
     * @param password the password to use.
670
     * @throws XMPPErrorException if an error occurs joining the room. In particular, a
671
     *      401 error can occur if no password was provided and one is required; or a
672
     *      403 error can occur if the user is banned; or a
673
     *      404 error can occur if the room does not exist or is locked; or a
674
     *      407 error can occur if user is not on the member list; or a
675
     *      409 error can occur if someone is already in the group chat with the same nickname.
676
     * @throws InterruptedException if the calling thread was interrupted.
677
     * @throws NotConnectedException if the XMPP connection is not connected.
678
     * @throws NoResponseException if there was no response from the server.
679
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
680
     */
681
    public void join(Resourcepart nickname, String password) throws XMPPErrorException, InterruptedException, NoResponseException, NotConnectedException, NotAMucServiceException {
682
        MucEnterConfiguration.Builder builder = getEnterConfigurationBuilder(nickname).withPassword(
×
683
                        password);
684
        join(builder.build());
×
685
    }
×
686

687
    /**
688
     * Joins the chat room using the specified nickname and password. If already joined
689
     * using another nickname, this method will first leave the room and then
690
     * re-join using the new nickname.<p>
691
     *
692
     * To control the amount of history to receive while joining a room you will need to provide
693
     * a configured DiscussionHistory object.<p>
694
     *
695
     * A password is required when joining password protected rooms. If the room does
696
     * not require a password there is no need to provide one.<p>
697
     *
698
     * If the room does not already exist when the user seeks to enter it, the server will
699
     * decide to create a new room or not.
700
     *
701
     * @param mucEnterConfiguration the configuration used to enter the MUC.
702
     * @return the join self-presence as reflected by the MUC.
703
     * @throws XMPPErrorException if an error occurs joining the room. In particular, a
704
     *      401 error can occur if no password was provided and one is required; or a
705
     *      403 error can occur if the user is banned; or a
706
     *      404 error can occur if the room does not exist or is locked; or a
707
     *      407 error can occur if user is not on the member list; or a
708
     *      409 error can occur if someone is already in the group chat with the same nickname.
709
     * @throws NoResponseException if there was no response from the server.
710
     * @throws NotConnectedException if the XMPP connection is not connected.
711
     * @throws InterruptedException if the calling thread was interrupted.
712
     * @throws NotAMucServiceException if the entity is not a MUC serivce.
713
     */
714
    public synchronized Presence join(MucEnterConfiguration mucEnterConfiguration)
715
        throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException, NotAMucServiceException {
716
        // If we've already joined the room, leave it before joining under a new
717
        // nickname.
718
        if (isJoined()) {
×
719
            try {
720
                leaveSync();
×
721
            }
722
            catch (XMPPErrorException | NoResponseException | MucNotJoinedException e) {
×
723
                LOGGER.log(Level.WARNING, "Could not leave MUC prior joining, assuming we are not joined", e);
×
724
            }
×
725
        }
726
        Presence reflectedJoinPresence = enter(mucEnterConfiguration);
×
727
        return reflectedJoinPresence;
×
728
    }
729

730
    /**
731
     * Returns true if currently in the multi user chat (after calling the {@link
732
     * #join(Resourcepart)} method).
733
     *
734
     * @return true if currently in the multi user chat room.
735
     */
736
    public boolean isJoined() {
737
        return getMyRoomJid() != null;
×
738
    }
739

740
    /**
741
     * Leave the chat room.
742
     *
743
     * @return the leave presence as reflected by the MUC.
744
     * @throws NotConnectedException if the XMPP connection is not connected.
745
     * @throws InterruptedException if the calling thread was interrupted.
746
     * @throws XMPPErrorException if there was an XMPP error returned.
747
     * @throws NoResponseException if there was no response from the remote entity.
748
     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
749
     * @deprecated use {@link #leave()} instead.
750
     */
751
    @Deprecated
752
    // TODO: Remove in Smack 4.5.
753
    public synchronized Presence leaveSync() throws NotConnectedException, InterruptedException, MucNotJoinedException, NoResponseException, XMPPErrorException {
754
        return leave();
×
755
    }
756

757
    /**
758
     * Leave the chat room.
759
     *
760
     * @return the leave presence as reflected by the MUC.
761
     * @throws NotConnectedException if the XMPP connection is not connected.
762
     * @throws InterruptedException if the calling thread was interrupted.
763
     * @throws XMPPErrorException if there was an XMPP error returned.
764
     * @throws NoResponseException if there was no response from the remote entity.
765
     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
766
     */
767
    public synchronized Presence leave()
768
                    throws NotConnectedException, InterruptedException, NoResponseException, XMPPErrorException, MucNotJoinedException {
769
        //  Note that this method is intentionally not guarded by
770
        // "if  (!joined) return" because it should be always be possible to leave the room in case the instance's
771
        // state does not reflect the actual state.
772

773
        final EntityFullJid myRoomJid = getMyRoomJid();
×
774
        if (myRoomJid == null) {
×
775
            throw new MucNotJoinedException(this);
×
776
        }
777

778
        // TODO: Consider adding a origin-id to the presence, once it is moved form smack-experimental into
779
        // smack-extensions, in case the MUC service does not support stable IDs, and modify
780
        // reflectedLeavePresenceFilters accordingly.
781

782
        // We leave a room by sending a presence packet where the "to"
783
        // field is in the form "roomName@service/nickname"
784
        Presence leavePresence = connection.getStanzaFactory().buildPresenceStanza()
×
785
                .ofType(Presence.Type.unavailable)
×
786
                .to(myRoomJid)
×
787
                .build();
×
788

789
        List<StanzaFilter> reflectedLeavePresenceFilters = new ArrayList<>(3);
×
790
        reflectedLeavePresenceFilters.add(StanzaTypeFilter.PRESENCE);
×
791
        reflectedLeavePresenceFilters.add(new OrFilter(
×
792
                        new AndFilter(FromMatchesFilter.createFull(myRoomJid), PresenceTypeFilter.UNAVAILABLE,
×
793
                                        MUCUserStatusCodeFilter.STATUS_110_PRESENCE_TO_SELF),
794
                        new AndFilter(fromRoomFilter, PresenceTypeFilter.ERROR)));
795

796
        if (serviceSupportsStableIds()) {
×
797
            reflectedLeavePresenceFilters.add(new StanzaIdFilter(leavePresence));
×
798
        }
799

800
        StanzaFilter reflectedLeavePresenceFilter = new AndFilter(reflectedLeavePresenceFilters);
×
801

802
        Presence reflectedLeavePresence;
803
        try {
804
            reflectedLeavePresence = connection.createStanzaCollectorAndSend(reflectedLeavePresenceFilter, leavePresence).nextResultOrThrow();
×
805
        } finally {
806
            // Reset occupant information after we send the leave presence. This ensures that we only call userHasLeft()
807
            // and reset the local MUC state after we successfully left the MUC (or if an exception occurred).
808
            userHasLeft();
×
809
        }
810

811
        return reflectedLeavePresence;
×
812
    }
813

814
    /**
815
     * Get a {@link MucConfigFormManager} to configure this room.
816
     * <p>
817
     * Only room owners are able to configure a room.
818
     * </p>
819
     *
820
     * @return a MUC configuration form manager for this room.
821
     * @throws NoResponseException if there was no response from the remote entity.
822
     * @throws XMPPErrorException if there was an XMPP error returned.
823
     * @throws NotConnectedException if the XMPP connection is not connected.
824
     * @throws InterruptedException if the calling thread was interrupted.
825
     * @see <a href="http://xmpp.org/extensions/xep-0045.html#roomconfig">XEP-45 § 10.2 Subsequent Room Configuration</a>
826
     * @since 4.2
827
     */
828
    public MucConfigFormManager getConfigFormManager() throws NoResponseException,
829
                    XMPPErrorException, NotConnectedException, InterruptedException {
830
        return new MucConfigFormManager(this);
×
831
    }
832

833
    /**
834
     * Returns the room's configuration form that the room's owner can use.
835
     * The configuration form allows to set the room's language,
836
     * enable logging, specify room's type, etc..
837
     *
838
     * @return the Form that contains the fields to complete together with the instrucions or
839
     * <code>null</code> if no configuration is possible.
840
     * @throws XMPPErrorException if an error occurs asking the configuration form for the room.
841
     * @throws NoResponseException if there was no response from the server.
842
     * @throws NotConnectedException if the XMPP connection is not connected.
843
     * @throws InterruptedException if the calling thread was interrupted.
844
     */
845
    public Form getConfigurationForm() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
846
        MUCOwner iq = new MUCOwner();
×
847
        iq.setTo(room);
×
848
        iq.setType(IQ.Type.get);
×
849

850
        IQ answer = connection.sendIqRequestAndWaitForResponse(iq);
×
851
        DataForm dataForm = DataForm.from(answer, MucConfigFormManager.FORM_TYPE);
×
852
        return new Form(dataForm);
×
853
    }
854

855
    /**
856
     * Sends the completed configuration form to the server. The room will be configured
857
     * with the new settings defined in the form.
858
     *
859
     * @param form the form with the new settings.
860
     * @throws XMPPErrorException if an error occurs setting the new rooms' configuration.
861
     * @throws NoResponseException if there was no response from the server.
862
     * @throws NotConnectedException if the XMPP connection is not connected.
863
     * @throws InterruptedException if the calling thread was interrupted.
864
     */
865
    public void sendConfigurationForm(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
866
        final DataForm dataForm;
867
        if (form != null) {
×
868
            dataForm = form.getDataFormToSubmit();
×
869
        } else {
870
            // Instant room, cf. XEP-0045 § 10.1.2
871
            dataForm = DataForm.builder().build();
×
872
        }
873

874
        MUCOwner iq = new MUCOwner();
×
875
        iq.setTo(room);
×
876
        iq.setType(IQ.Type.set);
×
877
        iq.addExtension(dataForm);
×
878

879
        connection.sendIqRequestAndWaitForResponse(iq);
×
880
    }
×
881

882
    /**
883
     * Returns the room's registration form that an unaffiliated user, can use to become a member
884
     * of the room or <code>null</code> if no registration is possible. Some rooms may restrict the
885
     * privilege to register members and allow only room admins to add new members.<p>
886
     *
887
     * If the user requesting registration requirements is not allowed to register with the room
888
     * (e.g. because that privilege has been restricted), the room will return a "Not Allowed"
889
     * error to the user (error code 405).
890
     *
891
     * @return the registration Form that contains the fields to complete together with the
892
     * instrucions or <code>null</code> if no registration is possible.
893
     * @throws XMPPErrorException if an error occurs asking the registration form for the room or a
894
     * 405 error if the user is not allowed to register with the room.
895
     * @throws NoResponseException if there was no response from the server.
896
     * @throws NotConnectedException if the XMPP connection is not connected.
897
     * @throws InterruptedException if the calling thread was interrupted.
898
     */
899
    public Form getRegistrationForm() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
900
        Registration reg = new Registration();
×
901
        reg.setType(IQ.Type.get);
×
902
        reg.setTo(room);
×
903

904
        IQ result = connection.sendIqRequestAndWaitForResponse(reg);
×
905
        DataForm dataForm = DataForm.from(result);
×
906
        return new Form(dataForm);
×
907
    }
908

909
    /**
910
     * Sends the completed registration form to the server. After the user successfully submits
911
     * the form, the room may queue the request for review by the room admins or may immediately
912
     * add the user to the member list by changing the user's affiliation from "none" to "member.<p>
913
     *
914
     * If the desired room nickname is already reserved for that room, the room will return a
915
     * "Conflict" error to the user (error code 409). If the room does not support registration,
916
     * it will return a "Service Unavailable" error to the user (error code 503).
917
     *
918
     * @param form the completed registration form.
919
     * @throws XMPPErrorException if an error occurs submitting the registration form. In particular, a
920
     *      409 error can occur if the desired room nickname is already reserved for that room;
921
     *      or a 503 error can occur if the room does not support registration.
922
     * @throws NoResponseException if there was no response from the server.
923
     * @throws NotConnectedException if the XMPP connection is not connected.
924
     * @throws InterruptedException if the calling thread was interrupted.
925
     */
926
    public void sendRegistrationForm(FillableForm form) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
927
        Registration reg = new Registration();
×
928
        reg.setType(IQ.Type.set);
×
929
        reg.setTo(room);
×
930
        reg.addExtension(form.getDataFormToSubmit());
×
931

932
        connection.sendIqRequestAndWaitForResponse(reg);
×
933
    }
×
934

935
    /**
936
     * Sends a request to destroy the room.
937
     *
938
     * @throws XMPPErrorException if an error occurs while trying to destroy the room.
939
     *      An error can occur which will be wrapped by an XMPPException --
940
     *      XMPP error code 403. The error code can be used to present more
941
     *      appropriate error messages to end-users.
942
     * @throws NoResponseException if there was no response from the server.
943
     * @throws NotConnectedException if the XMPP connection is not connected.
944
     * @throws InterruptedException if the calling thread was interrupted.
945
     * @see #destroy(String, EntityBareJid)
946
     * @since 4.5
947
     */
948
    public void destroy() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
949
        destroy(null, null);
×
950
    }
×
951

952
    /**
953
     * Sends a request to the server to destroy the room. The sender of the request
954
     * should be the room's owner. If the sender of the destroy request is not the room's owner
955
     * then the server will answer a "Forbidden" error (403).
956
     *
957
     * @param reason an optional reason for the room destruction.
958
     * @param alternateJID an optional JID of an alternate location.
959
     * @throws XMPPErrorException if an error occurs while trying to destroy the room.
960
     *      An error can occur which will be wrapped by an XMPPException --
961
     *      XMPP error code 403. The error code can be used to present more
962
     *      appropriate error messages to end-users.
963
     * @throws NoResponseException if there was no response from the server.
964
     * @throws NotConnectedException if the XMPP connection is not connected.
965
     * @throws InterruptedException if the calling thread was interrupted.
966
     */
967
    public void destroy(String reason, EntityBareJid alternateJID) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
NEW
968
        destroy(reason, alternateJID, null);
×
NEW
969
    }
×
970

971
    /**
972
     * Sends a request to the server to destroy the room. The sender of the request
973
     * should be the room's owner. If the sender of the destroy request is not the room's owner
974
     * then the server will answer a "Forbidden" error (403).
975
     *
976
     * @param reason an optional reason for the room destruction.
977
     * @param alternateJID an optional JID of an alternate location.
978
     * @param password an optional password for the alternate location
979
     * @throws XMPPErrorException if an error occurs while trying to destroy the room.
980
     *      An error can occur which will be wrapped by an XMPPException --
981
     *      XMPP error code 403. The error code can be used to present more
982
     *      appropriate error messages to end-users.
983
     * @throws NoResponseException if there was no response from the server.
984
     * @throws NotConnectedException if the XMPP connection is not connected.
985
     * @throws InterruptedException if the calling thread was interrupted.
986
     */
987
    public void destroy(String reason, EntityBareJid alternateJID, String password) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
988
        MUCOwner iq = new MUCOwner();
×
989
        iq.setTo(room);
×
990
        iq.setType(IQ.Type.set);
×
991

992
        // Create the reason for the room destruction
NEW
993
        Destroy destroy = new Destroy(alternateJID, password, reason);
×
994
        iq.setDestroy(destroy);
×
995

996
        try {
997
            connection.sendIqRequestAndWaitForResponse(iq);
×
998
        }
999
        catch (XMPPErrorException e) {
×
1000
            // Note that we do not call userHasLeft() here because an XMPPErrorException would usually indicate that the
1001
            // room was not destroyed and we therefore we also did not leave the room.
1002
            throw e;
×
1003
        }
1004
        catch (NoResponseException | NotConnectedException | InterruptedException e) {
×
1005
            // Reset occupant information.
1006
            userHasLeft();
×
1007
            throw e;
×
1008
        }
×
1009

1010
        // Reset occupant information.
1011
        userHasLeft();
×
1012
    }
×
1013

1014
    /**
1015
     * Invites another user to the room in which one is an occupant. The invitation
1016
     * will be sent to the room which in turn will forward the invitation to the invitee.<p>
1017
     *
1018
     * If the room is password-protected, the invitee will receive a password to use to join
1019
     * the room. If the room is members-only, the invitee may be added to the member list.
1020
     *
1021
     * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
1022
     * @param reason the reason why the user is being invited.
1023
     * @throws NotConnectedException if the XMPP connection is not connected.
1024
     * @throws InterruptedException if the calling thread was interrupted.
1025
     */
1026
    public void invite(EntityBareJid user, String reason) throws NotConnectedException, InterruptedException {
1027
        invite(connection.getStanzaFactory().buildMessageStanza(), user, reason);
×
1028
    }
×
1029

1030
    /**
1031
     * Invites another user to the room in which one is an occupant using a given Message. The invitation
1032
     * will be sent to the room which in turn will forward the invitation to the invitee.<p>
1033
     *
1034
     * If the room is password-protected, the invitee will receive a password to use to join
1035
     * the room. If the room is members-only, the invitee may be added to the member list.
1036
     *
1037
     * @param message the message to use for sending the invitation.
1038
     * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
1039
     * @param reason the reason why the user is being invited.
1040
     * @throws NotConnectedException if the XMPP connection is not connected.
1041
     * @throws InterruptedException if the calling thread was interrupted.
1042
     * @deprecated use {@link #invite(MessageBuilder, EntityBareJid, String)} instead.
1043
     */
1044
    @Deprecated
1045
    // TODO: Remove in Smack 4.5.
1046
    public void invite(Message message, EntityBareJid user, String reason) throws NotConnectedException, InterruptedException {
1047
        // TODO listen for 404 error code when inviter supplies a non-existent JID
1048
        message.setTo(room);
×
1049

1050
        // Create the MUCUser packet that will include the invitation
1051
        MUCUser mucUser = new MUCUser();
×
1052
        MUCUser.Invite invite = new MUCUser.Invite(reason, user);
×
1053
        mucUser.setInvite(invite);
×
1054
        // Add the MUCUser packet that includes the invitation to the message
1055
        message.addExtension(mucUser);
×
1056

1057
        connection.sendStanza(message);
×
1058
    }
×
1059

1060
    /**
1061
     * Invites another user to the room in which one is an occupant using a given Message. The invitation
1062
     * will be sent to the room which in turn will forward the invitation to the invitee.<p>
1063
     *
1064
     * If the room is password-protected, the invitee will receive a password to use to join
1065
     * the room. If the room is members-only, the invitee may be added to the member list.
1066
     *
1067
     * @param messageBuilder the message to use for sending the invitation.
1068
     * @param user the user to invite to the room.(e.g. hecate@shakespeare.lit)
1069
     * @param reason the reason why the user is being invited.
1070
     * @throws NotConnectedException if the XMPP connection is not connected.
1071
     * @throws InterruptedException if the calling thread was interrupted.
1072
     */
1073
    public void invite(MessageBuilder messageBuilder, EntityBareJid user, String reason) throws NotConnectedException, InterruptedException {
1074
        // TODO listen for 404 error code when inviter supplies a non-existent JID
1075
        messageBuilder.to(room);
×
1076

1077
        // Create the MUCUser packet that will include the invitation
1078
        MUCUser mucUser = new MUCUser();
×
1079
        MUCUser.Invite invite = new MUCUser.Invite(reason, user);
×
1080
        mucUser.setInvite(invite);
×
1081
        // Add the MUCUser packet that includes the invitation to the message
1082
        messageBuilder.addExtension(mucUser);
×
1083

1084
        Message message = messageBuilder.build();
×
1085
        connection.sendStanza(message);
×
1086
    }
×
1087

1088
    /**
1089
     * Invites another user to the room in which one is an occupant. In contrast
1090
     * to the method "invite", the invitation is sent directly to the user rather
1091
     * than via the chat room.  This is useful when the user being invited is
1092
     * offline, as otherwise the invitation would be dropped.
1093
     *
1094
     * @param address the user to send the invitation to
1095
     * @throws NotConnectedException if the XMPP connection is not connected.
1096
     * @throws InterruptedException if the calling thread was interrupted.
1097
     */
1098
    public void inviteDirectly(EntityBareJid address) throws NotConnectedException, InterruptedException {
1099
        inviteDirectly(address, null, null, false, null);
1✔
1100
    }
1✔
1101

1102
     /**
1103
     * Invites another user to the room in which one is an occupant. In contrast
1104
     * to the method "invite", the invitation is sent directly to the user rather
1105
     * than via the chat room.  This is useful when the user being invited is
1106
     * offline, as otherwise the invitation would be dropped.
1107
     *
1108
     * @param address the user to send the invitation to
1109
     * @param reason the purpose for the invitation
1110
     * @param password specifies a password needed for entry
1111
     * @param continueAsOneToOneChat specifies if the groupchat room continues a one-to-one chat having the designated thread
1112
     * @param thread the thread to continue
1113
     * @throws NotConnectedException if the XMPP connection is not connected.
1114
     * @throws InterruptedException if the calling thread was interrupted.
1115
     */
1116
    public void inviteDirectly(EntityBareJid address, String reason, String password, boolean continueAsOneToOneChat, String thread)
1117
        throws NotConnectedException, InterruptedException {
1118
        // Add the extension for direct invitation
1119
        GroupChatInvitation invitationExt = new GroupChatInvitation(room,
1✔
1120
                                                                    reason,
1121
                                                                    password,
1122
                                                                    continueAsOneToOneChat,
1123
                                                                    thread);
1124

1125
        Message message = connection.getStanzaFactory().buildMessageStanza()
1✔
1126
                .to(address)
1✔
1127
                .addExtension(invitationExt)
1✔
1128
                .build();
1✔
1129

1130
        connection.sendStanza(message);
1✔
1131
    }
1✔
1132

1133
    /**
1134
     * Adds a listener to invitation rejections notifications. The listener will be fired anytime
1135
     * an invitation is declined.
1136
     *
1137
     * @param listener an invitation rejection listener.
1138
     * @return true if the listener was not already added.
1139
     */
1140
    public boolean addInvitationRejectionListener(InvitationRejectionListener listener) {
1141
         return invitationRejectionListeners.add(listener);
×
1142
    }
1143

1144
    /**
1145
     * Removes a listener from invitation rejections notifications. The listener will be fired
1146
     * anytime an invitation is declined.
1147
     *
1148
     * @param listener an invitation rejection listener.
1149
     * @return true if the listener was registered and is now removed.
1150
     */
1151
    public boolean removeInvitationRejectionListener(InvitationRejectionListener listener) {
1152
        return invitationRejectionListeners.remove(listener);
×
1153
    }
1154

1155
    /**
1156
     * Fires invitation rejection listeners.
1157
     *
1158
     * @param message the message.
1159
     * @param rejection the information about the rejection.
1160
     */
1161
    private void fireInvitationRejectionListeners(Message message, MUCUser.Decline rejection) {
1162
        EntityBareJid invitee = rejection.getFrom();
×
1163
        String reason = rejection.getReason();
×
1164
        InvitationRejectionListener[] listeners;
1165
        synchronized (invitationRejectionListeners) {
×
1166
            listeners = new InvitationRejectionListener[invitationRejectionListeners.size()];
×
1167
            invitationRejectionListeners.toArray(listeners);
×
1168
        }
×
1169
        for (InvitationRejectionListener listener : listeners) {
×
1170
            listener.invitationDeclined(invitee, reason, message, rejection);
×
1171
        }
1172
    }
×
1173

1174
    /**
1175
     * Adds a listener to subject change notifications. The listener will be fired anytime
1176
     * the room's subject changes.
1177
     *
1178
     * @param listener a subject updated listener.
1179
     * @return true if the listener was not already added.
1180
     */
1181
    public boolean addSubjectUpdatedListener(SubjectUpdatedListener listener) {
1182
        return subjectUpdatedListeners.add(listener);
×
1183
    }
1184

1185
    /**
1186
     * Removes a listener from subject change notifications. The listener will be fired
1187
     * anytime the room's subject changes.
1188
     *
1189
     * @param listener a subject updated listener.
1190
     * @return true if the listener was registered and is now removed.
1191
     */
1192
    public boolean removeSubjectUpdatedListener(SubjectUpdatedListener listener) {
1193
        return subjectUpdatedListeners.remove(listener);
×
1194
    }
1195

1196
    /**
1197
     * Adds a new {@link StanzaListener} that will be invoked every time a new presence
1198
     * is going to be sent by this MultiUserChat to the server. Stanza interceptors may
1199
     * add new extensions to the presence that is going to be sent to the MUC service.
1200
     *
1201
     * @param presenceInterceptor the new stanza interceptor that will intercept presence packets.
1202
     */
1203
    public void addPresenceInterceptor(Consumer<PresenceBuilder> presenceInterceptor) {
1204
        boolean added = presenceInterceptors.add(presenceInterceptor);
×
1205
        if (!added) return;
×
1206
        int currentCount = presenceInterceptorCount.incrementAndGet();
×
1207
        if (currentCount == 1) {
×
1208
            connection.addPresenceInterceptor(this.presenceInterceptor, ToMatchesFilter.create(room).asPredicate(Presence.class));
×
1209
        }
1210
    }
×
1211

1212
    /**
1213
     * Removes a {@link StanzaListener} that was being invoked every time a new presence
1214
     * was being sent by this MultiUserChat to the server. Stanza interceptors may
1215
     * add new extensions to the presence that is going to be sent to the MUC service.
1216
     *
1217
     * @param presenceInterceptor the stanza interceptor to remove.
1218
     */
1219
    public void removePresenceInterceptor(Consumer<PresenceBuilder> presenceInterceptor) {
1220
        boolean removed = presenceInterceptors.remove(presenceInterceptor);
×
1221
        if (!removed) return;
×
1222
        int currentCount = presenceInterceptorCount.decrementAndGet();
×
1223
        if (currentCount == 0) {
×
1224
            connection.removePresenceInterceptor(this.presenceInterceptor);
×
1225
        }
1226
    }
×
1227

1228
    /**
1229
     * Returns the last known room's subject or <code>null</code> if the user hasn't joined the room
1230
     * or the room does not have a subject yet. In case the room has a subject, as soon as the
1231
     * user joins the room a message with the current room's subject will be received.<p>
1232
     *
1233
     * To be notified every time the room's subject change you should add a listener
1234
     * to this room. {@link #addSubjectUpdatedListener(SubjectUpdatedListener)}<p>
1235
     *
1236
     * To change the room's subject use {@link #changeSubject(String)}.
1237
     *
1238
     * @return the room's subject or <code>null</code> if the user hasn't joined the room or the
1239
     * room does not have a subject yet.
1240
     */
1241
    public String getSubject() {
1242
        return subject;
×
1243
    }
1244

1245
    /**
1246
     * Returns the reserved room nickname for the user in the room. A user may have a reserved
1247
     * nickname, for example through explicit room registration or database integration. In such
1248
     * cases it may be desirable for the user to discover the reserved nickname before attempting
1249
     * to enter the room.
1250
     *
1251
     * @return the reserved room nickname or <code>null</code> if none.
1252
     * @throws SmackException if there was no response from the server.
1253
     * @throws InterruptedException if the calling thread was interrupted.
1254
     */
1255
    public String getReservedNickname() throws SmackException, InterruptedException {
1256
        try {
1257
            DiscoverInfo result =
×
1258
                ServiceDiscoveryManager.getInstanceFor(connection).discoverInfo(
×
1259
                    room,
1260
                    "x-roomuser-item");
1261
            // Look for an Identity that holds the reserved nickname and return its name
1262
            for (DiscoverInfo.Identity identity : result.getIdentities()) {
×
1263
                return identity.getName();
×
1264
            }
1265
        }
1266
        catch (XMPPException e) {
×
1267
            LOGGER.log(Level.SEVERE, "Error retrieving room nickname", e);
×
1268
        }
×
1269
        // If no Identity was found then the user does not have a reserved room nickname
1270
        return null;
×
1271
    }
1272

1273
    /**
1274
     * Returns the nickname that was used to join the room, or <code>null</code> if not
1275
     * currently joined.
1276
     *
1277
     * @return the nickname currently being used.
1278
     */
1279
    public Resourcepart getNickname() {
1280
        final EntityFullJid myRoomJid = getMyRoomJid();
×
1281
        if (myRoomJid == null) {
×
1282
            return null;
×
1283
        }
1284
        return myRoomJid.getResourcepart();
×
1285
    }
1286

1287
    /**
1288
     * Return the full JID of the user in the room, or <code>null</code> if the room is not joined.
1289
     *
1290
     * @return the full JID of the user in the room, or <code>null</code>.
1291
     * @since 4.5.0
1292
     */
1293
    public EntityFullJid getMyRoomJid() {
1294
        return myRoomJid;
×
1295
    }
1296

1297
    private static final Object changeNicknameLock = new Object();
1✔
1298

1299
    /**
1300
     * Changes the occupant's nickname to a new nickname within the room. Each room occupant
1301
     * will receive two presence packets. One of type "unavailable" for the old nickname and one
1302
     * indicating availability for the new nickname. The unavailable presence will contain the new
1303
     * nickname and an appropriate status code (namely 303) as extended presence information. The
1304
     * status code 303 indicates that the occupant is changing his/her nickname.
1305
     *
1306
     * @param nickname the new nickname within the room.
1307
     * @throws XMPPErrorException if the new nickname is already in use by another occupant.
1308
     * @throws NoResponseException if there was no response from the server.
1309
     * @throws NotConnectedException if the XMPP connection is not connected.
1310
     * @throws InterruptedException if the calling thread was interrupted.
1311
     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
1312
     */
1313
    public void changeNickname(Resourcepart nickname) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException, MucNotJoinedException  {
1314
        Objects.requireNonNull(nickname, "Nickname must not be null or blank.");
×
1315
        // Check that we already have joined the room before attempting to change the
1316
        // nickname.
1317
        if (!isJoined()) {
×
1318
            throw new MucNotJoinedException(this);
×
1319
        }
1320
        final EntityFullJid jid = JidCreate.entityFullFrom(room, nickname);
×
1321
        // We change the nickname by sending a presence packet where the "to"
1322
        // field is in the form "roomName@service/nickname"
1323
        // We don't have to signal the MUC support again
1324
        Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza()
×
1325
                .to(jid)
×
1326
                .ofType(Presence.Type.available)
×
1327
                .build();
×
1328

1329
        synchronized (changeNicknameLock) {
×
1330
            // Wait for a presence packet back from the server.
1331
            StanzaFilter responseFilter =
×
1332
                new AndFilter(
1333
                   FromMatchesFilter.createFull(jid),
×
1334
                   new StanzaTypeFilter(Presence.class));
1335
            StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, joinPresence);
×
1336
            // Wait up to a certain number of seconds for a reply. If there is a negative reply, an
1337
            // exception will be thrown
1338
            response.nextResultOrThrow();
×
1339

1340
            // TODO: Shouldn't this handle nickname rewriting by the MUC service?
1341
            setNickname(nickname);
×
1342
        }
×
1343
    }
×
1344

1345
    /**
1346
     * Changes the occupant's availability status within the room. The presence type
1347
     * will remain available but with a new status that describes the presence update and
1348
     * a new presence mode (e.g. Extended away).
1349
     *
1350
     * @param status a text message describing the presence update.
1351
     * @param mode the mode type for the presence update.
1352
     * @throws NotConnectedException if the XMPP connection is not connected.
1353
     * @throws InterruptedException if the calling thread was interrupted.
1354
     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
1355
     */
1356
    public void changeAvailabilityStatus(String status, Presence.Mode mode) throws NotConnectedException, InterruptedException, MucNotJoinedException {
1357
        final EntityFullJid myRoomJid = getMyRoomJid();
×
1358
        if (myRoomJid == null) {
×
1359
            throw new MucNotJoinedException(this);
×
1360
        }
1361

1362
        // We change the availability status by sending a presence packet to the room with the
1363
        // new presence status and mode
1364
        Presence joinPresence = connection.getStanzaFactory().buildPresenceStanza()
×
1365
                .to(myRoomJid)
×
1366
                .ofType(Presence.Type.available)
×
1367
                .setStatus(status)
×
1368
                .setMode(mode)
×
1369
                .build();
×
1370

1371
        // Send join packet.
1372
        connection.sendStanza(joinPresence);
×
1373
    }
×
1374

1375
    /**
1376
     * Kicks a visitor or participant from the room. The kicked occupant will receive a presence
1377
     * of type "unavailable" including a status code 307 and optionally along with the reason
1378
     * (if provided) and the bare JID of the user who initiated the kick. After the occupant
1379
     * was kicked from the room, the rest of the occupants will receive a presence of type
1380
     * "unavailable". The presence will include a status code 307 which means that the occupant
1381
     * was kicked from the room.
1382
     *
1383
     * @param nickname the nickname of the participant or visitor to kick from the room
1384
     * (e.g. "john").
1385
     * @param reason the reason why the participant or visitor is being kicked from the room.
1386
     * @throws XMPPErrorException if an error occurs kicking the occupant. In particular, a
1387
     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1388
     *      was intended to be kicked (i.e. Not Allowed error); or a
1389
     *      403 error can occur if the occupant that intended to kick another occupant does
1390
     *      not have kicking privileges (i.e. Forbidden error); or a
1391
     *      400 error can occur if the provided nickname is not present in the room.
1392
     * @throws NoResponseException if there was no response from the server.
1393
     * @throws NotConnectedException if the XMPP connection is not connected.
1394
     * @throws InterruptedException if the calling thread was interrupted.
1395
     */
1396
    public void kickParticipant(Resourcepart nickname, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1397
        changeRole(nickname, MUCRole.none, reason);
×
1398
    }
×
1399

1400
    /**
1401
     * Sends a voice request to the MUC. The room moderators usually need to approve this request.
1402
     *
1403
     * @throws NotConnectedException if the XMPP connection is not connected.
1404
     * @throws InterruptedException if the calling thread was interrupted.
1405
     * @see <a href="http://xmpp.org/extensions/xep-0045.html#requestvoice">XEP-45 § 7.13 Requesting
1406
     *      Voice</a>
1407
     * @since 4.1
1408
     */
1409
    public void requestVoice() throws NotConnectedException, InterruptedException {
1410
        DataForm.Builder form = DataForm.builder()
×
1411
                        .setFormType(MUCInitialPresence.NAMESPACE + "#request");
×
1412

1413
        TextSingleFormField.Builder requestVoiceField = FormField.textSingleBuilder("muc#role");
×
1414
        requestVoiceField.setLabel("Requested role");
×
1415
        requestVoiceField.setValue("participant");
×
1416
        form.addField(requestVoiceField.build());
×
1417

1418
        Message message = connection.getStanzaFactory().buildMessageStanza()
×
1419
                .to(room)
×
1420
                .addExtension(form.build())
×
1421
                .build();
×
1422
        connection.sendStanza(message);
×
1423
    }
×
1424

1425
    /**
1426
     * Grants voice to visitors in the room. In a moderated room, a moderator may want to manage
1427
     * who does and does not have "voice" in the room. To have voice means that a room occupant
1428
     * is able to send messages to the room occupants.
1429
     *
1430
     * @param nicknames the nicknames of the visitors to grant voice in the room (e.g. "john").
1431
     * @throws XMPPErrorException if an error occurs granting voice to a visitor. In particular, a
1432
     *      403 error can occur if the occupant that intended to grant voice is not
1433
     *      a moderator in this room (i.e. Forbidden error); or a
1434
     *      400 error can occur if the provided nickname is not present in the room.
1435
     * @throws NoResponseException if there was no response from the server.
1436
     * @throws NotConnectedException if the XMPP connection is not connected.
1437
     * @throws InterruptedException if the calling thread was interrupted.
1438
     */
1439
    public void grantVoice(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1440
        changeRole(nicknames, MUCRole.participant);
×
1441
    }
×
1442

1443
    /**
1444
     * Grants voice to a visitor in the room. In a moderated room, a moderator may want to manage
1445
     * who does and does not have "voice" in the room. To have voice means that a room occupant
1446
     * is able to send messages to the room occupants.
1447
     *
1448
     * @param nickname the nickname of the visitor to grant voice in the room (e.g. "john").
1449
     * @throws XMPPErrorException if an error occurs granting voice to a visitor. In particular, a
1450
     *      403 error can occur if the occupant that intended to grant voice is not
1451
     *      a moderator in this room (i.e. Forbidden error); or a
1452
     *      400 error can occur if the provided nickname is not present in the room.
1453
     * @throws NoResponseException if there was no response from the server.
1454
     * @throws NotConnectedException if the XMPP connection is not connected.
1455
     * @throws InterruptedException if the calling thread was interrupted.
1456
     */
1457
    public void grantVoice(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1458
        changeRole(nickname, MUCRole.participant, null);
×
1459
    }
×
1460

1461
    /**
1462
     * Revokes voice from participants in the room. In a moderated room, a moderator may want to
1463
     * revoke an occupant's privileges to speak. To have voice means that a room occupant
1464
     * is able to send messages to the room occupants.
1465
     *
1466
     * @param nicknames the nicknames of the participants to revoke voice (e.g. "john").
1467
     * @throws XMPPErrorException if an error occurs revoking voice from a participant. In particular, a
1468
     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1469
     *      was tried to revoke his voice (i.e. Not Allowed error); or a
1470
     *      400 error can occur if the provided nickname is not present in the room.
1471
     * @throws NoResponseException if there was no response from the server.
1472
     * @throws NotConnectedException if the XMPP connection is not connected.
1473
     * @throws InterruptedException if the calling thread was interrupted.
1474
     */
1475
    public void revokeVoice(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1476
        changeRole(nicknames, MUCRole.visitor);
×
1477
    }
×
1478

1479
    /**
1480
     * Revokes voice from a participant in the room. In a moderated room, a moderator may want to
1481
     * revoke an occupant's privileges to speak. To have voice means that a room occupant
1482
     * is able to send messages to the room occupants.
1483
     *
1484
     * @param nickname the nickname of the participant to revoke voice (e.g. "john").
1485
     * @throws XMPPErrorException if an error occurs revoking voice from a participant. In particular, a
1486
     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1487
     *      was tried to revoke his voice (i.e. Not Allowed error); or a
1488
     *      400 error can occur if the provided nickname is not present in the room.
1489
     * @throws NoResponseException if there was no response from the server.
1490
     * @throws NotConnectedException if the XMPP connection is not connected.
1491
     * @throws InterruptedException if the calling thread was interrupted.
1492
     */
1493
    public void revokeVoice(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1494
        changeRole(nickname, MUCRole.visitor, null);
×
1495
    }
×
1496

1497
    /**
1498
     * Bans users from the room. An admin or owner of the room can ban users from a room. This
1499
     * means that the banned user will no longer be able to join the room unless the ban has been
1500
     * removed. If the banned user was present in the room then he/she will be removed from the
1501
     * room and notified that he/she was banned along with the reason (if provided) and the bare
1502
     * XMPP user ID of the user who initiated the ban.
1503
     *
1504
     * @param jids the bare XMPP user IDs of the users to ban.
1505
     * @throws XMPPErrorException if an error occurs banning a user. In particular, a
1506
     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1507
     *      was tried to be banned (i.e. Not Allowed error).
1508
     * @throws NoResponseException if there was no response from the server.
1509
     * @throws NotConnectedException if the XMPP connection is not connected.
1510
     * @throws InterruptedException if the calling thread was interrupted.
1511
     */
1512
    public void banUsers(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1513
        changeAffiliationByAdmin(jids, MUCAffiliation.outcast);
×
1514
    }
×
1515

1516
    /**
1517
     * Bans a user from the room. An admin or owner of the room can ban users from a room. This
1518
     * means that the banned user will no longer be able to join the room unless the ban has been
1519
     * removed. If the banned user was present in the room then he/she will be removed from the
1520
     * room and notified that he/she was banned along with the reason (if provided) and the bare
1521
     * XMPP user ID of the user who initiated the ban.
1522
     *
1523
     * @param jid the bare XMPP user ID of the user to ban (e.g. "user@host.org").
1524
     * @param reason the optional reason why the user was banned.
1525
     * @throws XMPPErrorException if an error occurs banning a user. In particular, a
1526
     *      405 error can occur if a moderator or a user with an affiliation of "owner" or "admin"
1527
     *      was tried to be banned (i.e. Not Allowed error).
1528
     * @throws NoResponseException if there was no response from the server.
1529
     * @throws NotConnectedException if the XMPP connection is not connected.
1530
     * @throws InterruptedException if the calling thread was interrupted.
1531
     */
1532
    public void banUser(Jid jid, String reason) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1533
        changeAffiliationByAdmin(jid, MUCAffiliation.outcast, reason);
×
1534
    }
×
1535

1536
    /**
1537
     * Grants membership to other users. Only administrators are able to grant membership. A user
1538
     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1539
     * that a user cannot enter without being on the member list).
1540
     *
1541
     * @param jids the XMPP user IDs of the users to grant membership.
1542
     * @throws XMPPErrorException if an error occurs granting membership to a user.
1543
     * @throws NoResponseException if there was no response from the server.
1544
     * @throws NotConnectedException if the XMPP connection is not connected.
1545
     * @throws InterruptedException if the calling thread was interrupted.
1546
     */
1547
    public void grantMembership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1548
        changeAffiliationByAdmin(jids, MUCAffiliation.member);
×
1549
    }
×
1550

1551
    /**
1552
     * Grants membership to a user. Only administrators are able to grant membership. A user
1553
     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1554
     * that a user cannot enter without being on the member list).
1555
     *
1556
     * @param jid the XMPP user ID of the user to grant membership (e.g. "user@host.org").
1557
     * @throws XMPPErrorException if an error occurs granting membership to a user.
1558
     * @throws NoResponseException if there was no response from the server.
1559
     * @throws NotConnectedException if the XMPP connection is not connected.
1560
     * @throws InterruptedException if the calling thread was interrupted.
1561
     */
1562
    public void grantMembership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1563
        changeAffiliationByAdmin(jid, MUCAffiliation.member, null);
×
1564
    }
×
1565

1566
    /**
1567
     * Revokes users' membership. Only administrators are able to revoke membership. A user
1568
     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1569
     * that a user cannot enter without being on the member list). If the user is in the room and
1570
     * the room is of type members-only then the user will be removed from the room.
1571
     *
1572
     * @param jids the bare XMPP user IDs of the users to revoke membership.
1573
     * @throws XMPPErrorException if an error occurs revoking membership to a user.
1574
     * @throws NoResponseException if there was no response from the server.
1575
     * @throws NotConnectedException if the XMPP connection is not connected.
1576
     * @throws InterruptedException if the calling thread was interrupted.
1577
     */
1578
    public void revokeMembership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1579
        changeAffiliationByAdmin(jids, MUCAffiliation.none);
×
1580
    }
×
1581

1582
    /**
1583
     * Revokes a user's membership. Only administrators are able to revoke membership. A user
1584
     * that becomes a room member will be able to enter a room of type Members-Only (i.e. a room
1585
     * that a user cannot enter without being on the member list). If the user is in the room and
1586
     * the room is of type members-only then the user will be removed from the room.
1587
     *
1588
     * @param jid the bare XMPP user ID of the user to revoke membership (e.g. "user@host.org").
1589
     * @throws XMPPErrorException if an error occurs revoking membership to a user.
1590
     * @throws NoResponseException if there was no response from the server.
1591
     * @throws NotConnectedException if the XMPP connection is not connected.
1592
     * @throws InterruptedException if the calling thread was interrupted.
1593
     */
1594
    public void revokeMembership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1595
        changeAffiliationByAdmin(jid, MUCAffiliation.none, null);
×
1596
    }
×
1597

1598
    /**
1599
     * Grants moderator privileges to participants or visitors. Room administrators may grant
1600
     * moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite
1601
     * other users, modify room's subject plus all the partcipants privileges.
1602
     *
1603
     * @param nicknames the nicknames of the occupants to grant moderator privileges.
1604
     * @throws XMPPErrorException if an error occurs granting moderator privileges to a user.
1605
     * @throws NoResponseException if there was no response from the server.
1606
     * @throws NotConnectedException if the XMPP connection is not connected.
1607
     * @throws InterruptedException if the calling thread was interrupted.
1608
     */
1609
    public void grantModerator(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1610
        changeRole(nicknames, MUCRole.moderator);
×
1611
    }
×
1612

1613
    /**
1614
     * Grants moderator privileges to a participant or visitor. Room administrators may grant
1615
     * moderator privileges. A moderator is allowed to kick users, grant and revoke voice, invite
1616
     * other users, modify room's subject plus all the partcipants privileges.
1617
     *
1618
     * @param nickname the nickname of the occupant to grant moderator privileges.
1619
     * @throws XMPPErrorException if an error occurs granting moderator privileges to a user.
1620
     * @throws NoResponseException if there was no response from the server.
1621
     * @throws NotConnectedException if the XMPP connection is not connected.
1622
     * @throws InterruptedException if the calling thread was interrupted.
1623
     */
1624
    public void grantModerator(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1625
        changeRole(nickname, MUCRole.moderator, null);
×
1626
    }
×
1627

1628
    /**
1629
     * Revokes moderator privileges from other users. The occupant that loses moderator
1630
     * privileges will become a participant. Room administrators may revoke moderator privileges
1631
     * only to occupants whose affiliation is member or none. This means that an administrator is
1632
     * not allowed to revoke moderator privileges from other room administrators or owners.
1633
     *
1634
     * @param nicknames the nicknames of the occupants to revoke moderator privileges.
1635
     * @throws XMPPErrorException if an error occurs revoking moderator privileges from a user.
1636
     * @throws NoResponseException if there was no response from the server.
1637
     * @throws NotConnectedException if the XMPP connection is not connected.
1638
     * @throws InterruptedException if the calling thread was interrupted.
1639
     */
1640
    public void revokeModerator(Collection<Resourcepart> nicknames) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1641
        changeRole(nicknames, MUCRole.participant);
×
1642
    }
×
1643

1644
    /**
1645
     * Revokes moderator privileges from another user. The occupant that loses moderator
1646
     * privileges will become a participant. Room administrators may revoke moderator privileges
1647
     * only to occupants whose affiliation is member or none. This means that an administrator is
1648
     * not allowed to revoke moderator privileges from other room administrators or owners.
1649
     *
1650
     * @param nickname the nickname of the occupant to revoke moderator privileges.
1651
     * @throws XMPPErrorException if an error occurs revoking moderator privileges from a user.
1652
     * @throws NoResponseException if there was no response from the server.
1653
     * @throws NotConnectedException if the XMPP connection is not connected.
1654
     * @throws InterruptedException if the calling thread was interrupted.
1655
     */
1656
    public void revokeModerator(Resourcepart nickname) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1657
        changeRole(nickname, MUCRole.participant, null);
×
1658
    }
×
1659

1660
    /**
1661
     * Grants ownership privileges to other users. Room owners may grant ownership privileges.
1662
     * Some room implementations will not allow to grant ownership privileges to other users.
1663
     * An owner is allowed to change defining room features as well as perform all administrative
1664
     * functions.
1665
     *
1666
     * @param jids the collection of bare XMPP user IDs of the users to grant ownership.
1667
     * @throws XMPPErrorException if an error occurs granting ownership privileges to a user.
1668
     * @throws NoResponseException if there was no response from the server.
1669
     * @throws NotConnectedException if the XMPP connection is not connected.
1670
     * @throws InterruptedException if the calling thread was interrupted.
1671
     */
1672
    public void grantOwnership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1673
        changeAffiliationByAdmin(jids, MUCAffiliation.owner);
×
1674
    }
×
1675

1676
    /**
1677
     * Grants ownership privileges to another user. Room owners may grant ownership privileges.
1678
     * Some room implementations will not allow to grant ownership privileges to other users.
1679
     * An owner is allowed to change defining room features as well as perform all administrative
1680
     * functions.
1681
     *
1682
     * @param jid the bare XMPP user ID of the user to grant ownership (e.g. "user@host.org").
1683
     * @throws XMPPErrorException if an error occurs granting ownership privileges to a user.
1684
     * @throws NoResponseException if there was no response from the server.
1685
     * @throws NotConnectedException if the XMPP connection is not connected.
1686
     * @throws InterruptedException if the calling thread was interrupted.
1687
     */
1688
    public void grantOwnership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1689
        changeAffiliationByAdmin(jid, MUCAffiliation.owner, null);
×
1690
    }
×
1691

1692
    /**
1693
     * Revokes ownership privileges from other users. The occupant that loses ownership
1694
     * privileges will become an administrator. Room owners may revoke ownership privileges.
1695
     * Some room implementations will not allow to grant ownership privileges to other users.
1696
     *
1697
     * @param jids the bare XMPP user IDs of the users to revoke ownership.
1698
     * @throws XMPPErrorException if an error occurs revoking ownership privileges from a user.
1699
     * @throws NoResponseException if there was no response from the server.
1700
     * @throws NotConnectedException if the XMPP connection is not connected.
1701
     * @throws InterruptedException if the calling thread was interrupted.
1702
     */
1703
    public void revokeOwnership(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1704
        changeAffiliationByAdmin(jids, MUCAffiliation.admin);
×
1705
    }
×
1706

1707
    /**
1708
     * Revokes ownership privileges from another user. The occupant that loses ownership
1709
     * privileges will become an administrator. Room owners may revoke ownership privileges.
1710
     * Some room implementations will not allow to grant ownership privileges to other users.
1711
     *
1712
     * @param jid the bare XMPP user ID of the user to revoke ownership (e.g. "user@host.org").
1713
     * @throws XMPPErrorException if an error occurs revoking ownership privileges from a user.
1714
     * @throws NoResponseException if there was no response from the server.
1715
     * @throws NotConnectedException if the XMPP connection is not connected.
1716
     * @throws InterruptedException if the calling thread was interrupted.
1717
     */
1718
    public void revokeOwnership(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1719
        changeAffiliationByAdmin(jid, MUCAffiliation.admin, null);
×
1720
    }
×
1721

1722
    /**
1723
     * Grants administrator privileges to other users. Room owners may grant administrator
1724
     * privileges to a member or unaffiliated user. An administrator is allowed to perform
1725
     * administrative functions such as banning users and edit moderator list.
1726
     *
1727
     * @param jids the bare XMPP user IDs of the users to grant administrator privileges.
1728
     * @throws XMPPErrorException if an error occurs granting administrator privileges to a user.
1729
     * @throws NoResponseException if there was no response from the server.
1730
     * @throws NotConnectedException if the XMPP connection is not connected.
1731
     * @throws InterruptedException if the calling thread was interrupted.
1732
     */
1733
    public void grantAdmin(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1734
        changeAffiliationByAdmin(jids, MUCAffiliation.admin);
×
1735
    }
×
1736

1737
    /**
1738
     * Grants administrator privileges to another user. Room owners may grant administrator
1739
     * privileges to a member or unaffiliated user. An administrator is allowed to perform
1740
     * administrative functions such as banning users and edit moderator list.
1741
     *
1742
     * @param jid the bare XMPP user ID of the user to grant administrator privileges
1743
     * (e.g. "user@host.org").
1744
     * @throws XMPPErrorException if an error occurs granting administrator privileges to a user.
1745
     * @throws NoResponseException if there was no response from the server.
1746
     * @throws NotConnectedException if the XMPP connection is not connected.
1747
     * @throws InterruptedException if the calling thread was interrupted.
1748
     */
1749
    public void grantAdmin(Jid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1750
        changeAffiliationByAdmin(jid, MUCAffiliation.admin);
×
1751
    }
×
1752

1753
    /**
1754
     * Revokes administrator privileges from users. The occupant that loses administrator
1755
     * privileges will become a member. Room owners may revoke administrator privileges from
1756
     * a member or unaffiliated user.
1757
     *
1758
     * @param jids the bare XMPP user IDs of the user to revoke administrator privileges.
1759
     * @throws XMPPErrorException if an error occurs revoking administrator privileges from a user.
1760
     * @throws NoResponseException if there was no response from the server.
1761
     * @throws NotConnectedException if the XMPP connection is not connected.
1762
     * @throws InterruptedException if the calling thread was interrupted.
1763
     */
1764
    public void revokeAdmin(Collection<? extends Jid> jids) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1765
        changeAffiliationByAdmin(jids, MUCAffiliation.admin);
×
1766
    }
×
1767

1768
    /**
1769
     * Revokes administrator privileges from a user. The occupant that loses administrator
1770
     * privileges will become a member. Room owners may revoke administrator privileges from
1771
     * a member or unaffiliated user.
1772
     *
1773
     * @param jid the bare XMPP user ID of the user to revoke administrator privileges
1774
     * (e.g. "user@host.org").
1775
     * @throws XMPPErrorException if an error occurs revoking administrator privileges from a user.
1776
     * @throws NoResponseException if there was no response from the server.
1777
     * @throws NotConnectedException if the XMPP connection is not connected.
1778
     * @throws InterruptedException if the calling thread was interrupted.
1779
     */
1780
    public void revokeAdmin(EntityJid jid) throws XMPPErrorException, NoResponseException, NotConnectedException, InterruptedException {
1781
        changeAffiliationByAdmin(jid, MUCAffiliation.member);
×
1782
    }
×
1783

1784
    /**
1785
     * Tries to change the affiliation with an 'muc#admin' namespace
1786
     *
1787
     * @param jid TODO javadoc me please
1788
     * @param affiliation TODO javadoc me please
1789
     * @throws XMPPErrorException if there was an XMPP error returned.
1790
     * @throws NoResponseException if there was no response from the remote entity.
1791
     * @throws NotConnectedException if the XMPP connection is not connected.
1792
     * @throws InterruptedException if the calling thread was interrupted.
1793
     */
1794
    private void changeAffiliationByAdmin(Jid jid, MUCAffiliation affiliation)
1795
                    throws NoResponseException, XMPPErrorException,
1796
                    NotConnectedException, InterruptedException {
1797
        changeAffiliationByAdmin(jid, affiliation, null);
×
1798
    }
×
1799

1800
    /**
1801
     * Tries to change the affiliation with an 'muc#admin' namespace
1802
     *
1803
     * @param jid TODO javadoc me please
1804
     * @param affiliation TODO javadoc me please
1805
     * @param reason the reason for the affiliation change (optional)
1806
     * @throws XMPPErrorException if there was an XMPP error returned.
1807
     * @throws NoResponseException if there was no response from the remote entity.
1808
     * @throws NotConnectedException if the XMPP connection is not connected.
1809
     * @throws InterruptedException if the calling thread was interrupted.
1810
     */
1811
    private void changeAffiliationByAdmin(Jid jid, MUCAffiliation affiliation, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1812
        MUCAdmin iq = new MUCAdmin();
×
1813
        iq.setTo(room);
×
1814
        iq.setType(IQ.Type.set);
×
1815
        // Set the new affiliation.
1816
        MUCItem item = new MUCItem(affiliation, jid, reason);
×
1817
        iq.addItem(item);
×
1818

1819
        connection.sendIqRequestAndWaitForResponse(iq);
×
1820
    }
×
1821

1822
    private void changeAffiliationByAdmin(Collection<? extends Jid> jids, MUCAffiliation affiliation)
1823
                    throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1824
        MUCAdmin iq = new MUCAdmin();
×
1825
        iq.setTo(room);
×
1826
        iq.setType(IQ.Type.set);
×
1827
        for (Jid jid : jids) {
×
1828
            // Set the new affiliation.
1829
            MUCItem item = new MUCItem(affiliation, jid);
×
1830
            iq.addItem(item);
×
1831
        }
×
1832

1833
        connection.sendIqRequestAndWaitForResponse(iq);
×
1834
    }
×
1835

1836
    private void changeRole(Resourcepart nickname, MUCRole role, String reason) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1837
        MUCAdmin iq = new MUCAdmin();
×
1838
        iq.setTo(room);
×
1839
        iq.setType(IQ.Type.set);
×
1840
        // Set the new role.
1841
        MUCItem item = new MUCItem(role, nickname, reason);
×
1842
        iq.addItem(item);
×
1843

1844
        connection.sendIqRequestAndWaitForResponse(iq);
×
1845
    }
×
1846

1847
    private void changeRole(Collection<Resourcepart> nicknames, MUCRole role) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException  {
1848
        MUCAdmin iq = new MUCAdmin();
×
1849
        iq.setTo(room);
×
1850
        iq.setType(IQ.Type.set);
×
1851
        for (Resourcepart nickname : nicknames) {
×
1852
            // Set the new role.
1853
            MUCItem item = new MUCItem(role, nickname);
×
1854
            iq.addItem(item);
×
1855
        }
×
1856

1857
        connection.sendIqRequestAndWaitForResponse(iq);
×
1858
    }
×
1859

1860
    /**
1861
     * Returns the number of occupants in the group chat.<p>
1862
     *
1863
     * Note: this value will only be accurate after joining the group chat, and
1864
     * may fluctuate over time. If you query this value directly after joining the
1865
     * group chat it may not be accurate, as it takes a certain amount of time for
1866
     * the server to send all presence packets to this client.
1867
     *
1868
     * @return the number of occupants in the group chat.
1869
     */
1870
    public int getOccupantsCount() {
1871
        return occupantsMap.size();
×
1872
    }
1873

1874
    /**
1875
     * Returns an List  for the list of fully qualified occupants
1876
     * in the group chat. For example, "conference@chat.jivesoftware.com/SomeUser".
1877
     * Typically, a client would only display the nickname of the occupant. To
1878
     * get the nickname from the fully qualified name, use the
1879
     * {@link org.jxmpp.util.XmppStringUtils#parseResource(String)} method.
1880
     * Note: this value will only be accurate after joining the group chat, and may
1881
     * fluctuate over time.
1882
     *
1883
     * @return a List of the occupants in the group chat.
1884
     */
1885
    public List<EntityFullJid> getOccupants() {
1886
        return new ArrayList<>(occupantsMap.keySet());
×
1887
    }
1888

1889
    /**
1890
     * Returns the presence info for a particular user, or <code>null</code> if the user
1891
     * is not in the room.<p>
1892
     *
1893
     * @param user the room occupant to search for his presence. The format of user must
1894
     * be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch).
1895
     * @return the occupant's current presence, or <code>null</code> if the user is unavailable
1896
     *      or if no presence information is available.
1897
     */
1898
    public Presence getOccupantPresence(EntityFullJid user) {
1899
        return occupantsMap.get(user);
×
1900
    }
1901

1902
    /**
1903
     * Returns the Occupant information for a particular occupant, or <code>null</code> if the
1904
     * user is not in the room. The Occupant object may include information such as full
1905
     * JID of the user as well as the role and affiliation of the user in the room.<p>
1906
     *
1907
     * @param user the room occupant to search for his presence. The format of user must
1908
     * be: roomName@service/nickname (e.g. darkcave@macbeth.shakespeare.lit/thirdwitch).
1909
     * @return the Occupant or <code>null</code> if the user is unavailable (i.e. not in the room).
1910
     */
1911
    public Occupant getOccupant(EntityFullJid user) {
1912
        Presence presence = getOccupantPresence(user);
×
1913
        if (presence != null) {
×
1914
            return new Occupant(presence);
×
1915
        }
1916
        return null;
×
1917
    }
1918

1919
    /**
1920
     * Adds a stanza listener that will be notified of any new Presence packets
1921
     * sent to the group chat. Using a listener is a suitable way to know when the list
1922
     * of occupants should be re-loaded due to any changes.
1923
     *
1924
     * @param listener a stanza listener that will be notified of any presence packets
1925
     *      sent to the group chat.
1926
     * @return true if the listener was not already added.
1927
     */
1928
    public boolean addParticipantListener(PresenceListener listener) {
1929
        return presenceListeners.add(listener);
×
1930
    }
1931

1932
    /**
1933
     * Removes a stanza listener that was being notified of any new Presence packets
1934
     * sent to the group chat.
1935
     *
1936
     * @param listener a stanza listener that was being notified of any presence packets
1937
     *      sent to the group chat.
1938
     * @return true if the listener was removed, otherwise the listener was not added previously.
1939
     */
1940
    public boolean removeParticipantListener(PresenceListener listener) {
1941
        return presenceListeners.remove(listener);
×
1942
    }
1943

1944
    /**
1945
     * Returns a list of <code>Affiliate</code> with the room owners.
1946
     *
1947
     * @return a list of <code>Affiliate</code> with the room owners.
1948
     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1949
     * @throws NoResponseException if there was no response from the server.
1950
     * @throws NotConnectedException if the XMPP connection is not connected.
1951
     * @throws InterruptedException if the calling thread was interrupted.
1952
     */
1953
    public List<Affiliate> getOwners() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1954
        return getAffiliatesByAdmin(MUCAffiliation.owner);
×
1955
    }
1956

1957
    /**
1958
     * Returns a list of <code>Affiliate</code> with the room administrators.
1959
     *
1960
     * @return a list of <code>Affiliate</code> with the room administrators.
1961
     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1962
     * @throws NoResponseException if there was no response from the server.
1963
     * @throws NotConnectedException if the XMPP connection is not connected.
1964
     * @throws InterruptedException if the calling thread was interrupted.
1965
     */
1966
    public List<Affiliate> getAdmins() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1967
        return getAffiliatesByAdmin(MUCAffiliation.admin);
×
1968
    }
1969

1970
    /**
1971
     * Returns a list of <code>Affiliate</code> with the room members.
1972
     *
1973
     * @return a list of <code>Affiliate</code> with the room members.
1974
     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1975
     * @throws NoResponseException if there was no response from the server.
1976
     * @throws NotConnectedException if the XMPP connection is not connected.
1977
     * @throws InterruptedException if the calling thread was interrupted.
1978
     */
1979
    public List<Affiliate> getMembers() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException  {
1980
        return getAffiliatesByAdmin(MUCAffiliation.member);
×
1981
    }
1982

1983
    /**
1984
     * Returns a list of <code>Affiliate</code> with the room outcasts.
1985
     *
1986
     * @return a list of <code>Affiliate</code> with the room outcasts.
1987
     * @throws XMPPErrorException if you don't have enough privileges to get this information.
1988
     * @throws NoResponseException if there was no response from the server.
1989
     * @throws NotConnectedException if the XMPP connection is not connected.
1990
     * @throws InterruptedException if the calling thread was interrupted.
1991
     */
1992
    public List<Affiliate> getOutcasts() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
1993
        return getAffiliatesByAdmin(MUCAffiliation.outcast);
×
1994
    }
1995

1996
    /**
1997
     * Returns a collection of <code>Affiliate</code> that have the specified room affiliation
1998
     * sending a request in the admin namespace.
1999
     *
2000
     * @param affiliation the affiliation of the users in the room.
2001
     * @return a collection of <code>Affiliate</code> that have the specified room affiliation.
2002
     * @throws XMPPErrorException if you don't have enough privileges to get this information.
2003
     * @throws NoResponseException if there was no response from the server.
2004
     * @throws NotConnectedException if the XMPP connection is not connected.
2005
     * @throws InterruptedException if the calling thread was interrupted.
2006
     */
2007
    private List<Affiliate> getAffiliatesByAdmin(MUCAffiliation affiliation) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
2008
        MUCAdmin iq = new MUCAdmin();
×
2009
        iq.setTo(room);
×
2010
        iq.setType(IQ.Type.get);
×
2011
        // Set the specified affiliation. This may request the list of owners/admins/members/outcasts.
2012
        MUCItem item = new MUCItem(affiliation);
×
2013
        iq.addItem(item);
×
2014

2015
        MUCAdmin answer = (MUCAdmin) connection.sendIqRequestAndWaitForResponse(iq);
×
2016

2017
        // Get the list of affiliates from the server's answer
2018
        List<Affiliate> affiliates = new ArrayList<Affiliate>();
×
2019
        for (MUCItem mucadminItem : answer.getItems()) {
×
2020
            affiliates.add(new Affiliate(mucadminItem));
×
2021
        }
×
2022
        return affiliates;
×
2023
    }
2024

2025
    /**
2026
     * Returns a list of <code>Occupant</code> with the room moderators.
2027
     *
2028
     * @return a list of <code>Occupant</code> with the room moderators.
2029
     * @throws XMPPErrorException if you don't have enough privileges to get this information.
2030
     * @throws NoResponseException if there was no response from the server.
2031
     * @throws NotConnectedException if the XMPP connection is not connected.
2032
     * @throws InterruptedException if the calling thread was interrupted.
2033
     */
2034
    public List<Occupant> getModerators() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
2035
        return getOccupants(MUCRole.moderator);
×
2036
    }
2037

2038
    /**
2039
     * Returns a list of <code>Occupant</code> with the room participants.
2040
     *
2041
     * @return a list of <code>Occupant</code> with the room participants.
2042
     * @throws XMPPErrorException if you don't have enough privileges to get this information.
2043
     * @throws NoResponseException if there was no response from the server.
2044
     * @throws NotConnectedException if the XMPP connection is not connected.
2045
     * @throws InterruptedException if the calling thread was interrupted.
2046
     */
2047
    public List<Occupant> getParticipants() throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
2048
        return getOccupants(MUCRole.participant);
×
2049
    }
2050

2051
    /**
2052
     * Returns a list of <code>Occupant</code> that have the specified room role.
2053
     *
2054
     * @param role the role of the occupant in the room.
2055
     * @return a list of <code>Occupant</code> that have the specified room role.
2056
     * @throws XMPPErrorException if an error occurred while performing the request to the server or you
2057
     *         don't have enough privileges to get this information.
2058
     * @throws NoResponseException if there was no response from the server.
2059
     * @throws NotConnectedException if the XMPP connection is not connected.
2060
     * @throws InterruptedException if the calling thread was interrupted.
2061
     */
2062
    private List<Occupant> getOccupants(MUCRole role) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
2063
        MUCAdmin iq = new MUCAdmin();
×
2064
        iq.setTo(room);
×
2065
        iq.setType(IQ.Type.get);
×
2066
        // Set the specified role. This may request the list of moderators/participants.
2067
        MUCItem item = new MUCItem(role);
×
2068
        iq.addItem(item);
×
2069

2070
        MUCAdmin answer = (MUCAdmin) connection.sendIqRequestAndWaitForResponse(iq);
×
2071
        // Get the list of participants from the server's answer
2072
        List<Occupant> participants = new ArrayList<Occupant>();
×
2073
        for (MUCItem mucadminItem : answer.getItems()) {
×
2074
            participants.add(new Occupant(mucadminItem));
×
2075
        }
×
2076
        return participants;
×
2077
    }
2078

2079
    /**
2080
     * Sends a message to the chat room.
2081
     *
2082
     * @param text the text of the message to send.
2083
     * @throws NotConnectedException if the XMPP connection is not connected.
2084
     * @throws InterruptedException if the calling thread was interrupted.
2085
     */
2086
    public void sendMessage(String text) throws NotConnectedException, InterruptedException {
2087
        Message message = buildMessage()
×
2088
                .setBody(text)
×
2089
                .build();
×
2090
        connection.sendStanza(message);
×
2091
    }
×
2092

2093
    /**
2094
     * Returns a new Chat for sending private messages to a given room occupant.
2095
     * The Chat's occupant address is the room's JID (i.e. roomName@service/nick). The server
2096
     * service will change the 'from' address to the sender's room JID and delivering the message
2097
     * to the intended recipient's full JID.
2098
     *
2099
     * @param occupant occupant unique room JID (e.g. 'darkcave@macbeth.shakespeare.lit/Paul').
2100
     * @param listener the listener is a message listener that will handle messages for the newly
2101
     * created chat.
2102
     * @return new Chat for sending private messages to a given room occupant.
2103
     */
2104
    // 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.
2105
    // API sketch: PrivateMucChat createPrivateChat(Resourcepart nick)
2106
    @SuppressWarnings("deprecation")
2107
    public org.jivesoftware.smack.chat.Chat createPrivateChat(EntityFullJid occupant, ChatMessageListener listener) {
2108
        return org.jivesoftware.smack.chat.ChatManager.getInstanceFor(connection).createChat(occupant, listener);
×
2109
    }
2110

2111
    /**
2112
     * Creates a new Message to send to the chat room.
2113
     *
2114
     * @return a new Message addressed to the chat room.
2115
     * @deprecated use {@link #buildMessage()} instead.
2116
     */
2117
    @Deprecated
2118
    // TODO: Remove when stanza builder is ready.
2119
    public Message createMessage() {
2120
        return connection.getStanzaFactory().buildMessageStanza()
×
2121
                .ofType(Message.Type.groupchat)
×
2122
                .to(room)
×
2123
                .build();
×
2124
    }
2125

2126
    /**
2127
     * Constructs a new message builder for messages send to this MUC room.
2128
     *
2129
     * @return a new message builder.
2130
     */
2131
    public MessageBuilder buildMessage() {
2132
        return connection.getStanzaFactory()
×
2133
                .buildMessageStanza()
×
2134
                .ofType(Message.Type.groupchat)
×
2135
                .to(room)
×
2136
                ;
2137
    }
2138

2139
    /**
2140
     * Sends a Message to the chat room.
2141
     *
2142
     * @param message the message.
2143
     * @throws NotConnectedException if the XMPP connection is not connected.
2144
     * @throws InterruptedException if the calling thread was interrupted.
2145
     * @deprecated use {@link #sendMessage(MessageBuilder)} instead.
2146
     */
2147
    @Deprecated
2148
    // TODO: Remove in Smack 4.5.
2149
    public void sendMessage(Message message) throws NotConnectedException, InterruptedException {
2150
        sendMessage(message.asBuilder());
×
2151
    }
×
2152

2153
    /**
2154
     * Sends a Message to the chat room.
2155
     *
2156
     * @param messageBuilder the message.
2157
     * @return a read-only view of the send message.
2158
     * @throws NotConnectedException if the XMPP connection is not connected.
2159
     * @throws InterruptedException if the calling thread was interrupted.
2160
     */
2161
    public MessageView sendMessage(MessageBuilder messageBuilder) throws NotConnectedException, InterruptedException {
2162
        for (MucMessageInterceptor interceptor : messageInterceptors) {
×
2163
            interceptor.intercept(messageBuilder, this);
×
2164
        }
×
2165

2166
        Message message = messageBuilder.to(room).ofType(Message.Type.groupchat).build();
×
2167
        connection.sendStanza(message);
×
2168
        return message;
×
2169
    }
2170

2171
    /**
2172
    * Polls for and returns the next message, or <code>null</code> if there isn't
2173
    * a message immediately available. This method provides significantly different
2174
    * functionalty than the {@link #nextMessage()} method since it's non-blocking.
2175
    * In other words, the method call will always return immediately, whereas the
2176
    * nextMessage method will return only when a message is available (or after
2177
    * a specific timeout).
2178
    *
2179
    * @return the next message if one is immediately available and
2180
    *      <code>null</code> otherwise.
2181
     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
2182
    */
2183
    public Message pollMessage() throws MucNotJoinedException {
2184
        if (messageCollector == null) {
×
2185
            throw new MucNotJoinedException(this);
×
2186
        }
2187
        return messageCollector.pollResult();
×
2188
    }
2189

2190
    /**
2191
     * Returns the next available message in the chat. The method call will block
2192
     * (not return) until a message is available.
2193
     *
2194
     * @return the next message.
2195
     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
2196
     * @throws InterruptedException if the calling thread was interrupted.
2197
     */
2198
    public Message nextMessage() throws MucNotJoinedException, InterruptedException {
2199
        if (messageCollector == null) {
×
2200
            throw new MucNotJoinedException(this);
×
2201
        }
2202
        return  messageCollector.nextResultBlockForever();
×
2203
    }
2204

2205
    /**
2206
     * Returns the next available message in the chat. The method call will block
2207
     * (not return) until a stanza is available or the <code>timeout</code> has elapased.
2208
     * If the timeout elapses without a result, <code>null</code> will be returned.
2209
     *
2210
     * @param timeout the maximum amount of time to wait for the next message.
2211
     * @return the next message, or <code>null</code> if the timeout elapses without a
2212
     *      message becoming available.
2213
     * @throws MucNotJoinedException if not joined to the Multi-User Chat.
2214
     * @throws InterruptedException if the calling thread was interrupted.
2215
     */
2216
    public Message nextMessage(long timeout) throws MucNotJoinedException, InterruptedException {
2217
        if (messageCollector == null) {
×
2218
            throw new MucNotJoinedException(this);
×
2219
        }
2220
        return messageCollector.nextResult(timeout);
×
2221
    }
2222

2223
    /**
2224
     * Adds a stanza listener that will be notified of any new messages in the
2225
     * group chat. Only "group chat" messages addressed to this group chat will
2226
     * be delivered to the listener. If you wish to listen for other packets
2227
     * that may be associated with this group chat, you should register a
2228
     * PacketListener directly with the XMPPConnection with the appropriate
2229
     * PacketListener.
2230
     *
2231
     * @param listener a stanza listener.
2232
     * @return true if the listener was not already added.
2233
     */
2234
    public boolean addMessageListener(MessageListener listener) {
2235
        return messageListeners.add(listener);
×
2236
    }
2237

2238
    /**
2239
     * Removes a stanza listener that was being notified of any new messages in the
2240
     * multi user chat. Only "group chat" messages addressed to this multi user chat were
2241
     * being delivered to the listener.
2242
     *
2243
     * @param listener a stanza listener.
2244
     * @return true if the listener was removed, otherwise the listener was not added previously.
2245
     */
2246
    public boolean removeMessageListener(MessageListener listener) {
2247
        return messageListeners.remove(listener);
×
2248
    }
2249

2250
    public boolean addMessageInterceptor(MucMessageInterceptor interceptor) {
2251
        return messageInterceptors.add(interceptor);
×
2252
    }
2253

2254
    public boolean removeMessageInterceptor(MucMessageInterceptor interceptor) {
2255
        return messageInterceptors.remove(interceptor);
×
2256
    }
2257

2258
    /**
2259
     * Changes the subject within the room. As a default, only users with a role of "moderator"
2260
     * are allowed to change the subject in a room. Although some rooms may be configured to
2261
     * allow a mere participant or even a visitor to change the subject.
2262
     *
2263
     * @param subject the new room's subject to set.
2264
     * @throws XMPPErrorException if someone without appropriate privileges attempts to change the
2265
     *          room subject will throw an error with code 403 (i.e. Forbidden)
2266
     * @throws NoResponseException if there was no response from the server.
2267
     * @throws NotConnectedException if the XMPP connection is not connected.
2268
     * @throws InterruptedException if the calling thread was interrupted.
2269
     */
2270
    public void changeSubject(final String subject) throws NoResponseException, XMPPErrorException, NotConnectedException, InterruptedException {
2271
        Message message = buildMessage()
×
2272
                        .setSubject(subject)
×
2273
                        .build();
×
2274
        // Wait for an error or confirmation message back from the server.
2275
        StanzaFilter successFilter = new AndFilter(fromRoomGroupchatFilter, new StanzaFilter() {
×
2276
            @Override
2277
            public boolean accept(Stanza packet) {
2278
                Message msg = (Message) packet;
×
2279
                return subject.equals(msg.getSubject());
×
2280
            }
2281
        });
2282
        StanzaFilter errorFilter = new AndFilter(fromRoomFilter, new StanzaIdFilter(message), MessageTypeFilter.ERROR);
×
2283
        StanzaFilter responseFilter = new OrFilter(successFilter, errorFilter);
×
2284
        StanzaCollector response = connection.createStanzaCollectorAndSend(responseFilter, message);
×
2285
        // Wait up to a certain number of seconds for a reply.
2286
        response.nextResultOrThrow();
×
2287
    }
×
2288

2289
    /**
2290
     * Remove the connection callbacks (PacketListener, PacketInterceptor, StanzaCollector) used by this MUC from the
2291
     * connection.
2292
     */
2293
    private void removeConnectionCallbacks() {
2294
        connection.removeStanzaListener(messageListener);
×
2295
        connection.removeStanzaListener(presenceListener);
×
2296
        connection.removeStanzaListener(subjectListener);
×
2297
        connection.removeStanzaListener(declinesListener);
×
2298
        connection.removePresenceInterceptor(presenceInterceptor);
×
2299
        if (messageCollector != null) {
×
2300
            messageCollector.cancel();
×
2301
            messageCollector = null;
×
2302
        }
2303
    }
×
2304

2305
    /**
2306
     * Remove all callbacks and resources necessary when the user has left the room for some reason.
2307
     */
2308
    private synchronized void userHasLeft() {
2309
        occupantsMap.clear();
×
2310
        myRoomJid = null;
×
2311
        // Update the list of joined rooms
2312
        multiUserChatManager.removeJoinedRoom(room);
×
2313
        removeConnectionCallbacks();
×
2314
    }
×
2315

2316
    /**
2317
     * Adds a listener that will be notified of changes in your status in the room
2318
     * such as the user being kicked, banned, or granted admin permissions.
2319
     *
2320
     * @param listener a user status listener.
2321
     * @return true if the user status listener was not already added.
2322
     */
2323
    public boolean addUserStatusListener(UserStatusListener listener) {
2324
        return userStatusListeners.add(listener);
×
2325
    }
2326

2327
    /**
2328
     * Removes a listener that was being notified of changes in your status in the room
2329
     * such as the user being kicked, banned, or granted admin permissions.
2330
     *
2331
     * @param listener a user status listener.
2332
     * @return true if the listener was registered and is now removed.
2333
     */
2334
    public boolean removeUserStatusListener(UserStatusListener listener) {
2335
        return userStatusListeners.remove(listener);
×
2336
    }
2337

2338
    /**
2339
     * Adds a listener that will be notified of changes in occupants status in the room
2340
     * such as the user being kicked, banned, or granted admin permissions.
2341
     *
2342
     * @param listener a participant status listener.
2343
     * @return true if the listener was not already added.
2344
     */
2345
    public boolean addParticipantStatusListener(ParticipantStatusListener listener) {
2346
        return participantStatusListeners.add(listener);
×
2347
    }
2348

2349
    /**
2350
     * Removes a listener that was being notified of changes in occupants status in the room
2351
     * such as the user being kicked, banned, or granted admin permissions.
2352
     *
2353
     * @param listener a participant status listener.
2354
     * @return true if the listener was registered and is now removed.
2355
     */
2356
    public boolean removeParticipantStatusListener(ParticipantStatusListener listener) {
2357
        return participantStatusListeners.remove(listener);
×
2358
    }
2359

2360
    /**
2361
     * Fires notification events if the role of a room occupant has changed. If the occupant that
2362
     * changed his role is your occupant then the <code>UserStatusListeners</code> added to this
2363
     * <code>MultiUserChat</code> will be fired. On the other hand, if the occupant that changed
2364
     * his role is not yours then the <code>ParticipantStatusListeners</code> added to this
2365
     * <code>MultiUserChat</code> will be fired. The following table shows the events that will
2366
     * be fired depending on the previous and new role of the occupant.
2367
     *
2368
     * <pre>
2369
     * <table border="1">
2370
     * <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr>
2371
     *
2372
     * <tr><td>None</td><td>Visitor</td><td>--</td></tr>
2373
     * <tr><td>Visitor</td><td>Participant</td><td>voiceGranted</td></tr>
2374
     * <tr><td>Participant</td><td>Moderator</td><td>moderatorGranted</td></tr>
2375
     *
2376
     * <tr><td>None</td><td>Participant</td><td>voiceGranted</td></tr>
2377
     * <tr><td>None</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr>
2378
     * <tr><td>Visitor</td><td>Moderator</td><td>voiceGranted + moderatorGranted</td></tr>
2379
     *
2380
     * <tr><td>Moderator</td><td>Participant</td><td>moderatorRevoked</td></tr>
2381
     * <tr><td>Participant</td><td>Visitor</td><td>voiceRevoked</td></tr>
2382
     * <tr><td>Visitor</td><td>None</td><td>kicked</td></tr>
2383
     *
2384
     * <tr><td>Moderator</td><td>Visitor</td><td>voiceRevoked + moderatorRevoked</td></tr>
2385
     * <tr><td>Moderator</td><td>None</td><td>kicked</td></tr>
2386
     * <tr><td>Participant</td><td>None</td><td>kicked</td></tr>
2387
     * </table>
2388
     * </pre>
2389
     *
2390
     * @param oldRole the previous role of the user in the room before receiving the new presence
2391
     * @param newRole the new role of the user in the room after receiving the new presence
2392
     * @param isUserModification whether the received presence is about your user in the room or not
2393
     * @param from the occupant whose role in the room has changed
2394
     * (e.g. room@conference.jabber.org/nick).
2395
     */
2396
    private void checkRoleModifications(
2397
        MUCRole oldRole,
2398
        MUCRole newRole,
2399
        boolean isUserModification,
2400
        EntityFullJid from) {
2401
        // Voice was granted to a visitor
2402
        if ((MUCRole.visitor.equals(oldRole) || MUCRole.none.equals(oldRole))
×
2403
            && MUCRole.participant.equals(newRole)) {
×
2404
            if (isUserModification) {
×
2405
                for (UserStatusListener listener : userStatusListeners) {
×
2406
                    listener.voiceGranted();
×
2407
                }
×
2408
            }
2409
            else {
2410
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2411
                    listener.voiceGranted(from);
×
2412
                }
×
2413
            }
2414
        }
2415
        // The participant's voice was revoked from the room
2416
        else if (
×
2417
            MUCRole.participant.equals(oldRole)
×
2418
                && (MUCRole.visitor.equals(newRole) || MUCRole.none.equals(newRole))) {
×
2419
            if (isUserModification) {
×
2420
                for (UserStatusListener listener : userStatusListeners) {
×
2421
                    listener.voiceRevoked();
×
2422
                }
×
2423
            }
2424
            else {
2425
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2426
                    listener.voiceRevoked(from);
×
2427
                }
×
2428
            }
2429
        }
2430
        // Moderator privileges were granted to a participant
2431
        if (!MUCRole.moderator.equals(oldRole) && MUCRole.moderator.equals(newRole)) {
×
2432
            if (MUCRole.visitor.equals(oldRole) || MUCRole.none.equals(oldRole)) {
×
2433
                if (isUserModification) {
×
2434
                    for (UserStatusListener listener : userStatusListeners) {
×
2435
                        listener.voiceGranted();
×
2436
                    }
×
2437
                }
2438
                else {
2439
                    for (ParticipantStatusListener listener : participantStatusListeners) {
×
2440
                        listener.voiceGranted(from);
×
2441
                    }
×
2442
                }
2443
            }
2444
            if (isUserModification) {
×
2445
                for (UserStatusListener listener : userStatusListeners) {
×
2446
                    listener.moderatorGranted();
×
2447
                }
×
2448
            }
2449
            else {
2450
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2451
                    listener.moderatorGranted(from);
×
2452
                }
×
2453
            }
2454
        }
2455
        // Moderator privileges were revoked from a participant
2456
        else if (MUCRole.moderator.equals(oldRole) && !MUCRole.moderator.equals(newRole)) {
×
2457
            if (MUCRole.visitor.equals(newRole) || MUCRole.none.equals(newRole)) {
×
2458
                if (isUserModification) {
×
2459
                    for (UserStatusListener listener : userStatusListeners) {
×
2460
                        listener.voiceRevoked();
×
2461
                    }
×
2462
                }
2463
                else {
2464
                    for (ParticipantStatusListener listener : participantStatusListeners) {
×
2465
                        listener.voiceRevoked(from);
×
2466
                    }
×
2467
                }
2468
            }
2469
            if (isUserModification) {
×
2470
                for (UserStatusListener listener : userStatusListeners) {
×
2471
                    listener.moderatorRevoked();
×
2472
                }
×
2473
            }
2474
            else {
2475
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2476
                    listener.moderatorRevoked(from);
×
2477
                }
×
2478
            }
2479
        }
2480
    }
×
2481

2482
    /**
2483
     * Fires notification events if the affiliation of a room occupant has changed. If the
2484
     * occupant that changed his affiliation is your occupant then the
2485
     * <code>UserStatusListeners</code> added to this <code>MultiUserChat</code> will be fired.
2486
     * On the other hand, if the occupant that changed his affiliation is not yours then the
2487
     * <code>ParticipantStatusListeners</code> added to this <code>MultiUserChat</code> will be
2488
     * fired. The following table shows the events that will be fired depending on the previous
2489
     * and new affiliation of the occupant.
2490
     *
2491
     * <pre>
2492
     * <table border="1">
2493
     * <tr><td><b>Old</b></td><td><b>New</b></td><td><b>Events</b></td></tr>
2494
     *
2495
     * <tr><td>None</td><td>Member</td><td>membershipGranted</td></tr>
2496
     * <tr><td>Member</td><td>Admin</td><td>membershipRevoked + adminGranted</td></tr>
2497
     * <tr><td>Admin</td><td>Owner</td><td>adminRevoked + ownershipGranted</td></tr>
2498
     *
2499
     * <tr><td>None</td><td>Admin</td><td>adminGranted</td></tr>
2500
     * <tr><td>None</td><td>Owner</td><td>ownershipGranted</td></tr>
2501
     * <tr><td>Member</td><td>Owner</td><td>membershipRevoked + ownershipGranted</td></tr>
2502
     *
2503
     * <tr><td>Owner</td><td>Admin</td><td>ownershipRevoked + adminGranted</td></tr>
2504
     * <tr><td>Admin</td><td>Member</td><td>adminRevoked + membershipGranted</td></tr>
2505
     * <tr><td>Member</td><td>None</td><td>membershipRevoked</td></tr>
2506
     *
2507
     * <tr><td>Owner</td><td>Member</td><td>ownershipRevoked + membershipGranted</td></tr>
2508
     * <tr><td>Owner</td><td>None</td><td>ownershipRevoked</td></tr>
2509
     * <tr><td>Admin</td><td>None</td><td>adminRevoked</td></tr>
2510
     * <tr><td><i>Anyone</i></td><td>Outcast</td><td>banned</td></tr>
2511
     * </table>
2512
     * </pre>
2513
     *
2514
     * @param oldAffiliation the previous affiliation of the user in the room before receiving the
2515
     * new presence
2516
     * @param newAffiliation the new affiliation of the user in the room after receiving the new
2517
     * presence
2518
     * @param isUserModification whether the received presence is about your user in the room or not
2519
     * @param from the occupant whose role in the room has changed
2520
     * (e.g. room@conference.jabber.org/nick).
2521
     */
2522
    private void checkAffiliationModifications(
2523
        MUCAffiliation oldAffiliation,
2524
        MUCAffiliation newAffiliation,
2525
        boolean isUserModification,
2526
        EntityFullJid from) {
2527
        // First check for revoked affiliation and then for granted affiliations. The idea is to
2528
        // first fire the "revoke" events and then fire the "grant" events.
2529

2530
        // The user's ownership to the room was revoked
2531
        if (MUCAffiliation.owner.equals(oldAffiliation) && !MUCAffiliation.owner.equals(newAffiliation)) {
×
2532
            if (isUserModification) {
×
2533
                for (UserStatusListener listener : userStatusListeners) {
×
2534
                    listener.ownershipRevoked();
×
2535
                }
×
2536
            }
2537
            else {
2538
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2539
                    listener.ownershipRevoked(from);
×
2540
                }
×
2541
            }
2542
        }
2543
        // The user's administrative privileges to the room were revoked
2544
        else if (MUCAffiliation.admin.equals(oldAffiliation) && !MUCAffiliation.admin.equals(newAffiliation)) {
×
2545
            if (isUserModification) {
×
2546
                for (UserStatusListener listener : userStatusListeners) {
×
2547
                    listener.adminRevoked();
×
2548
                }
×
2549
            }
2550
            else {
2551
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2552
                    listener.adminRevoked(from);
×
2553
                }
×
2554
            }
2555
        }
2556
        // The user's membership to the room was revoked
2557
        else if (MUCAffiliation.member.equals(oldAffiliation) && !MUCAffiliation.member.equals(newAffiliation)) {
×
2558
            if (isUserModification) {
×
2559
                for (UserStatusListener listener : userStatusListeners) {
×
2560
                    listener.membershipRevoked();
×
2561
                }
×
2562
            }
2563
            else {
2564
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2565
                    listener.membershipRevoked(from);
×
2566
                }
×
2567
            }
2568
        }
2569

2570
        // The user was granted ownership to the room
2571
        if (!MUCAffiliation.owner.equals(oldAffiliation) && MUCAffiliation.owner.equals(newAffiliation)) {
×
2572
            if (isUserModification) {
×
2573
                for (UserStatusListener listener : userStatusListeners) {
×
2574
                    listener.ownershipGranted();
×
2575
                }
×
2576
            }
2577
            else {
2578
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2579
                    listener.ownershipGranted(from);
×
2580
                }
×
2581
            }
2582
        }
2583
        // The user was granted administrative privileges to the room
2584
        else if (!MUCAffiliation.admin.equals(oldAffiliation) && MUCAffiliation.admin.equals(newAffiliation)) {
×
2585
            if (isUserModification) {
×
2586
                for (UserStatusListener listener : userStatusListeners) {
×
2587
                    listener.adminGranted();
×
2588
                }
×
2589
            }
2590
            else {
2591
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2592
                    listener.adminGranted(from);
×
2593
                }
×
2594
            }
2595
        }
2596
        // The user was granted membership to the room
2597
        else if (!MUCAffiliation.member.equals(oldAffiliation) && MUCAffiliation.member.equals(newAffiliation)) {
×
2598
            if (isUserModification) {
×
2599
                for (UserStatusListener listener : userStatusListeners) {
×
2600
                    listener.membershipGranted();
×
2601
                }
×
2602
            }
2603
            else {
2604
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2605
                    listener.membershipGranted(from);
×
2606
                }
×
2607
            }
2608
        }
2609
    }
×
2610

2611
    /**
2612
     * Fires events according to the received presence code.
2613
     *
2614
     * @param statusCodes TODO javadoc me please
2615
     * @param isUserModification TODO javadoc me please
2616
     * @param mucUser TODO javadoc me please
2617
     * @param from TODO javadoc me please
2618
     */
2619
    private void checkPresenceCode(
2620
        Set<Status> statusCodes,
2621
        boolean isUserModification,
2622
        MUCUser mucUser,
2623
        EntityFullJid from) {
2624
        // Check if an occupant was kicked from the room
2625
        if (statusCodes.contains(Status.KICKED_307)) {
×
2626
            // Check if this occupant was kicked
2627
            if (isUserModification) {
×
2628
                for (UserStatusListener listener : userStatusListeners) {
×
2629
                    listener.kicked(mucUser.getItem().getActor(), mucUser.getItem().getReason());
×
2630
                }
×
2631
            }
2632
            else {
2633
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2634
                    listener.kicked(from, mucUser.getItem().getActor(), mucUser.getItem().getReason());
×
2635
                }
×
2636
            }
2637
        }
2638
        // A user was banned from the room
2639
        if (statusCodes.contains(Status.BANNED_301)) {
×
2640
            // Check if this occupant was banned
2641
            if (isUserModification) {
×
2642
                for (UserStatusListener listener : userStatusListeners) {
×
2643
                    listener.banned(mucUser.getItem().getActor(), mucUser.getItem().getReason());
×
2644
                }
×
2645
            }
2646
            else {
2647
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2648
                    listener.banned(from, mucUser.getItem().getActor(), mucUser.getItem().getReason());
×
2649
                }
×
2650
            }
2651
        }
2652
        // A user's membership was revoked from the room
2653
        if (statusCodes.contains(Status.REMOVED_AFFIL_CHANGE_321)) {
×
2654
            // Check if this occupant's membership was revoked
2655
            if (isUserModification) {
×
2656
                for (UserStatusListener listener : userStatusListeners) {
×
2657
                    listener.membershipRevoked();
×
2658
                }
×
2659
            } else {
2660
                for (ParticipantStatusListener listener : participantStatusListeners) {
×
2661
                    listener.membershipRevoked(from);
×
2662
                }
×
2663
            }
2664
        }
2665
        // A occupant has changed his nickname in the room
2666
        if (statusCodes.contains(Status.NEW_NICKNAME_303)) {
×
2667
            for (ParticipantStatusListener listener : participantStatusListeners) {
×
2668
                listener.nicknameChanged(from, mucUser.getItem().getNick());
×
2669
            }
×
2670
        }
2671
    }
×
2672

2673
    /**
2674
     * Get the XMPP connection associated with this chat instance.
2675
     *
2676
     * @return the associated XMPP connection.
2677
     * @since 4.3.0
2678
     */
2679
    public XMPPConnection getXmppConnection() {
2680
        return connection;
1✔
2681
    }
2682

2683
    public boolean serviceSupportsStableIds() {
2684
        return DiscoverInfo.nullSafeContainsFeature(mucServiceDiscoInfo, MultiUserChatConstants.STABLE_ID_FEATURE);
×
2685
    }
2686

2687
    @Override
2688
    public String toString() {
2689
        return "MUC: " + room + "(" + connection.getUser() + ")";
×
2690
    }
2691
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc