GroupImpl.java 13.8 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 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 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 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
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright (C) 1999-2003 CoolServlets, Inc. All rights reserved.
 *
 * This software is the proprietary information of CoolServlets, Inc.
 * Use is subject to license terms.
 */
package org.jivesoftware.messenger.auth.spi;

import org.jivesoftware.util.CacheManager;
import org.jivesoftware.util.CacheSizes;
import org.jivesoftware.util.Cache;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.Entity;
import org.jivesoftware.messenger.auth.*;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.spi.UserIterator;
import java.util.*;

/**
 * Database implementation of the Group interface.
 *
 * @author Matt Tucker
 * @author Bruce Ritchie
 * @author Iain Shigeoka
 * @see Group
 */
public class GroupImpl implements Group, Cacheable {

    private GroupProvider provider = AuthProviderFactory.getGroupProvider();

    private long groupID;
    private String name = null;
    private String description = " ";
    private Date creationDate;
    private Date modificationDate;
    private Map properties;
    private long[] memberList;
    private long[] adminList;
    private Cache groupCache;
    private Cache groupMemberCache;

    /**
     * <p>Creates a group with the given settings.</p>
     *
     * @param id               The unique ID of the group
     * @param groupName        The name of the group
     * @param groupDescription The description of the group
     * @param created          The date-time the group was created
     * @param modified         The date-time the group was last modified
     */
    GroupImpl(long id,
              String groupName,
              String groupDescription,
              Date created,
              Date modified) {
        groupID = id;
        name = groupName;
        description = groupDescription;
        creationDate = created;
        modificationDate = modified;
        properties = new Hashtable();
        groupCache = CacheManager.getCache(GroupManager.GROUP_CACHE_NAME);
        groupMemberCache = CacheManager.getCache(GroupManager.GROUP_MEMBER_CACHE_NAME);
    }

    public long getID() {
        return groupID;
    }

    public String getName() {
        return name;
    }

    public void setName(String groupName) throws UnauthorizedException {
        if (groupName == null) {
            throw new IllegalArgumentException("Name cannot be null");
        }

        this.name = groupName;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String desc) throws UnauthorizedException {
        if (desc == null) {
            throw new IllegalArgumentException("Description cannot be null");
        }

        this.description = desc;
    }

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date created) throws UnauthorizedException {
        if (created == null) {
            throw new IllegalArgumentException("Creation date cannot be null");
        }

        this.creationDate.setTime(created.getTime());
    }

    public Date getModificationDate() {
        return modificationDate;
    }

    public void setModificationDate(Date modified) throws UnauthorizedException {
        if (modified == null) {
            throw new IllegalArgumentException("Modification date cannot be null");
        }

        this.modificationDate.setTime(modified.getTime());
    }

    public String getProperty(String name) {
        return (String)properties.get(name);
    }

    public void setProperty(String name, String value) throws UnauthorizedException {
        // Make sure the property name and value aren't null.
        if (name == null || value == null || "".equals(name) || "".equals(value)) {
            throw new NullPointerException("Cannot set property with empty or null value.");
        }
        // See if we need to update a property value or insert a new one.
        if (properties.containsKey(name)) {
            // Only update the value in the database if the property value has changed.
            if (!(value.equals(properties.get(name)))) {
                String original = (String)properties.get(name);
                properties.put(name, value);
                provider.updateProperty(groupID, name, value);

                // Re-add group to cache.
                groupCache.put(new Long(groupID), this);

                // fire off an event
                Map params = new HashMap();
                params.put("Type", "propertyModify");
                params.put("PropertyKey", name);
                params.put("originalValue", original);
            }
        }
        else {
            properties.put(name, value);
            provider.createProperty(groupID, name, value);

            // Re-add group to cache.
            groupCache.put(new Long(groupID), this);

            // fire off an event
            Map params = new HashMap();
            params.put("Type", "propertyAdd");
            params.put("PropertyKey", name);
        }
    }

    public void deleteProperty(String name) throws UnauthorizedException {
        // Only delete the property if it exists.
        if (properties.containsKey(name)) {
            // fire off an event
            Map params = new HashMap();
            params.put("Type", "propertyDelete");
            params.put("PropertyKey", name);

            properties.remove(name);
            provider.deleteProperty(groupID, name);

            // Re-add group to cache.
            groupCache.put(new Long(groupID), this);
        }
    }

    public Iterator getPropertyNames() {
        return Collections.unmodifiableSet(properties.keySet()).iterator();
    }

    public void addAdministrator(Entity entity)
            throws UnauthorizedException, UserAlreadyExistsException {
        // If the user is already an administrator, do nothing.
        if (isAdministrator(entity)) {
            throw new UserAlreadyExistsException("User " + entity.getUsername() + "with ID " + entity.getID() +
                    " already is a member of the group");
        }

        long userID = entity.getID();
        provider.createMember(groupID, userID, true);
        try {
            provider.updateGroup(this);
        }
        catch (GroupNotFoundException e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }

        // Changed admins, so reset admin list
        adminList = null;
        groupCache.put(new Long(groupID), this);
        groupMemberCache.put(groupID + ",admin," + entity.getID(), Boolean.TRUE);

        // Now, clear the permissions cache.
        // This is handled via a listener for the GroupEvent.GROUP_ADMINISTRATOR_ADD event

        // fire off an event
        Map params = new HashMap();
        params.put("Administrator", entity);
    }

    public void removeAdministrator(Entity entity) throws UnauthorizedException {
        // If the user is not an administrator, do nothing.
        if (isAdministrator(entity)) {

            long userID = entity.getID();
            provider.deleteMember(groupID, userID);
            try {
                provider.updateGroup(this);
            }
            catch (GroupNotFoundException e) {
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }

            // Changed admins, so reset admin list
            adminList = null;
            groupCache.put(new Long(groupID), this);

            // Remove user from admin cache
            groupMemberCache.remove(groupID + ",admin," + userID);

            // Now, clear the permissions cache.
            // This is handled via a listener for the GroupEvent.GROUP_ADMINISTRATOR_DELETE event
        }
    }

    public void addMember(Entity entity)
            throws UnauthorizedException, UserAlreadyExistsException {
        // Don't do anything if the user is already a member of the group.
        if (isMember(entity)) {
            throw new UserAlreadyExistsException("User " + entity.getUsername() + "with ID " + entity.getID() +
                    " already is a member of the group");
        }

        long userID = entity.getID();
        provider.createMember(groupID, userID, false);
        try {
            provider.updateGroup(this);
        }
        catch (GroupNotFoundException e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }

        // Changed membership, so reset member list
        memberList = null;
        groupCache.put(new Long(groupID), this);

        // Remove user from member cache
        groupMemberCache.remove(groupID + ",member," + userID);

        // Remove the user's entry for groups they belong in.
        groupMemberCache.remove("userGroups-" + userID);

        // Now, clear the permissions cache.
        // This is handled via a listener for the GroupEvent.GROUP_USER_ADD event
    }

    public void removeMember(Entity entity) throws UnauthorizedException {
        // Don't do anything if the user isn't a member of the group.
        if (!isMember(entity)) {
            return;
        }

        long userID = entity.getID();
        provider.deleteMember(groupID, userID);

        // Changed membership, so reset member list
        memberList = null;
        groupCache.put(new Long(groupID), this);

        // Remove user from member cache
        groupMemberCache.remove(groupID + ",member," + userID);

        // Remove the user's entry for groups they belong in.
        groupMemberCache.remove("userGroups-" + userID);

        // Now, clear the permissions cache.
        // This is handled via a listener for the GroupEvent.GROUP_USER_DELETE event
    }

    public boolean isAdministrator(Entity entity) {
        long userID = entity.getID();
        Boolean bool = null;
        bool = (Boolean)groupMemberCache.get(groupID + ",admin," + userID);

        if (bool == null) {
            bool = new Boolean(provider.isMember(groupID, userID, true));
            // Add to cache
            groupMemberCache.put(groupID + ",admin," + userID, bool);
        }
        return bool.booleanValue();
    }

    public boolean isMember(Entity entity) {
        long userID = entity.getID();
        Boolean bool = null;
        bool = (Boolean)groupMemberCache.get(groupID + ",member," + userID);
        if (bool == null) {
            bool = new Boolean(provider.isMember(groupID, userID, false));
            // Add to cache
            groupMemberCache.put(groupID + ",member," + userID, bool);
        }
        return bool.booleanValue();
    }

    public int getAdministratorCount() {
        // If the admin list is null, load it.
        if (adminList == null) {
            administrators();
        }
        return adminList.length;
    }

    public int getMemberCount() {
        // If the member list is null, load it.
        if (memberList == null) {
            members();
        }
        return memberList.length;
    }

    public Iterator members() {
        if (memberList == null) {
            memberList = provider.getMembers(groupID, false).toArray();
            // Re-add group to cache.
            groupCache.put(new Long(groupID), this);
        }

        try {
            return new UserIterator(memberList);
        }
        catch (UnauthorizedException e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        return null;
    }

    public Iterator administrators() {
        if (adminList == null) {
            adminList = provider.getMembers(groupID, true).toArray();
            // Re-add group to cache.
            groupCache.put(new Long(groupID), this);
        }

        try {
            return new UserIterator(adminList);
        }
        catch (UnauthorizedException e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        return null;
    }

    public Permissions getPermissions(AuthToken auth) {
        long userID = auth.getUserID();
        try {
            Boolean bool = null;
            bool = (Boolean)groupMemberCache.get(groupID + ",admin," + userID);

            if (bool == null) {
                bool = new Boolean(provider.isMember(groupID, userID, true));
                // Add to cache
                groupMemberCache.put(groupID + ",admin," + userID, bool);
            }

            if (bool.booleanValue()) {
                return new Permissions(Permissions.GROUP_ADMIN);
            }
        }
        catch (Exception e) {
        }

        return new Permissions(Permissions.NONE);
    }

    public boolean isAuthorized(long permissionType) {
        return true;
    }

    public int getCachedSize() {
        // 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.sizeOfLong();                // id
        size += CacheSizes.sizeOfString(name);          // name
        size += CacheSizes.sizeOfString(description);   // description
        size += CacheSizes.sizeOfDate();                // creation date
        size += CacheSizes.sizeOfDate();                // modification date
        size += CacheSizes.sizeOfMap(properties);       // properties
        size += CacheSizes.sizeOfObject();              // member list
        size += CacheSizes.sizeOfObject();              // admin list

        return size;
    }

    /**
     * Returns a String representation of the Group object using the group name.
     *
     * @return a String representation of the Group object.
     */
    public String toString() {
        return name;
    }

    public int hashCode() {
        return (int)groupID;
    }

    public boolean equals(Object object) {
        if (this == object) {
            return true;
        }
        if (object != null && object instanceof GroupImpl) {
            return groupID == ((GroupImpl)object).getID();
        }
        else {
            return false;
        }
    }
}