Group.java 15.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
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright (C) 2004 Jive Software. All rights reserved.
 *
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
 */

package org.jivesoftware.messenger.group;

import org.jivesoftware.util.Log;
Matt Tucker's avatar
Matt Tucker committed
15 16
import org.jivesoftware.util.Cacheable;
import org.jivesoftware.util.CacheSizes;
Matt Tucker's avatar
Matt Tucker committed
17
import org.jivesoftware.database.DbConnectionManager;
Matt Tucker's avatar
Matt Tucker committed
18
import org.jivesoftware.messenger.event.GroupEventDispatcher;
19 20
import org.jivesoftware.messenger.user.UserManager;
import org.jivesoftware.stringprep.Stringprep;
Matt Tucker's avatar
Matt Tucker committed
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Groups organize users into a single entity for easier management.
 *
 * @see GroupManager#createGroup(String)
 *
 * @author Matt Tucker
 */
Matt Tucker's avatar
Matt Tucker committed
36
public class Group implements Cacheable {
Matt Tucker's avatar
Matt Tucker committed
37 38

    private static final String LOAD_PROPERTIES =
39
        "SELECT name, propValue FROM jiveGroupProp WHERE groupName=?";
Matt Tucker's avatar
Matt Tucker committed
40
    private static final String DELETE_PROPERTY =
41
        "DELETE FROM jiveGroupProp WHERE groupName=? AND name=?";
Matt Tucker's avatar
Matt Tucker committed
42
    private static final String UPDATE_PROPERTY =
43
        "UPDATE jiveGroupProp SET propValue=? WHERE name=? AND groupName=?";
Matt Tucker's avatar
Matt Tucker committed
44
    private static final String INSERT_PROPERTY =
45
        "INSERT INTO jiveGroupProp (groupName, name, propValue) VALUES (?, ?, ?)";
Matt Tucker's avatar
Matt Tucker committed
46 47 48 49 50 51

    private GroupProvider provider;
    private GroupManager groupManager;
    private String name;
    private String description;
    private Map<String, String> properties;
52 53
    private Collection<String> members;
    private Collection<String> administrators;
Matt Tucker's avatar
Matt Tucker committed
54 55 56 57 58 59 60

    /**
     * Constructs a new group.
     *
     * @param provider the group provider.
     * @param name the name.
     * @param description the description.
61
     * @param members a Collection of the group members.
Matt Tucker's avatar
Matt Tucker committed
62 63
     * @param administrators a Collection of the group administrators.
     */
Matt Tucker's avatar
Matt Tucker committed
64 65
    protected Group(GroupProvider provider, String name, String description,
            Collection<String> members, Collection<String> administrators)
Matt Tucker's avatar
Matt Tucker committed
66 67 68 69 70
    {
        this.provider = provider;
        this.groupManager = GroupManager.getInstance();
        this.name = name;
        this.description = description;
71 72
        this.members = members;
        this.administrators = administrators;
Matt Tucker's avatar
Matt Tucker committed
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
    }

    /**
     * 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) {
        try {
Matt Tucker's avatar
Matt Tucker committed
92
            String originalName = this.name;
Matt Tucker's avatar
Matt Tucker committed
93
            provider.setName(this.name, name);
Matt Tucker's avatar
Matt Tucker committed
94 95 96
            groupManager.groupCache.remove(this.name);
            this.name = name;
            groupManager.groupCache.put(name, this);
Matt Tucker's avatar
Matt Tucker committed
97 98 99 100 101

            // Fire event.
            Map params = new HashMap();
            params.put("type", "nameModified");
            params.put("originalValue", originalName);
Matt Tucker's avatar
Matt Tucker committed
102 103
            GroupEventDispatcher.dispatchEvent(this, GroupEventDispatcher.EventType.group_modified,
                    params);
Matt Tucker's avatar
Matt Tucker committed
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
        }
        catch (Exception e) {
            Log.error(e);
        }
    }

    /**
     * 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) {
        try {
Matt Tucker's avatar
Matt Tucker committed
130
            String originalDescription = this.description;
Matt Tucker's avatar
Matt Tucker committed
131
            provider.setDescription(name, description);
Matt Tucker's avatar
Matt Tucker committed
132
            this.description = description;
Matt Tucker's avatar
Matt Tucker committed
133 134 135 136
            // Fire event.
            Map params = new HashMap();
            params.put("type", "descriptionModified");
            params.put("originalValue", originalDescription);
Matt Tucker's avatar
Matt Tucker committed
137 138
            GroupEventDispatcher.dispatchEvent(this,
                    GroupEventDispatcher.EventType.group_modified, params);
Matt Tucker's avatar
Matt Tucker committed
139 140 141 142 143 144 145 146 147 148 149 150 151
        }
        catch (Exception e) {
            Log.error(e);
        }
    }

    /**
     * Returns all extended properties of the group. Groups
     * have an arbitrary number of extended properties.
     *
     * @return the extended properties.
     */
    public Map<String,String> getProperties() {
152 153 154 155
        synchronized (this) {
            if (properties == null) {
                properties = new ConcurrentHashMap<String, String>();
                loadProperties();
Matt Tucker's avatar
Matt Tucker committed
156 157 158 159 160 161 162
            }
        }
        // Return a wrapper that will intercept add and remove commands.
        return new PropertiesMap();
    }

    /**
163
     * Returns a Collection of the group administrators.
Matt Tucker's avatar
Matt Tucker committed
164 165 166
     *
     * @return a Collection of the group administrators.
     */
167
    public Collection<String> getAdmins() {
168 169
        // Return a wrapper that will intercept add and remove commands.
        return new MemberCollection(administrators, true);
Matt Tucker's avatar
Matt Tucker committed
170 171 172
    }

    /**
173
     * Returns a Collection of the group members.
Matt Tucker's avatar
Matt Tucker committed
174 175 176 177
     *
     * @return a Collection of the group members.
     */
    public Collection<String> getMembers() {
178 179
        // Return a wrapper that will intercept add and remove commands.
        return new MemberCollection(members, false);
Matt Tucker's avatar
Matt Tucker committed
180 181
    }

182 183 184 185 186 187 188 189 190 191
    /**
     * 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) {
        return members.contains(username) || administrators.contains(username);
    }

192 193 194 195 196 197 198 199
    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.sizeOfString(name);
        size += CacheSizes.sizeOfString(description);
        return size;
Matt Tucker's avatar
Matt Tucker committed
200 201
    }

Matt Tucker's avatar
Matt Tucker committed
202
    /**
203 204
     * Collection implementation that notifies the GroupProvider of any
     * changes to the collection.
Matt Tucker's avatar
Matt Tucker committed
205
     */
206
    private class MemberCollection extends AbstractCollection {
Matt Tucker's avatar
Matt Tucker committed
207

208 209
        private Collection<String> users;
        private boolean adminCollection;
Matt Tucker's avatar
Matt Tucker committed
210

211 212 213
        public MemberCollection(Collection<String> users, boolean adminCollection) {
            this.users = users;
            this.adminCollection = adminCollection;
Matt Tucker's avatar
Matt Tucker committed
214 215
        }

216 217
        public Iterator iterator() {
            return new Iterator() {
Matt Tucker's avatar
Matt Tucker committed
218

219 220
                Iterator iter = users.iterator();
                Object current = null;
Matt Tucker's avatar
Matt Tucker committed
221

222 223 224
                public boolean hasNext() {
                    return iter.hasNext();
                }
225

226 227 228 229
                public Object next() {
                    current = iter.next();
                    return current;
                }
230

231 232 233 234
                public void remove() {
                    if (current == null) {
                        throw new IllegalStateException();
                    }
Matt Tucker's avatar
Matt Tucker committed
235
                    String user = (String)current;
Matt Tucker's avatar
Matt Tucker committed
236
                    // Remove the user from the collection in memory.
237
                    iter.remove();
Matt Tucker's avatar
Matt Tucker committed
238
                    // Remove the group user from the backend store.
239
                    provider.deleteMember(name, user);
Matt Tucker's avatar
Matt Tucker committed
240 241 242 243
                    // Fire event.
                    if (adminCollection) {
                        Map params = new HashMap();
                        params.put("admin", user);
Matt Tucker's avatar
Matt Tucker committed
244 245
                        GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.admin_removed, params);
Matt Tucker's avatar
Matt Tucker committed
246 247 248 249
                    }
                    else {
                        Map params = new HashMap();
                        params.put("member", user);
Matt Tucker's avatar
Matt Tucker committed
250 251
                        GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.member_removed, params);
Matt Tucker's avatar
Matt Tucker committed
252
                    }
253 254 255 256 257 258 259 260 261
                }
            };
        }

        public int size() {
            return users.size();
        }

        public boolean add(Object member) {
262 263 264 265 266 267 268 269
            String username = (String) member;
            try {
                username = Stringprep.nodeprep(username);
                UserManager.getInstance().getUser(username);
            }
            catch (Exception e) {
                throw new IllegalArgumentException("Invalid user.", e);
            }
270
            if (adminCollection) {
271
                if (members.contains(username)) {
272 273 274 275
                    throw new IllegalArgumentException("The user is already a member of the group");
                }
            }
            else {
276
                if (administrators.contains(username)) {
277 278 279
                    throw new IllegalArgumentException("The user is already an admin of the group");
                }
            }
280
            if (users.add(username)) {
Matt Tucker's avatar
Matt Tucker committed
281
                // Add the group user to the backend store.
282
                provider.addMember(name, username, adminCollection);
Matt Tucker's avatar
Matt Tucker committed
283 284 285 286 287

                // Fire event.
                if (adminCollection) {
                    Map params = new HashMap();
                    params.put("admin", username);
Matt Tucker's avatar
Matt Tucker committed
288 289
                    GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.admin_added, params);
Matt Tucker's avatar
Matt Tucker committed
290 291 292 293
                }
                else {
                    Map params = new HashMap();
                    params.put("member", username);
Matt Tucker's avatar
Matt Tucker committed
294 295
                    GroupEventDispatcher.dispatchEvent(Group.this,
                                GroupEventDispatcher.EventType.member_added, params);
Matt Tucker's avatar
Matt Tucker committed
296
                }
297 298 299 300
                return true;
            }
            return false;
        }
301 302
    }

Matt Tucker's avatar
Matt Tucker committed
303 304 305 306 307 308
    /**
     * Map implementation that updates the database when properties are modified.
     */
    private class PropertiesMap extends AbstractMap {

        public Object put(Object key, Object value) {
309
            Object answer;
Matt Tucker's avatar
Matt Tucker committed
310
            if (properties.containsKey(key)) {
Matt Tucker's avatar
Matt Tucker committed
311
                String originalValue = properties.get(key);
312
                answer = properties.put((String)key, (String)value);
Matt Tucker's avatar
Matt Tucker committed
313
                updateProperty((String)key, (String)value);
Matt Tucker's avatar
Matt Tucker committed
314 315 316 317 318
                // Fire event.
                Map params = new HashMap();
                params.put("type", "propertyModified");
                params.put("propertyKey", key);
                params.put("originalValue", originalValue);
Matt Tucker's avatar
Matt Tucker committed
319 320
                GroupEventDispatcher.dispatchEvent(Group.this,
                        GroupEventDispatcher.EventType.group_modified, params);
Matt Tucker's avatar
Matt Tucker committed
321 322
            }
            else {
323
                answer = properties.put((String)key, (String)value);
Matt Tucker's avatar
Matt Tucker committed
324
                insertProperty((String)key, (String)value);
Matt Tucker's avatar
Matt Tucker committed
325 326 327 328
                // Fire event.
                Map params = new HashMap();
                params.put("type", "propertyAdded");
                params.put("propertyKey", key);
Matt Tucker's avatar
Matt Tucker committed
329 330
                GroupEventDispatcher.dispatchEvent(Group.this,
                        GroupEventDispatcher.EventType.group_modified, params);
Matt Tucker's avatar
Matt Tucker committed
331
            }
332
            return answer;
Matt Tucker's avatar
Matt Tucker committed
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
        }

        public Set<Entry> entrySet() {
            return new PropertiesEntrySet();
        }
    }

    /**
     * Set implementation that updates the database when properties are deleted.
     */
    private class PropertiesEntrySet extends AbstractSet {

        public int size() {
            return properties.entrySet().size();
        }

        public Iterator iterator() {
            return new Iterator() {

                Iterator iter = properties.entrySet().iterator();
                Map.Entry current = null;

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

                public Object next() {
                    current = (Map.Entry)iter.next();
361
                    return current;
Matt Tucker's avatar
Matt Tucker committed
362 363 364 365 366 367 368 369
                }

                public void remove() {
                    if (current == null) {
                        throw new IllegalStateException();
                    }
                    deleteProperty((String)current.getKey());
                    iter.remove();
Matt Tucker's avatar
Matt Tucker committed
370 371 372 373
                    // Fire event.
                    Map params = new HashMap();
                    params.put("type", "propertyDeleted");
                    params.put("propertyKey", current.getKey());
Matt Tucker's avatar
Matt Tucker committed
374 375
                    GroupEventDispatcher.dispatchEvent(Group.this,
                        GroupEventDispatcher.EventType.group_modified, params);
Matt Tucker's avatar
Matt Tucker committed
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
                }
            };
        }
    }

    private void loadProperties() {
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(LOAD_PROPERTIES);
            pstmt.setString(1, name);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                properties.put(rs.getString(1), rs.getString(2));
            }
            rs.close();
        }
        catch (SQLException sqle) {
            Log.error(sqle);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
405
    private void insertProperty(String propName, String propValue) {
Matt Tucker's avatar
Matt Tucker committed
406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(INSERT_PROPERTY);
            pstmt.setString(1, name);
            pstmt.setString(2, propName);
            pstmt.setString(3, propValue);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
427
    private void updateProperty(String propName, String propValue) {
Matt Tucker's avatar
Matt Tucker committed
428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(UPDATE_PROPERTY);
            pstmt.setString(1, propValue);
            pstmt.setString(2, propName);
            pstmt.setString(3, name);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }

Matt Tucker's avatar
Matt Tucker committed
449
    private void deleteProperty(String propName) {
Matt Tucker's avatar
Matt Tucker committed
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        Connection con = null;
        PreparedStatement pstmt = null;
        try {
            con = DbConnectionManager.getConnection();
            pstmt = con.prepareStatement(DELETE_PROPERTY);
            pstmt.setString(1, name);
            pstmt.setString(2, propName);
            pstmt.executeUpdate();
        }
        catch (SQLException e) {
            Log.error(e);
        }
        finally {
            try { if (pstmt != null) pstmt.close(); }
            catch (Exception e) { Log.error(e); }
            try { if (con != null) con.close(); }
            catch (Exception e) { Log.error(e); }
        }
    }
}