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 com.google.inject.Key;
19:
20: /**
21: * A specialization of {@link AbstractContextScope} for the case when
22: * the context identifier itself can serve as a string-keyed instance registry
23: * using synchronization on the context to provide atomic put-if-absent
24: * and remove-specific-value behavior.
25: * @author Tim Peierls [tim at peierls dot net]
26: */
27: public abstract class AbstractSimpleContextScope<C> extends
28: AbstractContextScope<C, C> {
29: protected AbstractSimpleContextScope(Class<C> type, String scopeName) {
30: super (type, scopeName);
31: }
32:
33: @Override
34: public abstract C get();
35:
36: //
37: // These methods are restricted to String lookup of plain Objects.
38: //
39:
40: public abstract Object get(C registry, String keyString);
41:
42: public abstract void put(C registry, String keyString,
43: Object creator);
44:
45: //
46: // ContextRegistry methods
47: //
48:
49: public C registryFor(C context) {
50: return context;
51: }
52:
53: @SuppressWarnings("unchecked")
54: public <T> InstanceProvider<T> get(C registry, Key<T> key,
55: String keyString) {
56: return (InstanceProvider<T>) get(registry, keyString);
57: }
58:
59: @SuppressWarnings("unused")
60: public <T> void put(C registry, Key<T> key, String keyString,
61: InstanceProvider<T> creator) {
62: put(registry, keyString, creator);
63: }
64:
65: public <T> InstanceProvider<T> putIfAbsent(C registry, Key<T> key,
66: String keyString, InstanceProvider<T> creator) {
67: synchronized (registry) {
68: InstanceProvider<T> t = get(registry, key, keyString);
69: if (t != null) {
70: return t;
71: } else {
72: put(registry, key, keyString, creator);
73: return null;
74: }
75: }
76: }
77:
78: public <T> boolean remove(C registry, Key<T> key, String keyString,
79: InstanceProvider<T> creator) {
80: synchronized (registry) {
81: InstanceProvider<T> t = get(registry, key, keyString);
82: if (t == creator) {
83: // Assumes put(..., null) is equivalent to remove(...)
84: put(registry, keyString, null);
85: return true;
86: } else {
87: return false;
88: }
89: }
90: }
91: }
|