1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 package org.directwebremoting.guice;
17
18 import com.google.inject.Key;
19
20 import java.util.ArrayList;
21 import java.util.Collection;
22
23 /**
24 * A specialization of {@link AbstractContextScope} for the case when
25 * the context identifier itself can serve as a string-keyed instance registry
26 * using synchronization on the context to provide atomic put-if-absent
27 * and remove-specific-value behavior.
28 * @author Tim Peierls [tim at peierls dot net]
29 */
30 public abstract class AbstractSimpleContextScope<C> extends AbstractContextScope<C, C>
31 {
32 protected AbstractSimpleContextScope(Class<C> type, String scopeName)
33 {
34 super(type, scopeName);
35 }
36
37 public abstract C get();
38
39
40
41
42
43
44 public abstract Object get(C registry, String keyString);
45
46 public abstract void put(C registry, String keyString, Object creator);
47
48
49
50
51
52
53 public C registryFor(C context)
54 {
55 return context;
56 }
57
58 @SuppressWarnings("unchecked")
59 public <T> InstanceProvider<T> get(C registry, Key<T> key, String keyString)
60 {
61 return (InstanceProvider<T>) get(registry, keyString);
62 }
63
64 public <T> void put(C registry, Key<T> key, String keyString, InstanceProvider<T> creator)
65 {
66 put(registry, keyString, creator);
67 }
68
69 public <T> InstanceProvider<T> putIfAbsent(C registry, Key<T> key, String keyString,
70 InstanceProvider<T> creator)
71 {
72 synchronized (registry)
73 {
74 InstanceProvider<T> t = get(registry, key, keyString);
75 if (t != null)
76 {
77 return t;
78 }
79 else
80 {
81 put(registry, key, keyString, creator);
82 return null;
83 }
84 }
85 }
86
87 public <T> boolean remove(C registry, Key<T> key, String keyString,
88 InstanceProvider<T> creator)
89 {
90 synchronized (registry)
91 {
92 InstanceProvider<T> t = get(registry, key, keyString);
93 if (t == creator)
94 {
95
96 put(registry, keyString, null);
97 return true;
98 }
99 else
100 {
101 return false;
102 }
103 }
104 }
105 }