View Javadoc

1   package com.atlassian.user.impl.cache;
2   
3   import com.atlassian.user.User;
4   import com.atlassian.user.Group;
5   import com.atlassian.cache.*;
6   
7   import java.util.List;
8   import java.util.Iterator;
9   
10  /**
11   * The membership check cache is a cache where the key is the {@link String}
12   * returned by {@link #getMembershipKey(String, Group)} for a given user
13   * and group, and the value is a {@link Boolean} indicating whether the user
14   * is a member of that group.
15   * <p/>
16   * Both true and false membership checks are cached.
17   */
18  public class MembershipCache
19  {
20      private final CacheFactory cacheFactory;
21      private final String cacheName;
22  
23      public MembershipCache(CacheFactory cacheFactory, String cacheName)
24      {
25          this.cacheFactory = cacheFactory;
26          this.cacheName = cacheName;
27      }
28  
29      private com.atlassian.cache.Cache getCache()
30      {
31          return cacheFactory.getCache(cacheName);
32      }
33  
34      protected String getMembershipKey(String username, Group group)
35      {
36          return username + "_" + group.getName();
37      }
38  
39      public void put(User user, Group group, boolean isMember)
40      {
41          getCache().put(getMembershipKey(user.getName(), group), Boolean.valueOf(isMember));
42      }
43  
44      /**
45       * @return {@link Boolean#TRUE} if the user is a member of the group,
46       *         {@link Boolean#FALSE} if the user is not a member of the group, or
47       *         null if the result is not in the cache.
48       */
49      public Boolean get(User user, Group group)
50      {
51          return (Boolean) getCache().get(getMembershipKey(user.getName(), group));
52      }
53  
54      public void remove(User user, Group group)
55      {
56          getCache().remove(getMembershipKey(user.getName(), group));
57      }
58  
59      /**
60       * Remove all cached values for a list of users and an associated group.
61       * Typically called to remove all membership information when a group is
62       * removed.
63       *
64       * @param usernames a {@link List} of username {@link String}s.
65       * @param group the group of which the users are members.
66       */
67      public void remove(List usernames, Group group)
68      {
69          for (Iterator iter = usernames.iterator(); iter.hasNext();)
70          {
71              String username = (String) iter.next();
72              getCache().remove(getMembershipKey(username, group));
73          }
74      }
75  }