01: /*
02: * Copyright 2007 Tim Peierls
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.directwebremoting.guice;
17:
18: import java.util.concurrent.ConcurrentHashMap;
19: import java.util.concurrent.ConcurrentMap;
20:
21: import com.google.inject.Key;
22:
23: /**
24: * A specialization of {@link AbstractContextScope} using a concurrent map
25: * to hold registered instance providers. Concrete implementations must
26: * define {@code get()} to return the current context, and they must call
27: * {@code super(C.class)} in constructors.
28: * @author Tim Peierls [tim at peierls dot net]
29: */
30: public abstract class AbstractMapContextScope<C> extends
31: AbstractContextScope<C, InstanceMap<?>> {
32: protected AbstractMapContextScope(Class<C> type, String scopeName) {
33: super (type, scopeName);
34: }
35:
36: @Override
37: public abstract C get();
38:
39: //
40: // ContextRegistry methods
41: //
42:
43: /* (non-Javadoc)
44: * @see org.directwebremoting.guice.ContextRegistry#registryFor(java.lang.Object)
45: */
46: public InstanceMap<?> registryFor(C context) {
47: InstanceMap<?> instanceMap = map.get(context);
48:
49: if (instanceMap == null) {
50: InstanceMap<?> emptyMap = new InstanceMapImpl<Object>();
51: instanceMap = map.putIfAbsent(context, emptyMap);
52: if (instanceMap == null) {
53: instanceMap = emptyMap;
54: }
55: }
56:
57: return instanceMap;
58: }
59:
60: public <T> InstanceProvider<T> get(InstanceMap<?> registry,
61: Key<T> key, String keyString) {
62: return castToT(registry, key).get(key);
63: }
64:
65: public <T> InstanceProvider<T> putIfAbsent(InstanceMap<?> registry,
66: Key<T> key, String keyString, InstanceProvider<T> creator) {
67: return castToT(registry, key).putIfAbsent(key, creator);
68: }
69:
70: public <T> boolean remove(InstanceMap<?> registry, Key<T> key,
71: String keyString, InstanceProvider<T> creator) {
72: return castToT(registry, key).remove(key, creator);
73: }
74:
75: @SuppressWarnings("unused")
76: private <T> InstanceMap<T> castToT(InstanceMap<?> instanceMap,
77: Key<T> key) {
78: @SuppressWarnings("unchecked")
79: InstanceMap<T> result = (InstanceMap<T>) instanceMap;
80: return result;
81: }
82:
83: private final ConcurrentMap<C, InstanceMap<?>> map = new ConcurrentHashMap<C, InstanceMap<?>>();
84: }
|