1 package org.codehaus.plexus.context;
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 import java.util.Collections;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.ConcurrentMap;
24 import java.util.concurrent.atomic.AtomicBoolean;
25
26
27
28
29
30
31
32
33
34
35 public class DefaultContext implements Context {
36
37
38
39 private final ConcurrentMap<Object, Object> contextData = new ConcurrentHashMap<Object, Object>();
40
41
42
43
44 private final AtomicBoolean readOnly = new AtomicBoolean(false);
45
46
47
48
49 public DefaultContext() {}
50
51
52
53
54
55
56
57
58 public DefaultContext(Map<Object, Object> contextData) {
59 if (contextData == null) {
60 throw new NullPointerException("contextData is null");
61 }
62
63
64 for (Entry<Object, Object> entry : contextData.entrySet()) {
65 Object key = entry.getKey();
66 Object value = entry.getValue();
67 if (key == null) {
68 throw new IllegalArgumentException("Key is null");
69 }
70 if (value != null) {
71 this.contextData.put(key, value);
72 }
73 }
74 }
75
76 public boolean contains(Object key) {
77 Object data = contextData.get(key);
78
79 return data != null;
80 }
81
82 public Object get(Object key) throws ContextException {
83 Object data = contextData.get(key);
84
85 if (data == null) {
86
87 throw new ContextException("Unable to resolve context key: " + key);
88 }
89 return data;
90 }
91
92 public void put(Object key, Object value) throws IllegalStateException {
93 checkWriteable();
94
95
96 if (key == null) {
97 throw new IllegalArgumentException("Key is null");
98 }
99
100 if (value == null) {
101 contextData.remove(key);
102 } else {
103 contextData.put(key, value);
104 }
105 }
106
107 public void hide(Object key) throws IllegalStateException {
108 checkWriteable();
109
110 contextData.remove(key);
111 }
112
113
114
115
116
117
118 public Map<Object, Object> getContextData() {
119 return Collections.unmodifiableMap(contextData);
120 }
121
122
123
124
125
126
127 public void makeReadOnly() {
128 readOnly.set(true);
129 }
130
131
132
133
134
135
136 protected void checkWriteable() throws IllegalStateException {
137 if (readOnly.get()) {
138 throw new IllegalStateException("Context is read only and can not be modified");
139 }
140 }
141
142 public String toString() {
143 return contextData.toString();
144 }
145 }