GroupImpl.java 13.8 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
Matt Tucker's avatar
Matt Tucker committed
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
Matt Tucker's avatar
Matt Tucker committed
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Matt Tucker's avatar
Matt Tucker committed
10
 */
Matt Tucker's avatar
Matt Tucker committed
11

Matt Tucker's avatar
Matt Tucker committed
12 13 14 15 16 17 18 19
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.auth.*;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
20
import org.jivesoftware.messenger.user.User;
Matt Tucker's avatar
Matt Tucker committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
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;
42 43
    private String[] memberList;
    private String[] adminList;
Matt Tucker's avatar
Matt Tucker committed
44 45 46 47 48 49 50 51 52 53 54 55
    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
     */
56 57 58
    GroupImpl(long id, String groupName, String groupDescription, Date created,
              Date modified)
    {
Matt Tucker's avatar
Matt Tucker committed
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
        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();
    }

182
    public void addAdministrator(User user)
Matt Tucker's avatar
Matt Tucker committed
183 184
            throws UnauthorizedException, UserAlreadyExistsException {
        // If the user is already an administrator, do nothing.
185 186
        if (isAdministrator(user)) {
            throw new UserAlreadyExistsException("User " + user.getUsername() +
Matt Tucker's avatar
Matt Tucker committed
187 188
                    " already is a member of the group");
        }
189 190
        String username = user.getUsername();
        provider.createMember(groupID, username, true);
Matt Tucker's avatar
Matt Tucker committed
191 192 193 194 195 196 197 198 199 200
        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);
201
        groupMemberCache.put(groupID + ",admin," + username, Boolean.TRUE);
Matt Tucker's avatar
Matt Tucker committed
202 203 204 205 206 207

        // 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();
208
        params.put("Administrator", user);
Matt Tucker's avatar
Matt Tucker committed
209 210
    }

211
    public void removeAdministrator(User user) throws UnauthorizedException {
Matt Tucker's avatar
Matt Tucker committed
212
        // If the user is not an administrator, do nothing.
213
        if (isAdministrator(user)) {
Matt Tucker's avatar
Matt Tucker committed
214

215 216
            String username = user.getUsername();
            provider.deleteMember(groupID, username);
Matt Tucker's avatar
Matt Tucker committed
217 218 219 220 221 222 223 224 225 226 227 228
            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
229
            groupMemberCache.remove(groupID + ",admin," + username);
Matt Tucker's avatar
Matt Tucker committed
230 231 232 233 234 235

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

236
    public void addMember(User user)
Matt Tucker's avatar
Matt Tucker committed
237 238
            throws UnauthorizedException, UserAlreadyExistsException {
        // Don't do anything if the user is already a member of the group.
239 240 241
        if (isMember(user)) {
            throw new UserAlreadyExistsException("User " + user.getUsername() +
                    " is already a member of the group");
Matt Tucker's avatar
Matt Tucker committed
242
        }
243
        String username = user.getUsername();
Matt Tucker's avatar
Matt Tucker committed
244

245
        provider.createMember(groupID, username, false);
Matt Tucker's avatar
Matt Tucker committed
246 247 248 249 250 251 252 253 254 255 256 257
        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
258
        groupMemberCache.remove(groupID + ",member," + username);
Matt Tucker's avatar
Matt Tucker committed
259 260

        // Remove the user's entry for groups they belong in.
261
        groupMemberCache.remove("userGroups-" + username);
Matt Tucker's avatar
Matt Tucker committed
262 263 264 265 266

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

267
    public void removeMember(User user) throws UnauthorizedException {
Matt Tucker's avatar
Matt Tucker committed
268
        // Don't do anything if the user isn't a member of the group.
269
        if (!isMember(user)) {
Matt Tucker's avatar
Matt Tucker committed
270 271 272
            return;
        }

273 274
        String username = user.getUsername();
        provider.deleteMember(groupID, username);
Matt Tucker's avatar
Matt Tucker committed
275 276 277 278 279 280

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

        // Remove user from member cache
281
        groupMemberCache.remove(groupID + ",member," + username);
Matt Tucker's avatar
Matt Tucker committed
282 283

        // Remove the user's entry for groups they belong in.
284
        groupMemberCache.remove("userGroups-" + username);
Matt Tucker's avatar
Matt Tucker committed
285 286 287 288 289

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

290 291
    public boolean isAdministrator(User user) {
        String username = user.getUsername();
Matt Tucker's avatar
Matt Tucker committed
292
        Boolean bool = null;
293
        bool = (Boolean)groupMemberCache.get(groupID + ",admin," + username);
Matt Tucker's avatar
Matt Tucker committed
294 295

        if (bool == null) {
296
            bool = new Boolean(provider.isMember(groupID, username, true));
Matt Tucker's avatar
Matt Tucker committed
297
            // Add to cache
298
            groupMemberCache.put(groupID + ",admin," + username, bool);
Matt Tucker's avatar
Matt Tucker committed
299 300 301 302
        }
        return bool.booleanValue();
    }

303 304
    public boolean isMember(User user) {
        String username = user.getUsername();
Matt Tucker's avatar
Matt Tucker committed
305
        Boolean bool = null;
306
        bool = (Boolean)groupMemberCache.get(groupID + ",member," + username);
Matt Tucker's avatar
Matt Tucker committed
307
        if (bool == null) {
308
            bool = new Boolean(provider.isMember(groupID, username, false));
Matt Tucker's avatar
Matt Tucker committed
309
            // Add to cache
310
            groupMemberCache.put(groupID + ",member," + username, bool);
Matt Tucker's avatar
Matt Tucker committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        }
        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) {
333
            memberList = provider.getMembers(groupID, false);
Matt Tucker's avatar
Matt Tucker committed
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
            // 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) {
349
            adminList = provider.getMembers(groupID, true);
Matt Tucker's avatar
Matt Tucker committed
350 351 352 353 354 355 356 357 358 359 360 361 362 363
            // 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) {
364
        String username = auth.getUsername();
Matt Tucker's avatar
Matt Tucker committed
365 366
        try {
            Boolean bool = null;
367
            bool = (Boolean)groupMemberCache.get(groupID + ",admin," + username);
Matt Tucker's avatar
Matt Tucker committed
368 369

            if (bool == null) {
370
                bool = new Boolean(provider.isMember(groupID, username, true));
Matt Tucker's avatar
Matt Tucker committed
371
                // Add to cache
372
                groupMemberCache.put(groupID + ",admin," + username, bool);
Matt Tucker's avatar
Matt Tucker committed
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
            }

            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;
        }
    }
}