LocalMUCRoom.java 101 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3158 $
 * $Date: 2005-12-04 22:55:49 -0300 (Sun, 04 Dec 2005) $
 *
6
 * Copyright (C) 2004-2008 Jive Software. All rights reserved.
7
 *
8 9 10 11 12 13 14 15 16 17 18
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
19 20 21 22
 */

package org.jivesoftware.openfire.muc.spi;

23 24 25 26 27 28 29 30 31 32 33
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
34
import java.util.concurrent.ConcurrentMap;
35 36 37 38
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

39 40 41 42 43 44
import org.dom4j.Element;
import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.openfire.PacketRouter;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.auth.UnauthorizedException;
import org.jivesoftware.openfire.cluster.NodeID;
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
import org.jivesoftware.openfire.muc.CannotBeInvitedException;
import org.jivesoftware.openfire.muc.ConflictException;
import org.jivesoftware.openfire.muc.ForbiddenException;
import org.jivesoftware.openfire.muc.HistoryRequest;
import org.jivesoftware.openfire.muc.HistoryStrategy;
import org.jivesoftware.openfire.muc.MUCEventDispatcher;
import org.jivesoftware.openfire.muc.MUCRole;
import org.jivesoftware.openfire.muc.MUCRoom;
import org.jivesoftware.openfire.muc.MUCRoomHistory;
import org.jivesoftware.openfire.muc.MultiUserChatService;
import org.jivesoftware.openfire.muc.NotAcceptableException;
import org.jivesoftware.openfire.muc.NotAllowedException;
import org.jivesoftware.openfire.muc.RegistrationRequiredException;
import org.jivesoftware.openfire.muc.RoomLockedException;
import org.jivesoftware.openfire.muc.ServiceUnavailableException;
import org.jivesoftware.openfire.muc.cluster.AddMember;
import org.jivesoftware.openfire.muc.cluster.BroadcastMessageRequest;
import org.jivesoftware.openfire.muc.cluster.BroadcastPresenceRequest;
import org.jivesoftware.openfire.muc.cluster.ChangeNickname;
import org.jivesoftware.openfire.muc.cluster.DestroyRoomRequest;
import org.jivesoftware.openfire.muc.cluster.OccupantAddedEvent;
import org.jivesoftware.openfire.muc.cluster.OccupantLeftEvent;
import org.jivesoftware.openfire.muc.cluster.UpdateOccupant;
import org.jivesoftware.openfire.muc.cluster.UpdateOccupantRequest;
import org.jivesoftware.openfire.muc.cluster.UpdatePresence;
70 71
import org.jivesoftware.openfire.user.UserAlreadyExistsException;
import org.jivesoftware.openfire.user.UserNotFoundException;
72 73 74
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.NotFoundException;
75 76
import org.jivesoftware.util.cache.CacheFactory;
import org.jivesoftware.util.cache.ExternalizableUtil;
77 78 79 80 81 82 83 84
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.IQ;
import org.xmpp.packet.JID;
import org.xmpp.packet.Message;
import org.xmpp.packet.Packet;
import org.xmpp.packet.PacketError;
import org.xmpp.packet.Presence;
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99

/**
 * Implementation of a chatroom that is being hosted by this JVM. A LocalMUCRoom could represent
 * a persistent room which means that its configuration will be maintained in synch with its
 * representation in the database.<p>
 *
 * When running in a cluster each cluster node will have its own copy of local rooms. Persistent
 * rooms will be loaded by each cluster node when starting up. Not persistent rooms will be copied
 * from the senior cluster member. All room occupants will be copied from the senior cluster member
 * too.
 * 
 * @author Gaston Dombiak
 */
public class LocalMUCRoom implements MUCRoom {

100 101
	private static final Logger Log = LoggerFactory.getLogger(LocalMUCRoom.class);

102
    /**
103
     * The service hosting the room.
104
     */
105
    private MultiUserChatService mucService;
106 107 108 109 110 111 112 113 114

    /**
     * The occupants of the room accessible by the occupants nickname.
     */
    private Map<String,MUCRole> occupants = new ConcurrentHashMap<String, MUCRole>();

    /**
     * The occupants of the room accessible by the occupants bare JID.
     */
115
    private ConcurrentMap<JID, List<MUCRole>> occupantsByBareJID = new ConcurrentHashMap<JID, List<MUCRole>>();
116 117 118 119

    /**
     * The occupants of the room accessible by the occupants full JID.
     */
120
    private ConcurrentMap<JID, MUCRole> occupantsByFullJID = new ConcurrentHashMap<JID, MUCRole>();
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153

    /**
     * The name of the room.
     */
    private String name;

    /**
     * A lock to protect the room occupants.
     */
    ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * The role of the room itself.
     */
    private MUCRole role = new RoomRole(this);

    /**
     * The router used to send packets for the room.
     */
    private PacketRouter router;

    /**
     * The start time of the chat.
     */
    long startTime;

    /**
     * The end time of the chat.
     */
    long endTime;

    /**
     * After a room has been destroyed it may remain in memory but it won't be possible to use it.
154
     * When a room is destroyed it is immediately removed from the MultiUserChatService but it's
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
     * possible that while the room was being destroyed it was being used by another thread so we
     * need to protect the room under these rare circumstances.
     */
    boolean isDestroyed = false;

    /**
     * ChatRoomHistory object.
     */
    private MUCRoomHistory roomHistory;

    /**
     * Time when the room was locked. A value of zero means that the room is unlocked.
     */
    private long lockedTime;

    /**
     * List of chatroom's owner. The list contains only bare jid.
     */
173
    List<JID> owners = new CopyOnWriteArrayList<JID>();
174 175 176 177

    /**
     * List of chatroom's admin. The list contains only bare jid.
     */
178
    List<JID> admins = new CopyOnWriteArrayList<JID>();
179 180

    /**
181
     * List of chatroom's members. The list contains only bare jid, mapped to a nickname.
182
     */
183
    private ConcurrentMap<JID, String> members = new ConcurrentHashMap<JID,String>();
184 185 186 187

    /**
     * List of chatroom's outcast. The list contains only bare jid of not allowed users.
     */
188
    private List<JID> outcasts = new CopyOnWriteArrayList<JID>();
189 190 191 192 193 194 195 196 197 198 199 200 201

    /**
     * The natural language name of the room.
     */
    private String naturalLanguageName;

    /**
     * Description of the room. The owner can change the description using the room configuration
     * form.
     */
    private String description;

    /**
202
     * Indicates if occupants are allowed to change the subject of the room.
203
     */
204
    private boolean canOccupantsChangeSubject;
205 206 207 208 209

    /**
     * Maximum number of occupants that could be present in the room. If the limit's been reached
     * and a user tries to join, a not-allowed error will be returned.
     */
210
    private int maxUsers;
211 212 213 214 215 216 217 218 219 220 221

    /**
     * List of roles of which presence will be broadcasted to the rest of the occupants. This
     * feature is useful for implementing "invisible" occupants.
     */
    private List<String> rolesToBroadcastPresence = new ArrayList<String>();

    /**
     * A public room means that the room is searchable and visible. This means that the room can be
     * located using disco requests.
     */
222
    private boolean publicRoom;
223 224 225 226 227

    /**
     * Persistent rooms are saved to the database to make sure that rooms configurations can be
     * restored in case the server goes down.
     */
228
    private boolean persistent;
229 230 231 232 233

    /**
     * Moderated rooms enable only participants to speak. Users that join the room and aren't
     * participants can't speak (they are just visitors).
     */
234
    private boolean moderated;
235 236 237 238 239 240

    /**
     * A room is considered members-only if an invitation is required in order to enter the room.
     * Any user that is not a member of the room won't be able to join the room unless the user
     * decides to register with the room (thus becoming a member).
     */
241
    private boolean membersOnly;
242 243

    /**
244
     * Some rooms may restrict the occupants that are able to send invitations. Sending an
245 246
     * invitation in a members-only room adds the invitee to the members list.
     */
247
    private boolean canOccupantsInvite;
248 249 250 251 252 253 254 255

    /**
     * The password that every occupant should provide in order to enter the room.
     */
    private String password = null;

    /**
     * Every presence packet can include the JID of every occupant unless the owner deactives this
256
     * configuration.
257
     */
258
    private boolean canAnyoneDiscoverJID;
259 260 261 262 263

    /**
     * Enables the logging of the conversation. The conversation in the room will be saved to the
     * database.
     */
264
    private boolean logEnabled;
265 266 267 268 269

    /**
     * Enables the logging of the conversation. The conversation in the room will be saved to the
     * database.
     */
270
    private boolean loginRestrictedToNickname;
271 272 273 274 275

    /**
     * Enables the logging of the conversation. The conversation in the room will be saved to the
     * database.
     */
276
    private boolean canChangeNickname;
277 278 279 280 281

    /**
     * Enables the logging of the conversation. The conversation in the room will be saved to the
     * database.
     */
282
    private boolean registrationEnabled;
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299

    /**
     * Internal component that handles IQ packets sent by the room owners.
     */
    private IQOwnerHandler iqOwnerHandler;

    /**
     * Internal component that handles IQ packets sent by moderators, admins and owners.
     */
    private IQAdminHandler iqAdminHandler;

    /**
     * The last known subject of the room. This information is used to respond disco requests. The
     * MUCRoomHistory class holds the history of the room together with the last message that set
     * the room's subject.
     */
    private String subject = "";
300

301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336
    /**
     * The ID of the room. If the room is temporary and does not log its conversation then the value
     * will always be -1. Otherwise a value will be obtained from the database.
     */
    private long roomID = -1;

    /**
     * The date when the room was created.
     */
    private Date creationDate;

    /**
     * The last date when the room's configuration was modified.
     */
    private Date modificationDate;

    /**
     * The date when the last occupant left the room. A null value means that there are occupants
     * in the room at the moment.
     */
    private Date emptyDate;

    /**
     * Indicates if the room is present in the database.
     */
    private boolean savedToDB = false;

    /**
     * Do not use this constructor. It was added to implement the Externalizable
     * interface required to work inside of a cluster.
     */
    public LocalMUCRoom() {
    }

    /**
     * Create a new chat room.
337 338
     *
     * @param chatservice the service hosting the room.
339 340 341
     * @param roomname the name of the room.
     * @param packetRouter the router for sending packets from the room.
     */
342 343
    LocalMUCRoom(MultiUserChatService chatservice, String roomname, PacketRouter packetRouter) {
        this.mucService = chatservice;
344 345 346 347 348 349 350 351
        this.name = roomname;
        this.naturalLanguageName = roomname;
        this.description = roomname;
        this.router = packetRouter;
        this.startTime = System.currentTimeMillis();
        this.creationDate = new Date(startTime);
        this.modificationDate = new Date(startTime);
        this.emptyDate = new Date(startTime);
352 353 354 355 356 357 358 359 360 361 362 363
        this.canOccupantsChangeSubject = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.canOccupantsChangeSubject", false);
        this.maxUsers = MUCPersistenceManager.getIntProperty(mucService.getServiceName(), "room.maxUsers", 30);
        this.publicRoom = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.publicRoom", true);
        this.persistent = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.persistent", false);
        this.moderated = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.moderated", false);
        this.membersOnly = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.membersOnly", false);
        this.canOccupantsInvite = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.canOccupantsInvite", false);
        this.canAnyoneDiscoverJID = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.canAnyoneDiscoverJID", true);
        this.logEnabled = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.logEnabled", false);
        this.loginRestrictedToNickname = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.loginRestrictedToNickname", false);
        this.canChangeNickname = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.canChangeNickname", true);
        this.registrationEnabled = MUCPersistenceManager.getBooleanProperty(mucService.getServiceName(), "room.registrationEnabled", true);
364
        // TODO Allow to set the history strategy from the configuration form?
365
        roomHistory = new MUCRoomHistory(this, new HistoryStrategy(mucService.getHistoryStrategy()));
366 367 368 369 370 371 372 373 374 375 376 377 378 379
        this.iqOwnerHandler = new IQOwnerHandler(this, packetRouter);
        this.iqAdminHandler = new IQAdminHandler(this, packetRouter);
        // No one can join the room except the room's owner
        this.lockedTime = startTime;
        // Set the default roles for which presence is broadcast
        rolesToBroadcastPresence.add("moderator");
        rolesToBroadcastPresence.add("participant");
        rolesToBroadcastPresence.add("visitor");
    }

    public String getName() {
        return name;
    }

380 381 382 383 384 385 386 387 388 389 390 391
    public JID getJID() {
        return new JID(getName(), getMUCService().getServiceDomain(), null);
    }

    public MultiUserChatService getMUCService() {
        return mucService;
    }

    public void setMUCService(MultiUserChatService service) {
        this.mucService = service;
    }

392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
    public long getID() {
        if (isPersistent() || isLogEnabled()) {
            if (roomID == -1) {
                roomID = SequenceManager.nextID(JiveConstants.MUC_ROOM);
            }
        }
        return roomID;
    }

    public void setID(long roomID) {
        this.roomID = roomID;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Date getModificationDate() {
        return modificationDate;
    }

    public void setModificationDate(Date modificationDate) {
        this.modificationDate = modificationDate;
    }

    public void setEmptyDate(Date emptyDate) {
        // Do nothing if old value is same as new value
        if (this.emptyDate == emptyDate) {
            return;
        }
        this.emptyDate = emptyDate;
        MUCPersistenceManager.updateRoomEmptyDate(this);
    }

    public Date getEmptyDate() {
        return this.emptyDate;
    }

    public MUCRole getRole() {
        return role;
    }

    public MUCRole getOccupant(String nickname) throws UserNotFoundException {
        if (nickname == null) {
             throw new UserNotFoundException();
        }
        MUCRole role = occupants.get(nickname.toLowerCase());
        if (role != null) {
            return role;
        }
        throw new UserNotFoundException();
    }

449
    public List<MUCRole> getOccupantsByBareJID(JID jid) throws UserNotFoundException {
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
        List<MUCRole> roles = occupantsByBareJID.get(jid);
        if (roles != null && !roles.isEmpty()) {
            return Collections.unmodifiableList(roles);
        }
        throw new UserNotFoundException();
    }

    public MUCRole getOccupantByFullJID(JID jid) {
        MUCRole role = occupantsByFullJID.get(jid);
        if (role != null) {
            return role;
        }
        return null;
    }

    public Collection<MUCRole> getOccupants() {
        return Collections.unmodifiableCollection(occupants.values());
    }

    public int getOccupantsCount() {
        return occupants.size();
    }

    public boolean hasOccupant(String nickname) {
        return occupants.containsKey(nickname.toLowerCase());
    }

477 478
    public String getReservedNickname(JID jid) {
    	final JID bareJID = new JID(jid.toBareJID());
479 480 481 482 483 484 485
        String answer = members.get(bareJID);
        if (answer == null || answer.trim().length() == 0) {
            return null;
        }
        return answer;
    }

486 487 488
    public MUCRole.Affiliation getAffiliation(JID jid) {
    	final JID bareJID = new JID(jid.toBareJID());

489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508
        if (owners.contains(bareJID)) {
            return MUCRole.Affiliation.owner;
        }
        else if (admins.contains(bareJID)) {
            return MUCRole.Affiliation.admin;
        }
        else if (members.containsKey(bareJID)) {
            return MUCRole.Affiliation.member;
        }
        else if (outcasts.contains(bareJID)) {
            return MUCRole.Affiliation.outcast;
        }
        return MUCRole.Affiliation.none;
    }

    public LocalMUCRole joinRoom(String nickname, String password, HistoryRequest historyRequest,
            LocalMUCUser user, Presence presence) throws UnauthorizedException,
            UserAlreadyExistsException, RoomLockedException, ForbiddenException,
            RegistrationRequiredException, ConflictException, ServiceUnavailableException,
            NotAcceptableException {
509
        if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) {
510
            if (!((MultiUserChatServiceImpl)mucService).getMUCDelegate().joiningRoom(this, user.getAddress())) {
511 512 513 514
                // Delegate said no, reject join.
                throw new UnauthorizedException();
            }
        }
515 516 517 518 519 520 521
        LocalMUCRole joinRole = null;
        lock.writeLock().lock();
        try {
            // If the room has a limit of max user then check if the limit has been reached
            if (isDestroyed || (getMaxUsers() > 0 && getOccupantsCount() >= getMaxUsers())) {
                throw new ServiceUnavailableException();
            }
522 523
            final JID bareJID = new JID(user.getAddress().toBareJID());
			boolean isOwner = owners.contains(bareJID);
524 525 526 527 528 529
            // If the room is locked and this user is not an owner raise a RoomLocked exception
            if (isLocked()) {
                if (!isOwner) {
                    throw new RoomLockedException();
                }
            }
530
            // Check if the nickname is already used in the room
531
            if (occupants.containsKey(nickname.toLowerCase())) {
532
                if (occupants.get(nickname.toLowerCase()).getUserAddress().toBareJID().equals(bareJID.toBareJID())) {
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556
                    // Nickname exists in room, and belongs to this user, pretend to kick the previous instance.
                    // The previous instance will see that they are disconnected, and the new instance will
                    // "take over" the previous role.  Participants in the room shouldn't notice anything
                    // has occurred.
                    String reason = "Your account signed into this chatroom with the same nickname from another location.";
                    Presence updatedPresence = new Presence(Presence.Type.unavailable);
                    updatedPresence.setFrom(occupants.get(nickname.toLowerCase()).getRoleAddress());
                    updatedPresence.setTo(occupants.get(nickname.toLowerCase()).getUserAddress());
                    Element frag = updatedPresence.addChildElement(
                            "x", "http://jabber.org/protocol/muc#user");

                    // Set the person who performed the kick ("you" effectively)
                    frag.addElement("item").addElement("actor").setText(user.getAddress().toString());
                    // Add the reason why the user was kicked
                    frag.element("item").addElement("reason").setText(reason);
                    // Add the status code 307 that indicates that the user was kicked
                    frag.addElement("status").addAttribute("code", "307");

                    router.route(updatedPresence);
                }
                else {
                    // Nickname is already used, and not by the same JID
                    throw new UserAlreadyExistsException();
                }
557 558 559 560 561 562 563 564 565 566 567
            }
            // If the room is password protected and the provided password is incorrect raise a
            // Unauthorized exception
            if (isPasswordProtected()) {
                if (password == null || !password.equals(getPassword())) {
                    throw new UnauthorizedException();
                }
            }
            // If another user attempts to join the room with a nickname reserved by the first user
            // raise a ConflictException
            if (members.containsValue(nickname)) {
568
                if (!nickname.equals(members.get(bareJID))) {
569 570 571 572
                    throw new ConflictException();
                }
            }
            if (isLoginRestrictedToNickname()) {
573
                String reservedNickname = members.get(bareJID);
574 575 576 577 578 579 580 581 582 583 584 585 586
                if (reservedNickname != null && !nickname.equals(reservedNickname)) {
                    throw new NotAcceptableException();
                }
            }

            // Set the corresponding role based on the user's affiliation
            MUCRole.Role role;
            MUCRole.Affiliation affiliation;
            if (isOwner) {
                // The user is an owner. Set the role and affiliation accordingly.
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.owner;
            }
587
            else if (mucService.getSysadmins().contains(bareJID)) {
588
                // The user is a system administrator of the MUC service. Treat him as an owner
589 590 591 592
                // although he won't appear in the list of owners
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.owner;
            }
593
            else if (admins.contains(bareJID)) {
594 595 596 597
                // The user is an admin. Set the role and affiliation accordingly.
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.admin;
            }
598
            else if (members.containsKey(bareJID)) {
599 600 601 602
                // The user is a member. Set the role and affiliation accordingly.
                role = MUCRole.Role.participant;
                affiliation = MUCRole.Affiliation.member;
            }
603
            else if (outcasts.contains(bareJID)) {
604 605 606 607 608 609 610 611 612 613 614 615 616 617
                // The user is an outcast. Raise a "Forbidden" exception.
                throw new ForbiddenException();
            }
            else {
                // The user has no affiliation (i.e. NONE). Set the role accordingly.
                if (isMembersOnly()) {
                    // The room is members-only and the user is not a member. Raise a
                    // "Registration Required" exception.
                    throw new RegistrationRequiredException();
                }
                role = (isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant);
                affiliation = MUCRole.Affiliation.none;
            }
            // Create a new role for this user in this room
618
            joinRole = new LocalMUCRole(mucService, this, nickname, role, affiliation, user, presence, router);
619 620 621
            // Add the new user as an occupant of this room
            occupants.put(nickname.toLowerCase(), joinRole);
            // Update the tables of occupants based on the bare and full JID
622
            List<MUCRole> list = occupantsByBareJID.get(bareJID);
623 624
            if (list == null) {
                list = new ArrayList<MUCRole>();
625
                occupantsByBareJID.put(bareJID, list);
626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
            }
            list.add(joinRole);
            occupantsByFullJID.put(user.getAddress(), joinRole);
        }
        finally {
            lock.writeLock().unlock();
        }
        // Notify other cluster nodes that a new occupant joined the room
        CacheFactory.doClusterTask(new OccupantAddedEvent(this, joinRole));

        // Send presence of existing occupants to new occupant
        sendInitialPresences(joinRole);
        // It is assumed that the room is new based on the fact that it's locked and
        // that it was locked when it was created.
        boolean isRoomNew = isLocked() && creationDate.getTime() == lockedTime;
        try {
            // Send the presence of this new occupant to existing occupants
            Presence joinPresence = joinRole.getPresence().createCopy();
            if (isRoomNew) {
                Element frag = joinPresence.getChildElement("x", "http://jabber.org/protocol/muc#user");
                frag.addElement("status").addAttribute("code", "201");
            }
            broadcastPresence(joinPresence);
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        // If the room has just been created send the "room locked until configuration is
        // confirmed" message
        if (isRoomNew) {
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.new"));
            message.setFrom(role.getRoleAddress());
            joinRole.send(message);
        }
        else if (isLocked()) {
            // Warn the owner that the room is locked but it's not new
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.locked"));
            message.setFrom(role.getRoleAddress());
            joinRole.send(message);
        }
        else if (canAnyoneDiscoverJID()) {
            // Warn the new occupant that the room is non-anonymous (i.e. his JID will be
            // public)
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.warnnonanonymous"));
            message.setFrom(role.getRoleAddress());
            Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
            frag.addElement("status").addAttribute("code", "100");
            joinRole.send(message);
        }
        if (historyRequest == null) {
682
            Iterator<Message> history = roomHistory.getMessageHistory();
683
            while (history.hasNext()) {
684
                joinRole.send(history.next());
685 686 687 688 689 690 691 692
            }
        }
        else {
            historyRequest.sendHistory(joinRole, roomHistory);
        }
        // Update the date when the last occupant left the room
        setEmptyDate(null);
        // Fire event that occupant joined the room
693
        MUCEventDispatcher.occupantJoined(getRole().getRoleAddress(), user.getAddress(), joinRole.getNickname());
694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
        return joinRole;
    }

    /**
     * Sends presence of existing occupants to new occupant.
     *
     * @param joinRole the role of the new occupant in the room.
     */
    private void sendInitialPresences(LocalMUCRole joinRole) {
        for (MUCRole occupant : occupants.values()) {
            if (occupant == joinRole) {
                continue;
            }
            Presence occupantPresence = occupant.getPresence();
            // Skip to the next occupant if we cannot send presence of this occupant
            if (hasToCheckRoleToBroadcastPresence()) {
                Element frag = occupantPresence.getChildElement("x",
                        "http://jabber.org/protocol/muc#user");
                // Check if we can broadcast the presence for this role
                if (!canBroadcastPresence(frag.element("item").attributeValue("role"))) {
                    continue;
                }
            }
            // Don't include the occupant's JID if the room is semi-anon and the new occupant
            // is not a moderator
            if (!canAnyoneDiscoverJID() && MUCRole.Role.moderator != joinRole.getRole()) {
                occupantPresence = occupantPresence.createCopy();
                Element frag = occupantPresence.getChildElement("x",
                        "http://jabber.org/protocol/muc#user");
                frag.element("item").addAttribute("jid", null);
            }
            joinRole.send(occupantPresence);
        }
    }

    public void occupantAdded(OccupantAddedEvent event) {
730
        // Do not add new occupant with one with same nickname already exists
731 732 733 734 735
        if (occupants.containsKey(event.getNickname().toLowerCase())) {
            // TODO Handle conflict of nicknames
            return;
        }
        // Create a proxy for the occupant that joined the room from another cluster node
736
        RemoteMUCRole joinRole = new RemoteMUCRole(mucService, event);
737 738 739
        // Add the new user as an occupant of this room
        occupants.put(event.getNickname().toLowerCase(), joinRole);
        // Update the tables of occupants based on the bare and full JID
740 741
        JID bareJID = new JID(event.getUserAddress().toBareJID());
		List<MUCRole> list = occupantsByBareJID.get(bareJID);
742 743
        if (list == null) {
            list = new ArrayList<MUCRole>();
744
            occupantsByBareJID.put(bareJID, list);
745 746 747 748 749 750
        }
        list.add(joinRole);
        occupantsByFullJID.put(event.getUserAddress(), joinRole);

        // Update the date when the last occupant left the room
        setEmptyDate(null);
751 752
        if (event.isOriginator()) {
            // Fire event that occupant joined the room
753
            MUCEventDispatcher.occupantJoined(getRole().getRoleAddress(), event.getUserAddress(), joinRole.getNickname());
754
        }
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
        // Check if we need to send presences of the new occupant to occupants hosted by this JVM
        if (event.isSendPresence()) {
            for (MUCRole occupant : occupants.values()) {
                if (occupant.isLocal()) {
                    occupant.send(event.getPresence().createCopy());
                }
            }
        }
    }

    public void leaveRoom(MUCRole leaveRole) {
        if (leaveRole.isLocal()) {
            // Ask other cluster nodes to remove occupant from room
            OccupantLeftEvent event = new OccupantLeftEvent(this, leaveRole);
            CacheFactory.doClusterTask(event);
        }

        try {
773 774
            Presence originalPresence = leaveRole.getPresence();
            Presence presence = originalPresence.createCopy();
775 776 777 778 779 780 781 782 783 784 785 786
            presence.setType(Presence.Type.unavailable);
            presence.setStatus(null);
            // Change (or add) presence information about roles and affiliations
            Element childElement = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
            if (childElement == null) {
                childElement = presence.addChildElement("x", "http://jabber.org/protocol/muc#user");
            }
            Element item = childElement.element("item");
            if (item == null) {
                item = childElement.addElement("item");
            }
            item.addAttribute("role", "none");
787 788 789 790 791 792 793 794 795 796 797 798

            // Check to see if the user's original presence is one we should broadcast
            // a leave packet for. Need to check the original presence because we just
            // set the role to "none" above, which is always broadcast.
            if(!shouldBroadcastPresence(originalPresence)){
                // Inform the leaving user that he/she has left the room
                leaveRole.send(presence);
            }
            else {
                // Inform the rest of the room occupants that the user has left the room
                broadcastPresence(presence);
            }
799 800
        }
        catch (Exception e) {
801
            Log.error(e.getMessage(), e);
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817
        }

        // Remove occupant from room and destroy room if empty and not persistent
        OccupantLeftEvent event = new OccupantLeftEvent(this, leaveRole);
        event.setOriginator(true);
        event.run();
    }

    public void leaveRoom(OccupantLeftEvent event) {
        MUCRole leaveRole = event.getRole();
        if (leaveRole == null) {
            return;
        }
        lock.writeLock().lock();
        try {
            // Removes the role from the room
818
            removeOccupantRole(leaveRole, event.isOriginator());
819 820 821 822 823 824 825 826

            // TODO Implement this: If the room owner becomes unavailable for any reason before
            // submitting the form (e.g., a lost connection), the service will receive a presence
            // stanza of type "unavailable" from the owner to the room@service/nick or room@service
            // (or both). The service MUST then destroy the room, sending a presence stanza of type
            // "unavailable" from the room to the owner including a <destroy/> element and reason
            // (if provided) as defined under the "Destroying a Room" use case.

827
            // Remove the room from the service only if there are no more occupants and the room is
828 829 830 831
            // not persistent
            if (occupants.isEmpty() && !isPersistent()) {
                endTime = System.currentTimeMillis();
                if (event.isOriginator()) {
832
                    mucService.removeChatRoom(name);
833
                    // Fire event that the room has been destroyed
834
                    MUCEventDispatcher.roomDestroyed(getRole().getRoleAddress());
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
                }
            }
            if (occupants.isEmpty()) {
                // Update the date when the last occupant left the room
                setEmptyDate(new Date());
            }
        }
        finally {
            lock.writeLock().unlock();
        }
    }

    /**
     * Removes the role of the occupant from all the internal occupants collections. The role will
     * also be removed from the user's roles.
     *
     * @param leaveRole the role to remove.
852
     * @param originator true if this JVM is the one that originated the event.
853
     */
854
    private void removeOccupantRole(MUCRole leaveRole, boolean originator) {
855 856 857 858 859 860
        occupants.remove(leaveRole.getNickname().toLowerCase());

        JID userAddress = leaveRole.getUserAddress();
        // Notify the user that he/she is no longer in the room
        leaveRole.destroy();
        // Update the tables of occupants based on the bare and full JID
861 862
        JID bareJID = new JID(userAddress.toBareJID());
		List<MUCRole> list = occupantsByBareJID.get(bareJID);
863 864 865
        if (list != null) {
            list.remove(leaveRole);
            if (list.isEmpty()) {
866
                occupantsByBareJID.remove(bareJID);
867 868 869
            }
        }
        occupantsByFullJID.remove(userAddress);
870 871
        if (originator) {
            // Fire event that occupant left the room
872
            MUCEventDispatcher.occupantLeft(getRole().getRoleAddress(), userAddress);
873
        }
874 875 876
    }

    public void destroyRoom(DestroyRoomRequest destroyRequest) {
877
        JID alternateJID = destroyRequest.getAlternateJID();
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
        String reason = destroyRequest.getReason();
        MUCRole leaveRole;
        Collection<MUCRole> removedRoles = new ArrayList<MUCRole>();
        lock.writeLock().lock();
        try {
            boolean hasRemoteOccupants = false;
            // Remove each occupant
            for (String nickname: occupants.keySet()) {
                leaveRole = occupants.remove(nickname);

                if (leaveRole != null) {
                    // Add the removed occupant to the list of removed occupants. We are keeping a
                    // list of removed occupants to process later outside of the lock.
                    if (leaveRole.isLocal()) {
                        removedRoles.add(leaveRole);
                    }
                    else {
                        hasRemoteOccupants = true;
                    }
897
                    removeOccupantRole(leaveRole, destroyRequest.isOriginator());
898 899 900 901 902 903 904 905 906 907
                }
            }
            endTime = System.currentTimeMillis();
            // Set that the room has been destroyed
            isDestroyed = true;
            if (destroyRequest.isOriginator()) {
                if (hasRemoteOccupants) {
                    // Ask other cluster nodes to remove occupants since room is being destroyed
                    CacheFactory.doClusterTask(new DestroyRoomRequest(this, alternateJID, reason));
                }
908 909
                // Removes the room from the list of rooms hosted in the service
                mucService.removeChatRoom(name);
910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927
            }
        }
        finally {
            lock.writeLock().unlock();
        }
        // Send an unavailable presence to each removed occupant
        for (MUCRole removedRole : removedRoles) {
            try {
                // Send a presence stanza of type "unavailable" to the occupant
                Presence presence = createPresence(Presence.Type.unavailable);
                presence.setFrom(removedRole.getRoleAddress());

                // A fragment containing the x-extension for room destruction.
                Element fragment = presence.addChildElement("x",
                        "http://jabber.org/protocol/muc#user");
                Element item = fragment.addElement("item");
                item.addAttribute("affiliation", "none");
                item.addAttribute("role", "none");
928 929
                if (alternateJID != null) {
                    fragment.addElement("destroy").addAttribute("jid", alternateJID.toFullJID());
930 931 932 933 934 935 936 937 938 939 940
                }
                if (reason != null && reason.length() > 0) {
                    Element destroy = fragment.element("destroy");
                    if (destroy == null) {
                        destroy = fragment.addElement("destroy");
                    }
                    destroy.addElement("reason").setText(reason);
                }
                removedRole.send(presence);
            }
            catch (Exception e) {
941
                Log.error(e.getMessage(), e);
942 943 944 945 946
            }
        }
        if (destroyRequest.isOriginator()) {
            // Remove the room from the DB if the room was persistent
            MUCPersistenceManager.deleteFromDB(this);
947
            // Fire event that the room has been destroyed
948
            MUCEventDispatcher.roomDestroyed(getRole().getRoleAddress());
949 950 951
        }
    }

952
    public void destroyRoom(JID alternateJID, String reason) {
953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981
        DestroyRoomRequest destroyRequest = new DestroyRoomRequest(this, alternateJID, reason);
        destroyRequest.setOriginator(true);
        destroyRequest.run();
    }

    public Presence createPresence(Presence.Type presenceType) throws UnauthorizedException {
        Presence presence = new Presence();
        presence.setType(presenceType);
        presence.setFrom(role.getRoleAddress());
        return presence;
    }

    public void serverBroadcast(String msg) {
        Message message = new Message();
        message.setType(Message.Type.groupchat);
        message.setBody(msg);
        message.setFrom(role.getRoleAddress());
        broadcast(message);
    }

    public void sendPublicMessage(Message message, MUCRole senderRole) throws ForbiddenException {
        // Check that if the room is moderated then the sender of the message has to have voice
        if (isModerated() && senderRole.getRole().compareTo(MUCRole.Role.participant) > 0) {
            throw new ForbiddenException();
        }
        // Send the message to all occupants
        message.setFrom(senderRole.getRoleAddress());
        send(message);
        // Fire event that message was receibed by the room
982
        MUCEventDispatcher.messageReceived(getRole().getRoleAddress(), senderRole.getUserAddress(),
983 984 985 986 987 988 989 990 991
                senderRole.getNickname(), message);
    }

    public void sendPrivatePacket(Packet packet, MUCRole senderRole) throws NotFoundException {
        String resource = packet.getTo().getResource();
        MUCRole occupant = occupants.get(resource.toLowerCase());
        if (occupant != null) {
            packet.setFrom(senderRole.getRoleAddress());
            occupant.send(packet);
992 993 994 995 996
            if(packet instanceof Message) {
               Message message = (Message) packet;
                 MUCEventDispatcher.privateMessageRecieved(occupant.getUserAddress(), senderRole.getUserAddress(),
                         message);
            }
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017
        }
        else {
            throw new NotFoundException();
        }
    }

    public void send(Packet packet) {
        if (packet instanceof Message) {
            broadcast((Message)packet);
        }
        else if (packet instanceof Presence) {
            broadcastPresence((Presence)packet);
        }
        else if (packet instanceof IQ) {
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setChildElement(((IQ) packet).getChildElement());
            reply.setError(PacketError.Condition.bad_request);
            router.route(reply);
        }
    }

1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037
    /**
     * Checks the role of the sender and returns true if the given presence should be broadcasted
     * 
     * @param presence The presence to check
     * @return true if the presence should be broadcast to the rest of the room
     */
    private boolean shouldBroadcastPresence(Presence presence){
        if (presence == null) {
            return false;
        }
        if (hasToCheckRoleToBroadcastPresence()) {
            Element frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
            // Check if we can broadcast the presence for this role
            if (!canBroadcastPresence(frag.element("item").attributeValue("role"))) {
                return false;
            }
        }
        return true;
    }

1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
    /**
     * Broadcasts the specified presence to all room occupants. If the presence belongs to a
     * user whose role cannot be broadcast then the presence will only be sent to the presence's
     * user. On the other hand, the JID of the user that sent the presence won't be included if the
     * room is semi-anon and the target occupant is not a moderator.
     *
     * @param presence the presence to broadcast.
     */
    private void broadcastPresence(Presence presence) {
        if (presence == null) {
            return;
        }
1050 1051 1052 1053 1054 1055 1056 1057
        if (!shouldBroadcastPresence(presence)) {
            // Just send the presence to the sender of the presence
            try {
                MUCRole occupant = getOccupant(presence.getFrom().getResource());
                occupant.send(presence);
            }
            catch (UserNotFoundException e) {
                // Do nothing
1058
            }
1059
            return;
1060 1061 1062
        }

        // Broadcast presence to occupants hosted by other cluster nodes
1063
        BroadcastPresenceRequest request = new BroadcastPresenceRequest(this, presence);
1064 1065 1066
        CacheFactory.doClusterTask(request);

        // Broadcast presence to occupants connected to this JVM
1067
        request = new BroadcastPresenceRequest(this, presence);
1068 1069 1070 1071
        request.setOriginator(true);
        request.run();
    }

1072
    public void broadcast(BroadcastPresenceRequest presenceRequest) {
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100
        String jid = null;
        Presence presence = presenceRequest.getPresence();
        Element frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
        // Don't include the occupant's JID if the room is semi-anon and the new occupant
        // is not a moderator
        if (!canAnyoneDiscoverJID()) {
            jid = frag.element("item").attributeValue("jid");
        }
        for (MUCRole occupant : occupants.values()) {
            if (!occupant.isLocal()) {
                continue;
            }
            // Don't include the occupant's JID if the room is semi-anon and the new occupant
            // is not a moderator
            if (!canAnyoneDiscoverJID()) {
                if (MUCRole.Role.moderator == occupant.getRole()) {
                    frag.element("item").addAttribute("jid", jid);
                }
                else {
                    frag.element("item").addAttribute("jid", null);
                }
            }
            occupant.send(presence);
        }
    }

    private void broadcast(Message message) {
        // Broadcast message to occupants hosted by other cluster nodes
1101
        BroadcastMessageRequest request = new BroadcastMessageRequest(this, message, occupants.size());
1102 1103 1104
        CacheFactory.doClusterTask(request);

        // Broadcast message to occupants connected to this JVM
1105
        request = new BroadcastMessageRequest(this, message, occupants.size());
1106 1107 1108 1109
        request.setOriginator(true);
        request.run();
    }

1110
    public void broadcast(BroadcastMessageRequest messageRequest) {
1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
        Message message = messageRequest.getMessage();
        // Add message to the room history
        roomHistory.addMessage(message);
        // Send message to occupants connected to this JVM
        for (MUCRole occupant : occupants.values()) {
            // Do not send broadcast messages to deaf occupants or occupants hosted in
            // other cluster nodes
            if (occupant.isLocal() && !occupant.isVoiceOnly()) {
                occupant.send(message);
            }
        }
        if (messageRequest.isOriginator() && isLogEnabled()) {
            MUCRole senderRole = null;
            JID senderAddress;
            if (message.getFrom() != null && message.getFrom().getResource() != null) {
                senderRole = occupants.get(message.getFrom().getResource().toLowerCase());
            }
            if (senderRole == null) {
                // The room itself is sending the message
                senderAddress = getRole().getRoleAddress();
            }
            else {
                // An occupant is sending the message
                senderAddress = senderRole.getUserAddress();
            }
            // Log the conversation
1137
            mucService.logConversation(this, message, senderAddress);
1138
        }
1139
        mucService.messageBroadcastedTo(messageRequest.getOccupants());
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201
    }

    /**
     * An empty role that represents the room itself in the chatroom. Chatrooms need to be able to
     * speak (server messages) and so must have their own role in the chatroom.
     */
    private class RoomRole implements MUCRole {

        private MUCRoom room;

        private RoomRole(MUCRoom room) {
            this.room = room;
        }

        public Presence getPresence() {
            return null;
        }

        public void setPresence(Presence presence) {
        }

        public void setRole(MUCRole.Role newRole) {
        }

        public MUCRole.Role getRole() {
            return MUCRole.Role.moderator;
        }

        public void setAffiliation(MUCRole.Affiliation newAffiliation) {
        }

        public MUCRole.Affiliation getAffiliation() {
            return MUCRole.Affiliation.owner;
        }

        public void changeNickname(String nickname) {
        }

        public String getNickname() {
            return null;
        }

        public boolean isVoiceOnly() {
            return false;
        }

        public boolean isLocal() {
            return true;
        }

        public NodeID getNodeID() {
            return XMPPServer.getInstance().getNodeID();
        }

        public MUCRoom getChatRoom() {
            return room;
        }

        private JID crJID = null;

        public JID getRoleAddress() {
            if (crJID == null) {
1202
                crJID = new JID(room.getName(), mucService.getServiceDomain(), null, true);
1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226
            }
            return crJID;
        }

        public JID getUserAddress() {
            return null;
        }

        public void send(Packet packet) {
            room.send(packet);
        }

        public void destroy() {
        }
    }

    public long getChatLength() {
        return endTime - startTime;
    }

    /**
     * Updates all the presences of the given user with the new affiliation and role information. Do
     * nothing if the given jid is not present in the room. If the user has joined the room from
     * several client resources, all his/her occupants' presences will be updated.
1227
     *
1228 1229 1230 1231 1232 1233 1234 1235
     * @param bareJID the bare jid of the user to update his/her role.
     * @param newAffiliation the new affiliation for the JID.
     * @param newRole the new role for the JID.
     * @return the list of updated presences of all the client resources that the client used to
     *         join the room.
     * @throws NotAllowedException If trying to change the moderator role to an owner or an admin or
     *         if trying to ban an owner or an administrator.
     */
1236
    private List<Presence> changeOccupantAffiliation(JID jid, MUCRole.Affiliation newAffiliation, MUCRole.Role newRole)
1237 1238 1239
            throws NotAllowedException {
        List<Presence> presences = new ArrayList<Presence>();
        // Get all the roles (i.e. occupants) of this user based on his/her bare JID
1240 1241
        JID bareJID = new JID(jid.toBareJID());
		List<MUCRole> roles = occupantsByBareJID.get(bareJID);
1242 1243 1244 1245 1246 1247
        if (roles == null) {
            return presences;
        }
        // Collect all the updated presences of these roles
        for (MUCRole role : roles) {
            // Update the presence with the new affiliation and role
1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
            if (role.isLocal()) {
                role.setAffiliation(newAffiliation);
                role.setRole(newRole);
                // Notify the othe cluster nodes to update the occupant
                CacheFactory.doClusterTask(new UpdateOccupant(this, role));
                // Prepare a new presence to be sent to all the room occupants
                presences.add(role.getPresence().createCopy());
            }
            else {
                // Ask the cluster node hosting the occupant to make the changes. Note that if the change
                // is not allowed a NotAllowedException will be thrown
                Element element = (Element) CacheFactory.doSynchronousClusterTask(
                        new UpdateOccupantRequest(this, role.getNickname(), newAffiliation, newRole),
                        role.getNodeID().toByteArray());
                if (element != null) {
                    // Prepare a new presence to be sent to all the room occupants
                    presences.add(new Presence(element, true));
                }
                else {
                    throw new NotAllowedException();
                }
            }
1270 1271 1272 1273 1274 1275 1276 1277
        }
        // Answer all the updated presences
        return presences;
    }

    /**
     * Updates the presence of the given user with the new role information. Do nothing if the given
     * jid is not present in the room.
1278
     *
1279 1280 1281 1282 1283 1284 1285 1286 1287
     * @param jid the full jid of the user to update his/her role.
     * @param newRole the new role for the JID.
     * @return the updated presence of the user or null if none.
     * @throws NotAllowedException If trying to change the moderator role to an owner or an admin.
     */
    private Presence changeOccupantRole(JID jid, MUCRole.Role newRole) throws NotAllowedException {
        // Try looking the role in the bare JID list
        MUCRole role = occupantsByFullJID.get(jid);
        if (role != null) {
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
            if (role.isLocal()) {
                // Update the presence with the new role
                role.setRole(newRole);
                // Notify the othe cluster nodes to update the occupant
                CacheFactory.doClusterTask(new UpdateOccupant(this, role));
                // Prepare a new presence to be sent to all the room occupants
                return role.getPresence().createCopy();
            }
            else {
                // Ask the cluster node hosting the occupant to make the changes. Note that if the change
                // is not allowed a NotAllowedException will be thrown
                Element element = (Element) CacheFactory.doSynchronousClusterTask(
                        new UpdateOccupantRequest(this, role.getNickname(), null, newRole),
                        role.getNodeID().toByteArray());
                if (element != null) {
                    // Prepare a new presence to be sent to all the room occupants
                    return new Presence(element, true);
                }
                else {
                    throw new NotAllowedException();
                }
            }
1310 1311 1312 1313
        }
        return null;
    }

1314 1315
    public void addFirstOwner(JID bareJID) {
        owners.add(new JID(bareJID.toBareJID()));
1316 1317 1318
    }

    public List<Presence> addOwner(JID jid, MUCRole sendRole) throws ForbiddenException {
1319
        final JID bareJID = new JID(jid.toBareJID());
1320 1321 1322 1323 1324 1325 1326
        lock.writeLock().lock();
        try {
            MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
            if (MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
                throw new ForbiddenException();
            }
            // Check if user is already an owner
1327
			if (owners.contains(bareJID)) {
1328 1329 1330
                // Do nothing
                return Collections.emptyList();
            }
1331
            owners.add(bareJID);
1332
            // Remove the user from other affiliation lists
1333
            if (removeAdmin(bareJID)) {
1334 1335
                oldAffiliation = MUCRole.Affiliation.admin;
            }
1336
            else if (removeMember(bareJID)) {
1337 1338
                oldAffiliation = MUCRole.Affiliation.member;
            }
1339
            else if (removeOutcast(bareJID)) {
1340 1341 1342 1343 1344
                oldAffiliation = MUCRole.Affiliation.outcast;
            }
            // Update the DB if the room is persistent
            MUCPersistenceManager.saveAffiliationToDB(
                this,
1345
                bareJID,
1346 1347 1348
                null,
                MUCRole.Affiliation.owner,
                oldAffiliation);
1349
        }
1350 1351
        finally {
            lock.writeLock().unlock();
1352 1353 1354
        }
        // Update the presence with the new affiliation and inform all occupants
        try {
1355
            return changeOccupantAffiliation(jid, MUCRole.Affiliation.owner,
1356 1357 1358 1359 1360 1361 1362 1363
                    MUCRole.Role.moderator);
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

1364 1365
    private boolean removeOwner(JID jid) {
        return owners.remove(new JID(jid.toBareJID()));
1366 1367 1368
    }

    public List<Presence> addAdmin(JID jid, MUCRole sendRole) throws ForbiddenException,
1369
            ConflictException {
1370
    	final JID bareJID = new JID(jid.toBareJID());
1371 1372 1373 1374 1375 1376 1377
        lock.writeLock().lock();
        try {
            MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
            if (MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
                throw new ForbiddenException();
            }
            // Check that the room always has an owner
1378
            if (owners.contains(bareJID) && owners.size() == 1) {
1379 1380 1381
                throw new ConflictException();
            }
            // Check if user is already an admin
1382
            if (admins.contains(bareJID)) {
1383 1384 1385
                // Do nothing
                return Collections.emptyList();
            }
1386
            admins.add(bareJID);
1387
            // Remove the user from other affiliation lists
1388
            if (removeOwner(bareJID)) {
1389 1390
                oldAffiliation = MUCRole.Affiliation.owner;
            }
1391
            else if (removeMember(bareJID)) {
1392 1393
                oldAffiliation = MUCRole.Affiliation.member;
            }
1394
            else if (removeOutcast(bareJID)) {
1395 1396 1397 1398 1399
                oldAffiliation = MUCRole.Affiliation.outcast;
            }
            // Update the DB if the room is persistent
            MUCPersistenceManager.saveAffiliationToDB(
                this,
1400
                bareJID,
1401 1402 1403 1404 1405 1406
                null,
                MUCRole.Affiliation.admin,
                oldAffiliation);
        }
        finally {
            lock.writeLock().unlock();
1407 1408 1409
        }
        // Update the presence with the new affiliation and inform all occupants
        try {
1410
            return changeOccupantAffiliation(jid, MUCRole.Affiliation.admin,
1411 1412 1413 1414 1415 1416 1417 1418
                    MUCRole.Role.moderator);
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

1419 1420
    private boolean removeAdmin(JID bareJID) {
        return admins.remove(new JID(bareJID.toBareJID()));
1421 1422 1423 1424
    }

    public List<Presence> addMember(JID jid, String nickname, MUCRole sendRole)
            throws ForbiddenException, ConflictException {
1425
    	final JID bareJID = new JID(jid.toBareJID());
1426 1427
        lock.writeLock().lock();
        try {
1428
            MUCRole.Affiliation oldAffiliation = (members.containsKey(bareJID) ?
1429 1430 1431 1432 1433 1434 1435 1436 1437 1438
                    MUCRole.Affiliation.member : MUCRole.Affiliation.none);
            if (isMembersOnly()) {
                if (!canOccupantsInvite()) {
                    if (MUCRole.Affiliation.admin != sendRole.getAffiliation()
                            && MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
                        throw new ForbiddenException();
                    }
                }
            }
            else {
1439 1440 1441 1442 1443
                if (MUCRole.Affiliation.admin != sendRole.getAffiliation()
                        && MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
                    throw new ForbiddenException();
                }
            }
1444 1445
            // Check if the desired nickname is already reserved for another member
            if (nickname != null && nickname.trim().length() > 0 && members.containsValue(nickname)) {
1446
                if (!nickname.equals(members.get(bareJID))) {
1447 1448
                    throw new ConflictException();
                }
1449
            }
1450
            // Check that the room always has an owner
1451
            if (owners.contains(bareJID) && owners.size() == 1) {
1452 1453
                throw new ConflictException();
            }
1454 1455
            // Associate the reserved nickname with the bareJID. If nickname is null then associate an
            // empty string
1456
            members.put(bareJID, (nickname == null ? "" : nickname));
1457
            // Remove the user from other affiliation lists
1458
            if (removeOwner(bareJID)) {
1459 1460
                oldAffiliation = MUCRole.Affiliation.owner;
            }
1461
            else if (removeAdmin(bareJID)) {
1462 1463
                oldAffiliation = MUCRole.Affiliation.admin;
            }
1464
            else if (removeOutcast(bareJID)) {
1465 1466 1467 1468 1469
                oldAffiliation = MUCRole.Affiliation.outcast;
            }
            // Update the DB if the room is persistent
            MUCPersistenceManager.saveAffiliationToDB(
                this,
1470
                bareJID,
1471 1472 1473
                nickname,
                MUCRole.Affiliation.member,
                oldAffiliation);
1474
        }
1475 1476
        finally {
            lock.writeLock().unlock();
1477
        }
1478
        // Update other cluster nodes with new member
1479
        CacheFactory.doClusterTask(new AddMember(this, jid.toBareJID(), (nickname == null ? "" : nickname)));
1480 1481
        // Update the presence with the new affiliation and inform all occupants
        try {
1482
            return changeOccupantAffiliation(jid, MUCRole.Affiliation.member,
1483 1484 1485 1486 1487 1488 1489 1490
                    MUCRole.Role.participant);
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

1491 1492 1493
    private boolean removeMember(JID jid) {
        final JID bareJID = new JID(jid.toBareJID());
		boolean answer = members.containsKey(bareJID);
1494 1495 1496 1497
        members.remove(bareJID);
        return answer;
    }

1498 1499
    public List<Presence> addOutcast(JID jid, String reason, MUCRole senderRole)
            throws NotAllowedException, ForbiddenException, ConflictException {
1500
        final JID bareJID = new JID(jid.toBareJID());
1501 1502 1503 1504 1505 1506 1507 1508
        lock.writeLock().lock();
        try {
            MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
            if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                    && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                throw new ForbiddenException();
            }
            // Check that the room always has an owner
1509
            if (owners.contains(bareJID) && owners.size() == 1) {
1510 1511 1512
                throw new ConflictException();
            }
            // Check if user is already an outcast
1513
            if (outcasts.contains(bareJID)) {
1514 1515 1516 1517 1518
                // Do nothing
                return Collections.emptyList();
            }

            // Update the affiliation lists
1519
            outcasts.add(bareJID);
1520
            // Remove the user from other affiliation lists
1521
            if (removeOwner(bareJID)) {
1522 1523
                oldAffiliation = MUCRole.Affiliation.owner;
            }
1524
            else if (removeAdmin(bareJID)) {
1525 1526
                oldAffiliation = MUCRole.Affiliation.admin;
            }
1527
            else if (removeMember(bareJID)) {
1528 1529 1530 1531 1532
                oldAffiliation = MUCRole.Affiliation.member;
            }
            // Update the DB if the room is persistent
            MUCPersistenceManager.saveAffiliationToDB(
                this,
1533
                bareJID,
1534 1535 1536
                null,
                MUCRole.Affiliation.outcast,
                oldAffiliation);
1537
        }
1538 1539
        finally {
            lock.writeLock().unlock();
1540 1541 1542 1543 1544
        }
        // Update the presence with the new affiliation and inform all occupants
        // actorJID will be null if the room itself (ie. via admin console) made the request
        JID actorJID = senderRole.getUserAddress();
        List<Presence> updatedPresences = changeOccupantAffiliation(
1545
                jid,
1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567
                MUCRole.Affiliation.outcast,
                MUCRole.Role.none);
        Element frag;
        // Add the status code and reason why the user was banned to the presences that will
        // be sent to the room occupants (the banned user will not receive this presences)
        for (Presence presence : updatedPresences) {
            frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
            // Add the status code 301 that indicates that the user was banned
            frag.addElement("status").addAttribute("code", "301");
            // Add the reason why the user was banned
            if (reason != null && reason.trim().length() > 0) {
                frag.element("item").addElement("reason").setText(reason);
            }

            // Remove the banned users from the room. If a user has joined the room from
            // different client resources, he/she will be kicked from all the client resources
            // Effectively kick the occupant from the room
            kickPresence(presence, actorJID);
        }
        return updatedPresences;
    }

1568 1569
    private boolean removeOutcast(JID bareJID) {
        return outcasts.remove(new JID(bareJID.toBareJID()));
1570 1571 1572 1573
    }

    public List<Presence> addNone(JID jid, MUCRole senderRole) throws ForbiddenException,
            ConflictException {
1574
    	final JID bareJID = new JID(jid.toBareJID());
1575
        List<Presence> updatedPresences = Collections.emptyList();
1576 1577 1578 1579 1580 1581 1582 1583 1584
        boolean wasMember = false;
        lock.writeLock().lock();
        try {
            MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
            if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                    && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
                throw new ForbiddenException();
            }
            // Check that the room always has an owner
1585
            if (owners.contains(bareJID) && owners.size() == 1) {
1586 1587
                throw new ConflictException();
            }
1588
            wasMember = members.containsKey(bareJID) || admins.contains(bareJID) || owners.contains(bareJID);
1589
            // Remove the user from ALL the affiliation lists
1590
            if (removeOwner(bareJID)) {
1591 1592
                oldAffiliation = MUCRole.Affiliation.owner;
            }
1593
            else if (removeAdmin(bareJID)) {
1594 1595
                oldAffiliation = MUCRole.Affiliation.admin;
            }
1596
            else if (removeMember(bareJID)) {
1597 1598
                oldAffiliation = MUCRole.Affiliation.member;
            }
1599
            else if (removeOutcast(bareJID)) {
1600 1601 1602
                oldAffiliation = MUCRole.Affiliation.outcast;
            }
            // Remove the affiliation of this user from the DB if the room is persistent
1603
            MUCPersistenceManager.removeAffiliationFromDB(this, bareJID, oldAffiliation);
1604
        }
1605 1606
        finally {
            lock.writeLock().unlock();
1607 1608 1609 1610 1611 1612 1613 1614 1615 1616
        }
        // Update the presence with the new affiliation and inform all occupants
        try {
            MUCRole.Role newRole;
            if (isMembersOnly() && wasMember) {
                newRole = MUCRole.Role.none;
            }
            else {
                newRole = isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant;
            }
1617
            updatedPresences = changeOccupantAffiliation(bareJID, MUCRole.Affiliation.none, newRole);
1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
            if (isMembersOnly() && wasMember) {
                // If the room is members-only, remove the user from the room including a status
                // code of 321 to indicate that the user was removed because of an affiliation
                // change
                Element frag;
                // Add the status code to the presences that will be sent to the room occupants
                for (Presence presence : updatedPresences) {
                    // Set the presence as an unavailable presence
                    presence.setType(Presence.Type.unavailable);
                    presence.setStatus(null);
                    frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
                    // Add the status code 321 that indicates that the user was removed because of
                    // an affiliation change
                    frag.addElement("status").addAttribute("code", "321");

                    // Remove the ex-member from the room. If a user has joined the room from
                    // different client resources, he/she will be kicked from all the client
                    // resources.
                    // Effectively kick the occupant from the room
                    JID actorJID = senderRole.getUserAddress();
                    kickPresence(presence, actorJID);
                }
            }
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
1644
        	Log.error(e.getMessage(), e);
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681
        }
        return updatedPresences;
    }

    public boolean isLocked() {
        return lockedTime > 0;
    }

    public boolean isManuallyLocked() {
        return lockedTime > 0 && creationDate.getTime() != lockedTime;
    }

    public void presenceUpdated(MUCRole occupantRole, Presence newPresence) {
        // Ask other cluster nodes to update the presence of the occupant
        UpdatePresence request = new UpdatePresence(this, newPresence.createCopy(), occupantRole.getNickname());
        CacheFactory.doClusterTask(request);

        // Update the presence of the occupant
        request = new UpdatePresence(this, newPresence.createCopy(), occupantRole.getNickname());
        request.setOriginator(true);
        request.run();

        // Broadcast new presence of occupant
        broadcastPresence(occupantRole.getPresence().createCopy());
    }

    /**
     * Updates the presence of an occupant with the new presence included in the request.
     *
     * @param updatePresence request to update an occupant's presence.
     */
    public void presenceUpdated(UpdatePresence updatePresence) {
        MUCRole occupantRole = occupants.get(updatePresence.getNickname().toLowerCase());
        if (occupantRole != null) {
            occupantRole.setPresence(updatePresence.getPresence());
        }
        else {
1682
            Log.debug("LocalMUCRoom: Failed to update presence of room occupant. Occupant nickname: " + updatePresence.getNickname());
1683 1684 1685 1686
        }
    }

    public void occupantUpdated(UpdateOccupant update) {
1687
        MUCRole occupantRole = occupants.get(update.getNickname().toLowerCase());
1688
        if (occupantRole != null) {
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699
            if (!occupantRole.isLocal()) {
                occupantRole.setPresence(update.getPresence());
                try {
                    occupantRole.setRole(update.getRole());
                    occupantRole.setAffiliation(update.getAffiliation());
                } catch (NotAllowedException e) {
                    // Ignore. Should never happen with remote roles
                }
            }
            else {
                Log.error("Tried to update local occupant with info of local occupant?. Occupant nickname: " +
1700 1701
                        update.getNickname() + " new role: " + update.getRole() + " new affiliation: " +
                        update.getAffiliation());
1702
            }
1703 1704
        }
        else {
1705
            Log.debug("LocalMUCRoom: Failed to update information of room occupant. Occupant nickname: " + update.getNickname());
1706 1707 1708
        }
    }

1709 1710 1711
    public Presence updateOccupant(UpdateOccupantRequest updateRequest) throws NotAllowedException {
        MUCRole occupantRole = occupants.get(updateRequest.getNickname().toLowerCase());
        if (occupantRole != null) {
1712 1713 1714
            if (updateRequest.isAffiliationChanged()) {
                occupantRole.setAffiliation(updateRequest.getAffiliation());
            }
1715 1716 1717 1718 1719 1720
            occupantRole.setRole(updateRequest.getRole());
            // Notify the othe cluster nodes to update the occupant
            CacheFactory.doClusterTask(new UpdateOccupant(this, occupantRole));
            return occupantRole.getPresence();
        }
        else {
1721
            Log.debug("LocalMUCRoom: Failed to update information of local room occupant. Occupant nickname: " +
1722 1723 1724 1725 1726
                    updateRequest.getNickname());
        }
        return null;
    }

1727 1728 1729 1730 1731
    public void memberAdded(AddMember addMember) {
        // Associate the reserved nickname with the bareJID
        members.put(addMember.getBareJID(), addMember.getNickname());
    }

1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751
    public void nicknameChanged(MUCRole occupantRole, Presence newPresence, String oldNick, String newNick) {
        // Ask other cluster nodes to update the nickname of the occupant
        ChangeNickname request = new ChangeNickname(this, oldNick,  newNick, newPresence.createCopy());
        CacheFactory.doClusterTask(request);

        // Update the nickname of the occupant
        request = new ChangeNickname(this, oldNick,  newNick, newPresence.createCopy());
        request.setOriginator(true);
        request.run();

        // Broadcast new presence of occupant
        broadcastPresence(occupantRole.getPresence().createCopy());
    }

    public void nicknameChanged(ChangeNickname changeNickname) {
        MUCRole occupantRole = occupants.get(changeNickname.getOldNick().toLowerCase());
        if (occupantRole != null) {
            // Update the role with the new info
            occupantRole.setPresence(changeNickname.getPresence());
            occupantRole.changeNickname(changeNickname.getNewNick());
1752 1753
            if (changeNickname.isOriginator()) {
                // Fire event that user changed his nickname
1754
                MUCEventDispatcher.nicknameChanged(getRole().getRoleAddress(), occupantRole.getUserAddress(),
1755 1756
                        changeNickname.getOldNick(), changeNickname.getNewNick());
            }
1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776
            // Associate the existing MUCRole with the new nickname
            occupants.put(changeNickname.getNewNick().toLowerCase(), occupantRole);
            // Remove the old nickname
            occupants.remove(changeNickname.getOldNick().toLowerCase());
        }
    }

    public void changeSubject(Message packet, MUCRole role) throws ForbiddenException {
        if ((canOccupantsChangeSubject() && role.getRole().compareTo(MUCRole.Role.visitor) < 0) ||
                MUCRole.Role.moderator == role.getRole()) {
            // Do nothing if the new subject is the same as the existing one
            if (packet.getSubject().equals(subject)) {
                return;
            }
            // Set the new subject to the room
            subject = packet.getSubject();
            MUCPersistenceManager.updateRoomSubject(this);
            // Notify all the occupants that the subject has changed
            packet.setFrom(role.getRoleAddress());
            send(packet);
1777 1778 1779

            // Fire event signifying that the room's subject has changed.
            MUCEventDispatcher.roomSubjectChanged(getJID(), role.getUserAddress(), subject);
1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794
        }
        else {
            throw new ForbiddenException();
        }
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public void sendInvitation(JID to, String reason, MUCRole senderRole, List<Element> extensions)
1795
            throws ForbiddenException, CannotBeInvitedException {
1796 1797 1798 1799 1800 1801 1802 1803
        if (!isMembersOnly() || canOccupantsInvite()
                || MUCRole.Affiliation.admin == senderRole.getAffiliation()
                || MUCRole.Affiliation.owner == senderRole.getAffiliation()) {
            // If the room is not members-only OR if the room is members-only and anyone can send
            // invitations or the sender is an admin or an owner, then send the invitation
            Message message = new Message();
            message.setFrom(role.getRoleAddress());
            message.setTo(to);
1804 1805

            if (((MultiUserChatServiceImpl)mucService).getMUCDelegate() != null) {
1806
                switch(((MultiUserChatServiceImpl)mucService).getMUCDelegate().sendingInvitation(this, to, senderRole.getUserAddress(), reason)) {
1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818
                    case HANDLED_BY_DELEGATE:
                        //if the delegate is taking care of it, there's nothing for us to do
                        return;
                    case HANDLED_BY_OPENFIRE:
                        //continue as normal if we're asked to handle it
                        break;
                    case REJECTED:
                        //we can't invite that person
                        throw new CannotBeInvitedException();
                }
            }

1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879
            // Add a list of extensions sent with the original message invitation (if any)
            if (extensions != null) {
                for(Element element : extensions) {
                    element.setParent(null);
                    message.getElement().add(element);
                }
            }
            Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
            // ChatUser will be null if the room itself (ie. via admin console) made the request
            if (senderRole.getUserAddress() != null) {
                frag.addElement("invite").addAttribute("from", senderRole.getUserAddress().toBareJID());
            }
            if (reason != null && reason.length() > 0) {
                Element invite = frag.element("invite");
                if (invite == null) {
                    invite = frag.addElement("invite");
                }
                invite.addElement("reason").setText(reason);
            }
            if (isPasswordProtected()) {
                frag.addElement("password").setText(getPassword());
            }

            // Include the jabber:x:conference information for backward compatibility
            frag = message.addChildElement("x", "jabber:x:conference");
            frag.addAttribute("jid", role.getRoleAddress().toBareJID());

            // Send the message with the invitation
            router.route(message);
        }
        else {
            throw new ForbiddenException();
        }
    }

    public void sendInvitationRejection(JID to, String reason, JID sender) {
        Message message = new Message();
        message.setFrom(role.getRoleAddress());
        message.setTo(to);
        Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
        frag.addElement("decline").addAttribute("from", sender.toBareJID());
        if (reason != null && reason.length() > 0) {
            frag.element("decline").addElement("reason").setText(reason);
        }

        // Send the message with the invitation
        router.route(message);
    }

    public IQOwnerHandler getIQOwnerHandler() {
        return iqOwnerHandler;
    }

    public IQAdminHandler getIQAdminHandler() {
        return iqAdminHandler;
    }

    public MUCRoomHistory getRoomHistory() {
        return roomHistory;
    }

1880
    public Collection<JID> getOwners() {
1881 1882 1883
        return Collections.unmodifiableList(owners);
    }

1884
    public Collection<JID> getAdmins() {
1885 1886 1887
        return Collections.unmodifiableList(admins);
    }

1888
    public Collection<JID> getMembers() {
1889 1890 1891
        return Collections.unmodifiableMap(members).keySet();
    }

1892
    public Collection<JID> getOutcasts() {
1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981
        return Collections.unmodifiableList(outcasts);
    }

    public Collection<MUCRole> getModerators() {
        List<MUCRole> moderators = new ArrayList<MUCRole>();
        for (MUCRole role : occupants.values()) {
            if (MUCRole.Role.moderator == role.getRole()) {
                moderators.add(role);
            }
        }
        return moderators;
    }

    public Collection<MUCRole> getParticipants() {
        List<MUCRole> participants = new ArrayList<MUCRole>();
        for (MUCRole role : occupants.values()) {
            if (MUCRole.Role.participant == role.getRole()) {
                participants.add(role);
            }
        }
        return participants;
    }

    public Presence addModerator(JID jid, MUCRole senderRole) throws ForbiddenException {
        if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
            throw new ForbiddenException();
        }
        // Update the presence with the new role and inform all occupants
        try {
            return changeOccupantRole(jid, MUCRole.Role.moderator);
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

    public Presence addParticipant(JID jid, String reason, MUCRole senderRole)
            throws NotAllowedException, ForbiddenException {
        if (MUCRole.Role.moderator != senderRole.getRole()) {
            throw new ForbiddenException();
        }
        // Update the presence with the new role and inform all occupants
        Presence updatedPresence = changeOccupantRole(jid, MUCRole.Role.participant);
        if (updatedPresence != null) {
            Element frag = updatedPresence.getChildElement(
                    "x", "http://jabber.org/protocol/muc#user");
            // Add the reason why the user was granted voice
            if (reason != null && reason.trim().length() > 0) {
                frag.element("item").addElement("reason").setText(reason);
            }
        }
        return updatedPresence;
    }

    public Presence addVisitor(JID jid, MUCRole senderRole) throws NotAllowedException,
            ForbiddenException {
        if (MUCRole.Role.moderator != senderRole.getRole()) {
            throw new ForbiddenException();
        }
        return changeOccupantRole(jid, MUCRole.Role.visitor);
    }

    public Presence kickOccupant(JID jid, JID actorJID, String reason)
            throws NotAllowedException {
        // Update the presence with the new role and inform all occupants
        Presence updatedPresence = changeOccupantRole(jid, MUCRole.Role.none);
        if (updatedPresence != null) {
            Element frag = updatedPresence.getChildElement(
                    "x", "http://jabber.org/protocol/muc#user");

            // Add the status code 307 that indicates that the user was kicked
            frag.addElement("status").addAttribute("code", "307");
            // Add the reason why the user was kicked
            if (reason != null && reason.trim().length() > 0) {
                frag.element("item").addElement("reason").setText(reason);
            }

            // Effectively kick the occupant from the room
            kickPresence(updatedPresence, actorJID);
        }
        return updatedPresence;
    }

    /**
     * Kicks the occupant from the room. This means that the occupant will receive an unavailable
     * presence with the actor that initiated the kick (if any). The occupant will also be removed
     * from the occupants lists.
1982
     *
1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067
     * @param kickPresence the presence of the occupant to kick from the room.
     * @param actorJID The JID of the actor that initiated the kick or <tt>null</tt> if the info
     * was not provided.
     */
    private void kickPresence(Presence kickPresence, JID actorJID) {
        MUCRole kickedRole;
        // Get the role to kick
        kickedRole = occupants.get(kickPresence.getFrom().getResource().toLowerCase());
        if (kickedRole != null) {
            kickPresence = kickPresence.createCopy();
            // Add the actor's JID that kicked this user from the room
            if (actorJID != null && actorJID.toString().length() > 0) {
                Element frag = kickPresence.getChildElement(
                        "x", "http://jabber.org/protocol/muc#user");
                frag.element("item").addElement("actor").addAttribute("jid", actorJID.toBareJID());
            }
            // Send the unavailable presence to the banned user
            kickedRole.send(kickPresence);
            // Remove the occupant from the room's occupants lists
            OccupantLeftEvent event = new OccupantLeftEvent(this, kickedRole);
            event.setOriginator(true);
            event.run();

            // Remove the occupant from the room's occupants lists
            event = new OccupantLeftEvent(this, kickedRole);
            CacheFactory.doClusterTask(event);
        }
    }

    public boolean canAnyoneDiscoverJID() {
        return canAnyoneDiscoverJID;
    }

    public void setCanAnyoneDiscoverJID(boolean canAnyoneDiscoverJID) {
        this.canAnyoneDiscoverJID = canAnyoneDiscoverJID;
    }

    public boolean canOccupantsChangeSubject() {
        return canOccupantsChangeSubject;
    }

    public void setCanOccupantsChangeSubject(boolean canOccupantsChangeSubject) {
        this.canOccupantsChangeSubject = canOccupantsChangeSubject;
    }

    public boolean canOccupantsInvite() {
        return canOccupantsInvite;
    }

    public void setCanOccupantsInvite(boolean canOccupantsInvite) {
        this.canOccupantsInvite = canOccupantsInvite;
    }

    public String getNaturalLanguageName() {
        return naturalLanguageName;
    }

    public void setNaturalLanguageName(String naturalLanguageName) {
        this.naturalLanguageName = naturalLanguageName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public boolean isMembersOnly() {
        return membersOnly;
    }

    public List<Presence> setMembersOnly(boolean membersOnly) {
        List<Presence> presences = new ArrayList<Presence>();
        if (membersOnly && !this.membersOnly) {
            // If the room was not members-only and now it is, kick occupants that aren't member
            // of the room
            for (MUCRole occupant : occupants.values()) {
                if (occupant.getAffiliation().compareTo(MUCRole.Affiliation.member) > 0) {
                    try {
                        presences.add(kickOccupant(occupant.getRoleAddress(), null,
                                LocaleUtils.getLocalizedString("muc.roomIsNowMembersOnly")));
                    }
                    catch (NotAllowedException e) {
2068
                        Log.error(e.getMessage(), e);
2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143
                    }
                }
            }
        }
        this.membersOnly = membersOnly;
        return presences;
    }

    public boolean isLogEnabled() {
        return logEnabled;
    }

    public void setLogEnabled(boolean logEnabled) {
        this.logEnabled = logEnabled;
    }

    public void setLoginRestrictedToNickname(boolean restricted) {
        this.loginRestrictedToNickname = restricted;
    }

    public boolean isLoginRestrictedToNickname() {
        return loginRestrictedToNickname;
    }

    public void setChangeNickname(boolean canChange) {
        this.canChangeNickname = canChange;
    }

    public boolean canChangeNickname() {
        return canChangeNickname;
    }

    public void setRegistrationEnabled(boolean registrationEnabled) {
        this.registrationEnabled = registrationEnabled;
    }

    public boolean isRegistrationEnabled() {
        return registrationEnabled;
    }

    public int getMaxUsers() {
        return maxUsers;
    }

    public void setMaxUsers(int maxUsers) {
        this.maxUsers = maxUsers;
    }

    public boolean isModerated() {
        return moderated;
    }

    public void setModerated(boolean moderated) {
        this.moderated = moderated;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isPasswordProtected() {
        return password != null && password.trim().length() > 0;
    }

    public boolean isPersistent() {
        return persistent;
    }

    public boolean wasSavedToDB() {
        return isPersistent() && savedToDB;
    }
2144

2145 2146 2147
    public void setSavedToDB(boolean saved) {
        this.savedToDB = saved;
    }
2148

2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256
    public void setPersistent(boolean persistent) {
        this.persistent = persistent;
    }

    public boolean isPublicRoom() {
        return !isDestroyed && publicRoom;
    }

    public void setPublicRoom(boolean publicRoom) {
        this.publicRoom = publicRoom;
    }

    public List<String> getRolesToBroadcastPresence() {
        return Collections.unmodifiableList(rolesToBroadcastPresence);
    }

    public void setRolesToBroadcastPresence(List<String> rolesToBroadcastPresence) {
        // TODO If the list changes while there are occupants in the room we must send available or
        // unavailable presences of the affected occupants to the rest of the occupants
        this.rolesToBroadcastPresence = rolesToBroadcastPresence;
    }

    /**
     * Returns true if we need to check whether a presence could be sent or not.
     *
     * @return true if we need to check whether a presence could be sent or not.
     */
    private boolean hasToCheckRoleToBroadcastPresence() {
        // For performance reasons the check is done based on the size of the collection.
        return rolesToBroadcastPresence.size() < 3;
    }

    public boolean canBroadcastPresence(String roleToBroadcast) {
        return "none".equals(roleToBroadcast) || rolesToBroadcastPresence.contains(roleToBroadcast);
    }

    public void lock(MUCRole senderRole) throws ForbiddenException {
        if (MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
            throw new ForbiddenException();
        }
        if (isLocked()) {
            // Do nothing if the room was already locked
            return;
        }
        setLocked(true);
        if (senderRole.getUserAddress() != null) {
            // Send to the occupant that locked the room a message saying so
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.locked"));
            message.setFrom(getRole().getRoleAddress());
            senderRole.send(message);
        }
    }

    public void unlock(MUCRole senderRole) throws ForbiddenException {
        if (MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
            throw new ForbiddenException();
        }
        if (!isLocked()) {
            // Do nothing if the room was already unlocked
            return;
        }
        setLocked(false);
        if (senderRole.getUserAddress() != null) {
            // Send to the occupant that unlocked the room a message saying so
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.unlocked"));
            message.setFrom(getRole().getRoleAddress());
            senderRole.send(message);
        }
    }

    private void setLocked(boolean locked) {
        if (locked) {
            this.lockedTime = System.currentTimeMillis();
        }
        else {
            this.lockedTime = 0;
        }
        MUCPersistenceManager.updateRoomLock(this);
    }

    /**
     * Sets the date when the room was locked. Initially when the room is created it is locked so
     * the locked date is the creation date of the room. Afterwards, the room may be manually
     * locked and unlocked so the locked date may be in these cases different than the creation
     * date. A Date with time 0 means that the the room is unlocked.
     *
     * @param lockedTime the date when the room was locked.
     */
    void setLockedDate(Date lockedTime) {
        this.lockedTime = lockedTime.getTime();
    }

    /**
     * Returns the date when the room was locked. Initially when the room is created it is locked so
     * the locked date is the creation date of the room. Afterwards, the room may be manually
     * locked and unlocked so the locked date may be in these cases different than the creation
     * date. When the room is unlocked a Date with time 0 is returned.
     *
     * @return the date when the room was locked.
     */
    Date getLockedDate() {
        return new Date(lockedTime);
    }

2257
    public List<Presence> addAdmins(List<JID> newAdmins, MUCRole senderRole)
2258 2259
            throws ForbiddenException, ConflictException {
        List<Presence> answer = new ArrayList<Presence>(newAdmins.size());
2260 2261 2262 2263
        for (JID newAdmin : newAdmins) {
        	final JID bareJID = new JID(newAdmin.toBareJID());
            if (!admins.contains(bareJID)) {
                answer.addAll(addAdmin(bareJID, senderRole));
2264 2265 2266 2267 2268
            }
        }
        return answer;
    }

2269
    public List<Presence> addOwners(List<JID> newOwners, MUCRole senderRole)
2270 2271
            throws ForbiddenException {
        List<Presence> answer = new ArrayList<Presence>(newOwners.size());
2272 2273 2274 2275
        for (JID newOwner : newOwners) {
        	final JID bareJID = new JID(newOwner.toBareJID());
            if (!owners.contains(newOwner)) {
                answer.addAll(addOwner(bareJID, senderRole));
2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287
            }
        }
        return answer;
    }

    public void saveToDB() {
        // Make the room persistent
        MUCPersistenceManager.saveToDB(this);
        if (!savedToDB) {
            // Set that the room is now in the DB
            savedToDB = true;
            // Save the existing room owners to the DB
2288
            for (JID owner : owners) {
2289 2290 2291 2292 2293 2294 2295 2296
                MUCPersistenceManager.saveAffiliationToDB(
                    this,
                    owner,
                    null,
                    MUCRole.Affiliation.owner,
                    MUCRole.Affiliation.none);
            }
            // Save the existing room admins to the DB
2297
            for (JID admin : admins) {
2298 2299 2300 2301 2302 2303 2304 2305
                MUCPersistenceManager.saveAffiliationToDB(
                    this,
                    admin,
                    null,
                    MUCRole.Affiliation.admin,
                    MUCRole.Affiliation.none);
            }
            // Save the existing room members to the DB
2306
            for (JID bareJID : members.keySet()) {
2307 2308 2309 2310
                MUCPersistenceManager.saveAffiliationToDB(this, bareJID, members.get(bareJID),
                        MUCRole.Affiliation.member, MUCRole.Affiliation.none);
            }
            // Save the existing room outcasts to the DB
2311
            for (JID outcast : outcasts) {
2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325
                MUCPersistenceManager.saveAffiliationToDB(
                    this,
                    outcast,
                    null,
                    MUCRole.Affiliation.outcast,
                    MUCRole.Affiliation.none);
            }
        }
    }

    public void writeExternal(ObjectOutput out) throws IOException {
        ExternalizableUtil.getInstance().writeSafeUTF(out, name);
        ExternalizableUtil.getInstance().writeLong(out, startTime);
        ExternalizableUtil.getInstance().writeLong(out, lockedTime);
2326 2327 2328 2329
        ExternalizableUtil.getInstance().writeSerializableCollection(out, owners);
        ExternalizableUtil.getInstance().writeSerializableCollection(out, admins);
        ExternalizableUtil.getInstance().writeSerializableMap(out, members);
        ExternalizableUtil.getInstance().writeSerializableCollection(out, outcasts);
2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
        ExternalizableUtil.getInstance().writeSafeUTF(out, naturalLanguageName);
        ExternalizableUtil.getInstance().writeSafeUTF(out, description);
        ExternalizableUtil.getInstance().writeBoolean(out, canOccupantsChangeSubject);
        ExternalizableUtil.getInstance().writeInt(out, maxUsers);
        ExternalizableUtil.getInstance().writeStringList(out, rolesToBroadcastPresence);
        ExternalizableUtil.getInstance().writeBoolean(out, publicRoom);
        ExternalizableUtil.getInstance().writeBoolean(out, persistent);
        ExternalizableUtil.getInstance().writeBoolean(out, moderated);
        ExternalizableUtil.getInstance().writeBoolean(out, membersOnly);
        ExternalizableUtil.getInstance().writeBoolean(out, canOccupantsInvite);
        ExternalizableUtil.getInstance().writeSafeUTF(out, password);
        ExternalizableUtil.getInstance().writeBoolean(out, canAnyoneDiscoverJID);
        ExternalizableUtil.getInstance().writeBoolean(out, logEnabled);
        ExternalizableUtil.getInstance().writeBoolean(out, loginRestrictedToNickname);
        ExternalizableUtil.getInstance().writeBoolean(out, canChangeNickname);
        ExternalizableUtil.getInstance().writeBoolean(out, registrationEnabled);
        ExternalizableUtil.getInstance().writeSafeUTF(out, subject);
        ExternalizableUtil.getInstance().writeLong(out, roomID);
        ExternalizableUtil.getInstance().writeLong(out, creationDate.getTime());
        ExternalizableUtil.getInstance().writeLong(out, modificationDate.getTime());
        ExternalizableUtil.getInstance().writeBoolean(out, emptyDate != null);
        if (emptyDate != null) {
            ExternalizableUtil.getInstance().writeLong(out, emptyDate.getTime());
        }
        ExternalizableUtil.getInstance().writeBoolean(out, savedToDB);
2355
        ExternalizableUtil.getInstance().writeSafeUTF(out, mucService.getServiceName());
2356 2357 2358 2359 2360 2361
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = ExternalizableUtil.getInstance().readSafeUTF(in);
        startTime = ExternalizableUtil.getInstance().readLong(in);
        lockedTime = ExternalizableUtil.getInstance().readLong(in);
2362 2363 2364 2365
        ExternalizableUtil.getInstance().readSerializableCollection(in, owners, getClass().getClassLoader());
        ExternalizableUtil.getInstance().readSerializableCollection(in, admins, getClass().getClassLoader());
        ExternalizableUtil.getInstance().readSerializableMap(in, members, getClass().getClassLoader());
        ExternalizableUtil.getInstance().readSerializableCollection(in, outcasts, getClass().getClassLoader());
2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389
        naturalLanguageName = ExternalizableUtil.getInstance().readSafeUTF(in);
        description = ExternalizableUtil.getInstance().readSafeUTF(in);
        canOccupantsChangeSubject = ExternalizableUtil.getInstance().readBoolean(in);
        maxUsers = ExternalizableUtil.getInstance().readInt(in);
        rolesToBroadcastPresence.addAll(ExternalizableUtil.getInstance().readStringList(in));
        publicRoom = ExternalizableUtil.getInstance().readBoolean(in);
        persistent = ExternalizableUtil.getInstance().readBoolean(in);
        moderated = ExternalizableUtil.getInstance().readBoolean(in);
        membersOnly = ExternalizableUtil.getInstance().readBoolean(in);
        canOccupantsInvite = ExternalizableUtil.getInstance().readBoolean(in);
        password = ExternalizableUtil.getInstance().readSafeUTF(in);
        canAnyoneDiscoverJID = ExternalizableUtil.getInstance().readBoolean(in);
        logEnabled = ExternalizableUtil.getInstance().readBoolean(in);
        loginRestrictedToNickname = ExternalizableUtil.getInstance().readBoolean(in);
        canChangeNickname = ExternalizableUtil.getInstance().readBoolean(in);
        registrationEnabled = ExternalizableUtil.getInstance().readBoolean(in);
        subject = ExternalizableUtil.getInstance().readSafeUTF(in);
        roomID = ExternalizableUtil.getInstance().readLong(in);
        creationDate = new Date(ExternalizableUtil.getInstance().readLong(in));
        modificationDate = new Date(ExternalizableUtil.getInstance().readLong(in));
        if (ExternalizableUtil.getInstance().readBoolean(in)) {
            emptyDate = new Date(ExternalizableUtil.getInstance().readLong(in));
        }
        savedToDB = ExternalizableUtil.getInstance().readBoolean(in);
2390
        String subdomain = ExternalizableUtil.getInstance().readSafeUTF(in);
2391 2392
        mucService = XMPPServer.getInstance().getMultiUserChatManager().getMultiUserChatService(subdomain);
        if (mucService == null) throw new IllegalArgumentException("MUC service not found for subdomain: " + subdomain);
2393
        roomHistory = new MUCRoomHistory(this, new HistoryStrategy(mucService.getHistoryStrategy()));
2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430

        PacketRouter packetRouter = XMPPServer.getInstance().getPacketRouter();
        this.iqOwnerHandler = new IQOwnerHandler(this, packetRouter);
        this.iqAdminHandler = new IQAdminHandler(this, packetRouter);

        router = packetRouter;
    }

    public void updateConfiguration(LocalMUCRoom otherRoom) {
        startTime = otherRoom.startTime;
        lockedTime = otherRoom.lockedTime;
        owners = otherRoom.owners;
        admins = otherRoom.admins;
        members = otherRoom.members;
        outcasts = otherRoom.outcasts;
        naturalLanguageName = otherRoom.naturalLanguageName;
        description = otherRoom.description;
        canOccupantsChangeSubject = otherRoom.canOccupantsChangeSubject;
        maxUsers = otherRoom.maxUsers;
        rolesToBroadcastPresence = otherRoom.rolesToBroadcastPresence;
        publicRoom = otherRoom.publicRoom;
        persistent = otherRoom.persistent;
        moderated = otherRoom.moderated;
        membersOnly = otherRoom.membersOnly;
        canOccupantsInvite = otherRoom.canOccupantsInvite;
        password = otherRoom.password;
        canAnyoneDiscoverJID = otherRoom.canAnyoneDiscoverJID;
        logEnabled = otherRoom.logEnabled;
        loginRestrictedToNickname = otherRoom.loginRestrictedToNickname;
        canChangeNickname = otherRoom.canChangeNickname;
        registrationEnabled = otherRoom.registrationEnabled;
        subject = otherRoom.subject;
        roomID = otherRoom.roomID;
        creationDate = otherRoom.creationDate;
        modificationDate = otherRoom.modificationDate;
        emptyDate = otherRoom.emptyDate;
        savedToDB = otherRoom.savedToDB;
2431
        mucService = otherRoom.mucService;
2432
    }
2433 2434 2435 2436 2437 2438 2439 2440 2441 2442

    /*
     * (non-Javadoc)
     * @see org.jivesoftware.util.resultsetmanager.Result#getUID()
     */
	public String getUID()
	{
		// name is unique for each one particular MUC service.
		return name;
	}
2443
}