Group.java 19.7 KB
Newer Older
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision: 3127 $
 * $Date: 2005-11-30 15:26:07 -0300 (Wed, 30 Nov 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
package org.jivesoftware.openfire.group;
22

Gaston Dombiak's avatar
Gaston Dombiak committed
23
import java.io.Externalizable;
24
import java.io.IOException;
Gaston Dombiak's avatar
Gaston Dombiak committed
25 26
import java.io.ObjectInput;
import java.io.ObjectOutput;
27 28
import java.util.AbstractCollection;
import java.util.Collection;
29
import java.util.Collections;
30 31 32 33 34
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
35

36 37
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.openfire.event.GroupEventDispatcher;
38
import org.jivesoftware.util.PersistableMap;
39 40
import org.jivesoftware.util.cache.CacheSizes;
import org.jivesoftware.util.cache.Cacheable;
41
import org.jivesoftware.util.cache.CannotCalculateSizeException;
42 43 44 45 46
import org.jivesoftware.util.cache.ExternalizableUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmpp.packet.JID;

47
/**
48 49 50 51
 * Groups organize users into a single entity for easier management.<p>
 *
 * The actual group implementation is controlled by the {@link GroupProvider}, which
 * includes things like the group name, the members, and adminstrators. Each group
52
 * also has properties, which are always stored in the Openfire database.
53 54 55 56 57
 *
 * @see GroupManager#createGroup(String)
 *
 * @author Matt Tucker
 */
Gaston Dombiak's avatar
Gaston Dombiak committed
58
public class Group implements Cacheable, Externalizable {
59

60 61
	private static final Logger Log = LoggerFactory.getLogger(Group.class);

62 63
    private transient GroupProvider provider;
    private transient GroupManager groupManager;
64
    private transient PersistableMap<String, String> properties;
65
    private transient GroupJID jid;
66

67 68 69 70 71
    private String name;
    private String description;
    private Set<JID> members;
    private Set<JID> administrators;

Gaston Dombiak's avatar
Gaston Dombiak committed
72 73 74 75 76 77
    /**
     * Constructor added for Externalizable. Do not use this constructor.
     */
    public Group() {
    }

78 79 80 81 82 83 84 85 86 87
    /**
     * Constructs a new group. Note: this constructor is intended for implementors of the
     * {@link GroupProvider} interface. To create a new group, use the
     * {@link GroupManager#createGroup(String)} method. 
     *
     * @param name the name.
     * @param description the description.
     * @param members a Collection of the group members.
     * @param administrators a Collection of the group administrators.
     */
88 89
    public Group(String name, String description, Collection<JID> members,
            Collection<JID> administrators)
90 91
    {
        this.groupManager = GroupManager.getInstance();
92
        this.provider = groupManager.getProvider();
93 94 95 96 97 98
        this.name = name;
        this.description = description;
        this.members = new HashSet<JID>(members);
        this.administrators = new HashSet<JID>(administrators);
    }

99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    /**
     * Constructs a new group. Note: this constructor is intended for implementors of the
     * {@link GroupProvider} interface. To create a new group, use the
     * {@link GroupManager#createGroup(String)} method.
     *
     * @param name the name.
     * @param description the description.
     * @param members a Collection of the group members.
     * @param administrators a Collection of the group administrators.
     * @param properties a Map of properties with names and its values.
     */
    public Group(String name, String description, Collection<JID> members,
            Collection<JID> administrators, Map<String, String> properties)
    {
        this.groupManager = GroupManager.getInstance();
        this.provider = groupManager.getProvider();
        this.name = name;
        this.description = description;
        this.members = new HashSet<JID>(members);
        this.administrators = new HashSet<JID>(administrators);

120 121
        this.properties = provider.loadProperties(this);
        
122 123 124 125 126 127 128 129 130 131 132 133
        // Apply the given properties to the group
        for (Map.Entry<String, String> property : properties.entrySet()) {
            if (!property.getValue().equals(this.properties.get(property.getKey()))) {
                this.properties.put(property.getKey(), property.getValue());
            }
        }
        // Remove obsolete properties
        Iterator<String> oldProps = this.properties.keySet().iterator();
        while (oldProps.hasNext()) {
            if (!properties.containsKey(oldProps.next())) {
            	oldProps.remove();
            }
134 135 136
        }
    }

137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    /**
     * Returns a JID for the group based on the group name. This
     * instance will be of class GroupJID to distinguish it from
     * other types of JIDs in the system.
     * 
     * This method is synchronized to ensure each group has only
     * a single JID instance created via lazy instantiation.
     *
     * @return A JID for the group.
     */
    public synchronized GroupJID getJID() {
    	if (jid == null) {
    		jid = new GroupJID(getName());
    	}
        return jid;
    }

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
    /**
     * Returns the name of the group. For example, 'XYZ Admins'.
     *
     * @return the name of the group.
     */
    public String getName() {
        return name;
    }

    /**
     * Sets the name of the group. For example, 'XYZ Admins'. This
     * method is restricted to those with group administration permission.
     *
     * @param name the name for the group.
     */
    public void setName(String name) {
Gaston Dombiak's avatar
Gaston Dombiak committed
170 171
        if (name == this.name || (name != null && name.equals(this.name)) || provider.isReadOnly())
        {
Gaston Dombiak's avatar
Gaston Dombiak committed
172
            // Do nothing
173 174
            return;
        }
175 176
        try {
            String originalName = this.name;
177
            GroupJID originalJID = getJID();
178
            provider.setName(originalName, name);
179
            this.name = name;
180
            this.jid = null; // rebuilt when needed
181 182 183 184 185

            // Fire event.
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("type", "nameModified");
            params.put("originalValue", originalName);
186
            params.put("originalJID", originalJID);
187 188 189
            GroupEventDispatcher.dispatchEvent(this, GroupEventDispatcher.EventType.group_modified,
                    params);
        }
190 191
        catch (GroupAlreadyExistsException e) {
            Log.error("Failed to change group name; group already exists");
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
        }
    }

    /**
     * Returns the description of the group. The description often
     * summarizes a group's function, such as 'Administrators of the XYZ forum'.
     *
     * @return the description of the group.
     */
    public String getDescription() {
        return description;
    }

    /**
     * Sets the description of the group. The description often
     * summarizes a group's function, such as 'Administrators of
     * the XYZ forum'. This method is restricted to those with group
     * administration permission.
     *
     * @param description the description of the group.
     */
    public void setDescription(String description) {
214 215
        if (description == this.description || (description != null && description.equals(this.description)) ||
                provider.isReadOnly()) {
Gaston Dombiak's avatar
Gaston Dombiak committed
216 217 218
            // Do nothing
            return;
        }
219 220 221 222 223 224 225 226 227 228 229 230
        try {
            String originalDescription = this.description;
            provider.setDescription(name, description);
            this.description = description;
            // Fire event.
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("type", "descriptionModified");
            params.put("originalValue", originalDescription);
            GroupEventDispatcher.dispatchEvent(this,
                    GroupEventDispatcher.EventType.group_modified, params);
        }
        catch (Exception e) {
231
            Log.error(e.getMessage(), e);
232 233 234
        }
    }

235 236
    @Override
	public String toString() {
237 238 239 240
        return name;
    }

    /**
Gaston Dombiak's avatar
Gaston Dombiak committed
241 242 243
     * Returns all extended properties of the group. Groups have an arbitrary
     * number of extended properties. The returned collection can be modified
     * to add new properties or remove existing ones.
244 245 246
     *
     * @return the extended properties.
     */
247
    public PersistableMap<String,String> getProperties() {
248 249
        synchronized (this) {
            if (properties == null) {
250
                properties = provider.loadProperties(this);
251 252 253
            }
        }
        // Return a wrapper that will intercept add and remove commands.
254
        return properties;
255 256
    }

257 258 259 260 261 262 263 264 265 266 267
    /**
     * Returns a Collection of everyone in the group.
     *
     * @return a read-only Collection of the group administrators + members.
     */
    public Collection<JID> getAll() {
    	Set<JID> everybody = new HashSet<JID>(administrators);
    	everybody.addAll(members);
        return Collections.unmodifiableSet(everybody);
    }

268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288
    /**
     * Returns a Collection of the group administrators.
     *
     * @return a Collection of the group administrators.
     */
    public Collection<JID> getAdmins() {
        // Return a wrapper that will intercept add and remove commands.
        return new MemberCollection(administrators, true);
    }

    /**
     * Returns a Collection of the group members.
     *
     * @return a Collection of the group members.
     */
    public Collection<JID> getMembers() {
        // Return a wrapper that will intercept add and remove commands.
        return new MemberCollection(members, false);
    }

    /**
289
     * Returns true if the provided JID belongs to a user that is part of the group.
290 291 292 293 294
     *
     * @param user the JID address of the user to check.
     * @return true if the specified user is a group user.
     */
    public boolean isUser(JID user) {
295 296
        // Make sure that we are always checking bare JIDs 
        if (user != null && user.getResource() != null) {
297
            user = user.asBareJID();
298
        }
299 300 301 302 303 304 305 306 307 308 309
        return user != null && (members.contains(user) || administrators.contains(user));
    }

    /**
     * Returns true if the provided username belongs to a user of the group.
     *
     * @param username the username to check.
     * @return true if the provided username belongs to a user of the group.
     */
    public boolean isUser(String username) {
        if  (username != null) {
310
            return isUser(XMPPServer.getInstance().createJID(username, null, true));
311 312
        }
        else {
313 314 315 316
            return false;
        }
    }

317 318
    public int getCachedSize() 
	    throws CannotCalculateSizeException {
319 320 321 322 323 324
        // Approximate the size of the object in bytes by calculating the size
        // of each field.
        int size = 0;
        size += CacheSizes.sizeOfObject();              // overhead of object
        size += CacheSizes.sizeOfString(name);
        size += CacheSizes.sizeOfString(description);
325 326 327 328 329 330 331 332 333
        size += CacheSizes.sizeOfMap(properties);

        for (JID member: members) {
            size += CacheSizes.sizeOfString(member.toString());
        }
        for (JID admin: administrators) {
            size += CacheSizes.sizeOfString(admin.toString());
        }

334 335 336
        return size;
    }

337 338
    @Override
	public int hashCode() {
339 340 341
        return name.hashCode();
    }

342 343
    @Override
	public boolean equals(Object object) {
344 345 346 347 348 349 350 351 352 353
        if (this == object) {
            return true;
        }
        if (object != null && object instanceof Group) {
            return name.equals(((Group)object).getName());
        }
        else {
            return false;
        }
    }
354 355 356 357
    /**
     * Collection implementation that notifies the GroupProvider of any
     * changes to the collection.
     */
358
    private class MemberCollection extends AbstractCollection<JID> {
359 360 361 362 363 364 365 366 367

        private Collection<JID> users;
        private boolean adminCollection;

        public MemberCollection(Collection<JID> users, boolean adminCollection) {
            this.users = users;
            this.adminCollection = adminCollection;
        }

368 369
        @Override
		public Iterator<JID> iterator() {
Gaston Dombiak's avatar
Gaston Dombiak committed
370
            return new Iterator<JID>() {
371 372

                Iterator<JID> iter = users.iterator();
Gaston Dombiak's avatar
Gaston Dombiak committed
373
                JID current = null;
374 375 376 377 378

                public boolean hasNext() {
                    return iter.hasNext();
                }

Gaston Dombiak's avatar
Gaston Dombiak committed
379
                public JID next() {
380 381 382 383 384 385 386 387
                    current = iter.next();
                    return current;
                }

                public void remove() {
                    if (current == null) {
                        throw new IllegalStateException();
                    }
388 389 390 391
                    // Do nothing if the provider is read-only.
                    if (provider.isReadOnly()) {
                        return;
                    }
Gaston Dombiak's avatar
Gaston Dombiak committed
392
                    JID user = current;
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
                    // Remove the user from the collection in memory.
                    iter.remove();
                    // Remove the group user from the backend store.
                    provider.deleteMember(name, user);
                    // Fire event.
                    if (adminCollection) {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("admin", user.toString());
                        GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.admin_removed, params);
                    }
                    else {
                        Map<String, String> params = new HashMap<String, String>();
                        params.put("member", user.toString());
                        GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.member_removed, params);
                    }
                }
            };
        }

414 415
        @Override
		public int size() {
416 417 418
            return users.size();
        }

419
        @Override
420
		public boolean add(JID user) {
421 422 423 424 425 426
            // Do nothing if the provider is read-only.
            if (provider.isReadOnly()) {
                return false;
            }
            // Find out if the user was already a group user.
            boolean alreadyGroupUser;
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
            if (adminCollection) {
                alreadyGroupUser = members.contains(user);
            }
            else {
                alreadyGroupUser = administrators.contains(user);
            }
            if (users.add(user)) {
                if (alreadyGroupUser) {
                    // Update the group user privileges in the backend store.
                    provider.updateMember(name, user, adminCollection);
                }
                else {
                    // Add the group user to the backend store.
                    provider.addMember(name, user, adminCollection);
                }

                // Fire event.
444
                Map<String, String> params = new HashMap<String, String>();
445 446 447
                if (adminCollection) {
                    params.put("admin", user.toString());
                    if (alreadyGroupUser) {
448
                    	params.put("member", user.toString());
449 450 451 452 453 454 455 456 457
                        GroupEventDispatcher.dispatchEvent(Group.this,
                                    GroupEventDispatcher.EventType.member_removed, params);
                    }
                    GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.admin_added, params);
                }
                else {
                    params.put("member", user.toString());
                    if (alreadyGroupUser) {
458
                    	params.put("admin", user.toString());
459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484
                        GroupEventDispatcher.dispatchEvent(Group.this,
                                    GroupEventDispatcher.EventType.admin_removed, params);
                    }
                    GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.member_added, params);
                }
                // If the user was a member that became an admin or vice versa then remove the
                // user from the other collection
                if (alreadyGroupUser) {
                    if (adminCollection) {
                        if (members.contains(user)) {
                            members.remove(user);
                        }
                    }
                    else {
                        if (administrators.contains(user)) {
                            administrators.remove(user);
                        }
                    }
                }
                return true;
            }
            return false;
        }
    }

Gaston Dombiak's avatar
Gaston Dombiak committed
485 486
    public void writeExternal(ObjectOutput out) throws IOException {
        ExternalizableUtil.getInstance().writeSafeUTF(out, name);
487
        ExternalizableUtil.getInstance().writeBoolean(out, description != null);
Gaston Dombiak's avatar
Gaston Dombiak committed
488 489 490
        if (description != null) {
            ExternalizableUtil.getInstance().writeSafeUTF(out, description);
        }
491 492
        ExternalizableUtil.getInstance().writeSerializableCollection(out, members);
        ExternalizableUtil.getInstance().writeSerializableCollection(out, administrators);
Gaston Dombiak's avatar
Gaston Dombiak committed
493 494 495
    }

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
496 497 498
        groupManager = GroupManager.getInstance();
        provider = groupManager.getProvider();

Gaston Dombiak's avatar
Gaston Dombiak committed
499 500 501 502 503 504
        name = ExternalizableUtil.getInstance().readSafeUTF(in);
        if (ExternalizableUtil.getInstance().readBoolean(in)) {
            description = ExternalizableUtil.getInstance().readSafeUTF(in);
        }
        members= new HashSet<JID>();
        administrators = new HashSet<JID>();
505 506
        ExternalizableUtil.getInstance().readSerializableCollection(in, members, getClass().getClassLoader());
        ExternalizableUtil.getInstance().readSerializableCollection(in, administrators, getClass().getClassLoader());
Gaston Dombiak's avatar
Gaston Dombiak committed
507
    }
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
    
	/**
	 * Search for a JID within a group. If the given haystack is not resolvable
	 * to a group, this method returns false.
	 * 
	 * @param needle A JID, possibly a member/admin of the given group
	 * @param haystack Presumably a Group, a Group name, or a JID that represents a Group
	 * @return true if the JID (needle) is found in the group (haystack)
	 */
	public static boolean search(JID needle, Object haystack) {
		Group group = resolveFrom(haystack);
		return (group != null && group.isUser(needle));
	}
    
	/**
	 * Attempt to resolve the given object into a Group.
	 * 
	 * @param proxy Presumably a Group, a Group name, or a JID that represents a Group
	 * @return The corresponding group, or null if the proxy cannot be resolved as a group
	 */
	public static Group resolveFrom(Object proxy) {
		Group result = null;
		try {
			GroupManager groupManger = GroupManager.getInstance();
			if (proxy instanceof JID) {
				result = groupManger.getGroup((JID)proxy);
			} else if (proxy instanceof String) {
				result = groupManger.getGroup((String)proxy);
			} else if (proxy instanceof Group) {
				result = (Group) proxy;
			}
		} catch (GroupNotFoundException gnfe) {
			// ignore
		}
		return result;
	}
    
545
}