1 | |
|
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
package org.apache.shiro.cache; |
20 | |
|
21 | |
import org.apache.shiro.util.CollectionUtils; |
22 | |
|
23 | |
import java.util.Collection; |
24 | |
import java.util.Collections; |
25 | |
import java.util.Map; |
26 | |
import java.util.Set; |
27 | |
|
28 | |
|
29 | |
|
30 | |
|
31 | |
|
32 | |
|
33 | |
|
34 | |
public class MapCache<K, V> implements Cache<K, V> { |
35 | |
|
36 | |
|
37 | |
|
38 | |
|
39 | |
private final Map<K, V> map; |
40 | |
|
41 | |
|
42 | |
|
43 | |
|
44 | |
private final String name; |
45 | |
|
46 | 2 | public MapCache(String name, Map<K, V> backingMap) { |
47 | 2 | if (name == null) { |
48 | 0 | throw new IllegalArgumentException("Cache name cannot be null."); |
49 | |
} |
50 | 2 | if (backingMap == null) { |
51 | 0 | throw new IllegalArgumentException("Backing map cannot be null."); |
52 | |
} |
53 | 2 | this.name = name; |
54 | 2 | this.map = backingMap; |
55 | 2 | } |
56 | |
|
57 | |
public V get(K key) throws CacheException { |
58 | 6 | return map.get(key); |
59 | |
} |
60 | |
|
61 | |
public V put(K key, V value) throws CacheException { |
62 | 6 | return map.put(key, value); |
63 | |
} |
64 | |
|
65 | |
public V remove(K key) throws CacheException { |
66 | 0 | return map.remove(key); |
67 | |
} |
68 | |
|
69 | |
public void clear() throws CacheException { |
70 | 0 | map.clear(); |
71 | 0 | } |
72 | |
|
73 | |
public int size() { |
74 | 0 | return map.size(); |
75 | |
} |
76 | |
|
77 | |
public Set<K> keys() { |
78 | 0 | Set<K> keys = map.keySet(); |
79 | 0 | if (!keys.isEmpty()) { |
80 | 0 | return Collections.unmodifiableSet(keys); |
81 | |
} |
82 | 0 | return Collections.emptySet(); |
83 | |
} |
84 | |
|
85 | |
public Collection<V> values() { |
86 | 0 | Collection<V> values = map.values(); |
87 | 0 | if (!CollectionUtils.isEmpty(values)) { |
88 | 0 | return Collections.unmodifiableCollection(values); |
89 | |
} |
90 | 0 | return Collections.emptySet(); |
91 | |
} |
92 | |
|
93 | |
public String toString() { |
94 | 0 | return new StringBuilder("MapCache '") |
95 | |
.append(name).append("' (") |
96 | |
.append(map.size()) |
97 | |
.append(" entries)") |
98 | |
.toString(); |
99 | |
} |
100 | |
} |