-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
RequestContext.java
285 lines (252 loc) · 11 KB
/
RequestContext.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
package io.quarkus.arc.impl;
import io.quarkus.arc.ContextInstanceHandle;
import io.quarkus.arc.CurrentContext;
import io.quarkus.arc.InjectableBean;
import io.quarkus.arc.ManagedContext;
import io.quarkus.arc.impl.EventImpl.Notifier;
import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import javax.enterprise.context.BeforeDestroyed;
import javax.enterprise.context.ContextNotActiveException;
import javax.enterprise.context.Destroyed;
import javax.enterprise.context.Initialized;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.context.spi.Contextual;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.Any;
import org.jboss.logging.Logger;
/**
* The built-in context for {@link RequestScoped}.
*
* @author Martin Kouba
*/
class RequestContext implements ManagedContext {
private static final Logger LOG = Logger.getLogger(RequestContext.class.getPackage().getName());
private final CurrentContext<RequestContextState> currentContext;
private final LazyValue<Notifier<Object>> initializedNotifier;
private final LazyValue<Notifier<Object>> beforeDestroyedNotifier;
private final LazyValue<Notifier<Object>> destroyedNotifier;
private final boolean debugEnabled;
public RequestContext(CurrentContext<RequestContextState> currentContext) {
this.currentContext = currentContext;
this.initializedNotifier = new LazyValue<>(RequestContext::createInitializedNotifier);
this.beforeDestroyedNotifier = new LazyValue<>(RequestContext::createBeforeDestroyedNotifier);
this.destroyedNotifier = new LazyValue<>(RequestContext::createDestroyedNotifier);
// we do not need to check the effective log level
this.debugEnabled = LOG.isDebugEnabled();
}
@Override
public Class<? extends Annotation> getScope() {
return RequestScoped.class;
}
@SuppressWarnings("unchecked")
@Override
public <T> T getIfActive(Contextual<T> contextual, Function<Contextual<T>, CreationalContext<T>> creationalContextFun) {
Objects.requireNonNull(contextual, "Contextual must not be null");
Objects.requireNonNull(creationalContextFun, "CreationalContext supplier must not be null");
InjectableBean<T> bean = (InjectableBean<T>) contextual;
if (!Scopes.scopeMatches(this, bean)) {
throw Scopes.scopeDoesNotMatchException(this, bean);
}
RequestContextState ctxState = currentContext.get();
if (ctxState == null) {
// Context is not active!
return null;
}
ContextInstanceHandle<T> instance = (ContextInstanceHandle<T>) ctxState.map.get(contextual);
if (instance == null) {
CreationalContext<T> creationalContext = creationalContextFun.apply(contextual);
// Bean instance does not exist - create one if we have CreationalContext
instance = new ContextInstanceHandleImpl<T>((InjectableBean<T>) contextual,
contextual.create(creationalContext), creationalContext);
ctxState.map.put(contextual, instance);
}
return instance.get();
}
@Override
public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {
T result = getIfActive(contextual,
CreationalContextImpl.unwrap(Objects.requireNonNull(creationalContext, "CreationalContext must not be null")));
if (result == null) {
throw notActive();
}
return result;
}
@SuppressWarnings("unchecked")
@Override
public <T> T get(Contextual<T> contextual) {
Objects.requireNonNull(contextual, "Contextual must not be null");
InjectableBean<T> bean = (InjectableBean<T>) contextual;
if (!Scopes.scopeMatches(this, bean)) {
throw Scopes.scopeDoesNotMatchException(this, bean);
}
RequestContextState state = currentContext.get();
if (state == null) {
throw notActive();
}
ContextInstanceHandle<T> instance = (ContextInstanceHandle<T>) state.map.get(contextual);
return instance == null ? null : instance.get();
}
@Override
public boolean isActive() {
return currentContext.get() != null;
}
@Override
public void destroy(Contextual<?> contextual) {
RequestContextState state = currentContext.get();
if (state == null) {
// Context is not active
throw notActive();
}
ContextInstanceHandle<?> instance = state.map.remove(contextual);
if (instance != null) {
instance.destroy();
}
}
@Override
public void activate(ContextState initialState) {
if (debugEnabled) {
String stack = Arrays.stream(Thread.currentThread().getStackTrace())
.skip(2)
.limit(7)
.map(se -> "\n\t" + se.toString())
.collect(Collectors.joining());
LOG.debugf("Activate %s %s\n\t...",
initialState != null ? Integer.toHexString(initialState.hashCode()) : "new", stack);
}
if (initialState == null) {
currentContext.set(new RequestContextState(new ConcurrentHashMap<>()));
// Fire an event with qualifier @Initialized(RequestScoped.class) if there are any observers for it
fireIfNotEmpty(initializedNotifier);
} else {
if (initialState instanceof RequestContextState) {
currentContext.set((RequestContextState) initialState);
} else {
throw new IllegalArgumentException("Invalid initial state: " + initialState.getClass().getName());
}
}
}
@Override
public ContextState getState() {
RequestContextState state = currentContext.get();
if (state == null) {
// Thread local not set - context is not active!
throw notActive();
}
return state;
}
public ContextState getStateIfActive() {
return currentContext.get();
}
@Override
public void deactivate() {
if (debugEnabled) {
String stack = Arrays.stream(Thread.currentThread().getStackTrace())
.skip(2)
.limit(7)
.map(se -> "\n\t" + se.toString())
.collect(Collectors.joining());
LOG.debugf("Deactivate%s\n\t...", stack);
}
currentContext.remove();
}
@Override
public void destroy() {
destroy(currentContext.get());
}
@Override
public void destroy(ContextState state) {
if (debugEnabled) {
String stack = Arrays.stream(Thread.currentThread().getStackTrace())
.skip(2)
.limit(7)
.map(se -> "\n\t" + se.toString())
.collect(Collectors.joining());
LOG.debugf("Destroy %s%s\n\t...", state != null ? Integer.toHexString(state.hashCode()) : "", stack);
}
if (state == null) {
// nothing to destroy
return;
}
if (state instanceof RequestContextState) {
RequestContextState reqState = ((RequestContextState) state);
reqState.isValid = false;
synchronized (state) {
Map<Contextual<?>, ContextInstanceHandle<?>> map = ((RequestContextState) state).map;
// Fire an event with qualifier @BeforeDestroyed(RequestScoped.class) if there are any observers for it
try {
fireIfNotEmpty(beforeDestroyedNotifier);
} catch (Exception e) {
LOG.warn("An error occurred during delivery of the @BeforeDestroyed(RequestScoped.class) event", e);
}
//Performance: avoid an iterator on the map elements
map.forEach(this::destroyContextElement);
// Fire an event with qualifier @Destroyed(RequestScoped.class) if there are any observers for it
try {
fireIfNotEmpty(destroyedNotifier);
} catch (Exception e) {
LOG.warn("An error occurred during delivery of the @Destroyed(RequestScoped.class) event", e);
}
map.clear();
}
} else {
throw new IllegalArgumentException("Invalid state implementation: " + state.getClass().getName());
}
}
private void destroyContextElement(Contextual<?> contextual, ContextInstanceHandle<?> contextInstanceHandle) {
try {
contextInstanceHandle.destroy();
} catch (Exception e) {
throw new IllegalStateException("Unable to destroy instance" + contextInstanceHandle.get(), e);
}
}
private void fireIfNotEmpty(LazyValue<Notifier<Object>> value) {
Notifier<Object> notifier = value.get();
if (!notifier.isEmpty()) {
notifier.notify(toString());
}
}
private ContextNotActiveException notActive() {
String msg = "Request context is not active - you can activate the request context for a specific method using the @ActivateRequestContext interceptor binding";
return new ContextNotActiveException(msg);
}
private static Notifier<Object> createInitializedNotifier() {
return EventImpl.createNotifier(Object.class, Object.class,
new HashSet<>(Arrays.asList(Initialized.Literal.REQUEST, Any.Literal.INSTANCE)),
ArcContainerImpl.instance(), false);
}
private static Notifier<Object> createBeforeDestroyedNotifier() {
return EventImpl.createNotifier(Object.class, Object.class,
new HashSet<>(Arrays.asList(BeforeDestroyed.Literal.REQUEST, Any.Literal.INSTANCE)),
ArcContainerImpl.instance(), false);
}
private static Notifier<Object> createDestroyedNotifier() {
return EventImpl.createNotifier(Object.class, Object.class,
new HashSet<>(Arrays.asList(Destroyed.Literal.REQUEST, Any.Literal.INSTANCE)),
ArcContainerImpl.instance(), false);
}
static class RequestContextState implements ContextState {
private final Map<Contextual<?>, ContextInstanceHandle<?>> map;
private volatile boolean isValid;
RequestContextState(ConcurrentMap<Contextual<?>, ContextInstanceHandle<?>> value) {
this.map = Objects.requireNonNull(value);
this.isValid = true;
}
@Override
public Map<InjectableBean<?>, Object> getContextualInstances() {
return map.values().stream()
.collect(Collectors.toUnmodifiableMap(ContextInstanceHandle::getBean, ContextInstanceHandle::get));
}
@Override
public boolean isValid() {
return isValid;
}
}
}