Debian Codegraph @

spec/src/main/doc/events.asciidoc

raw
1 [[events]]
2
3 == Events
4
5 Beans may produce and consume events. This facility allows beans to interact in a completely decoupled fashion, with no compile-time dependency between the interacting beans. Most importantly, it allows stateful beans in one architectural tier of the application to synchronize their internal state with state changes that occur in a different tier.
6
7 An event comprises:
8
9 * A Java object - the _event object_
10 * A set of instances of qualifier types - the _event qualifiers_
11
12
13 The event object acts as a payload, to propagate state from producer to consumer. The event qualifiers act as topic selectors, allowing the consumer to narrow the set of events it observes.
14
15 An _observer method_ acts as event consumer, observing events of a specific type - the _observed event type_ - with a specific set of qualifiers - the _observed event qualifiers_. An observer method will be notified of an event if the event object is assignable to the observed event type, and if the set of observed event qualifiers is a subset of all the event qualifiers of the event.
16
17 [[event_types_and_qualifier_types]]
18
19 === Event types and qualifier types
20
21 An event object is an instance of a concrete Java class with no unresolvable type variables. The _event types_ of the event include all superclasses and interfaces of the runtime class of the event object.
22
23 An event type may not contain an unresolvable type variable.
24
25 An event qualifier type is just an ordinary qualifier type as specified in <<defining_qualifier_types>>, typically defined as +@Target({METHOD, FIELD, PARAMETER, TYPE})+ or +@Target({FIELD, PARAMETER})+.
26
27 Every event has the qualifier [email protected]+, even if it does not explicitly declare this qualifier.
28
29 Any Java type may be an observed event type.
30
31 [[firing_events]]
32
33 === Firing events
34
35 Beans fire events via an instance of the +javax.enterprise.event.Event+ interface, which may be injected:
36
37 [source, java]
38 ----
39 @Inject Event<LoggedInEvent> loggedInEvent;
40 ----
41
42 The method +fire()+ accepts an event object:
43
44 [source, java]
45 ----
46 public void login() {
47 ...
48 loggedInEvent.fire( new LoggedInEvent(user) );
49 }
50 ----
51
52 Any combination of qualifiers may be specified at the injection point:
53
54 [source, java]
55 ----
56 @Inject @Admin Event<LoggedInEvent> adminLoggedInEvent;
57 ----
58
59 Or the application may specify qualifiers dynamically:
60
61 [source, java]
62 ----
63 @Inject Event<LoggedInEvent> loggedInEvent;
64 ...
65 LoggedInEvent event = new LoggedInEvent(user);
66 if ( user.isAdmin() ) {
67 loggedInEvent.select( new AdminQualifier() ).fire(event);
68 }
69 else {
70 loggedInEvent.fire(event);
71 }
72 ----
73
74 In this example, the event sometimes has the qualifier +@Admin+, depending upon the value of +user.isAdmin()+.
75
76 [[event]]
77
78 ==== The +Event+ interface
79
80 The +Event+ interface provides a method for firing events with a specified combination of type and qualifiers:
81
82 [source, java]
83 ----
84 public interface Event<T> {
85
86 public void fire(T event);
87
88 public Event<T> select(Annotation... qualifiers);
89 public <U extends T> Event<U> select(Class<U> subtype, Annotation... qualifiers);
90 public <U extends T> Event<U> select(TypeLiteral<U> subtype, Annotation... qualifiers);
91
92 }
93 ----
94
95 For an injected +Event+:
96
97 * the _specified type_ is the type parameter specified at the injection point, and
98 * the _specified qualifiers_ are the qualifiers specified at the injection point.
99
100
101 For example, this injected +Event+ has specified type +LoggedInEvent+ and specified qualifier +@Admin+:
102
103 [source, java]
104 ----
105 @Inject @Admin Event<LoggedInEvent> any;
106 ----
107
108 The +select()+ method returns a child +Event+ for a given specified type and additional specified qualifiers. If no specified type is given, the specified type is the same as the parent.
109
110 For example, this child +Event+ has required type +AdminLoggedInEvent+ and additional specified qualifier +@Admin+:
111
112 [source, java]
113 ----
114 Event<AdminLoggedInEvent> admin = any.select(
115 AdminLoggedInEvent.class,
116 new AdminQualifier() );
117 ----
118
119 If the specified type contains a type variable, an +IllegalArgumentException+ is thrown.
120
121 If two instances of the same qualifier type are passed to +select()+, an +IllegalArgumentException+ is thrown.
122
123 If an instance of an annotation that is not a qualifier type is passed to +select()+, an +IllegalArgumentException+ is thrown.
124
125 The method +fire()+ fires an event with the specified qualifiers and notifies observers, as defined by <<observer_notification>>. If the container is unable to resolve the parameterized type of the event object, it uses the specified type to infer the parameterized type of the event types.
126
127 If the runtime type of the event object contains an unresolvable type variable, an +IllegalArgumentException+ is thrown.
128
129 If the runtime type of the event object is assignable to the type of a container lifecycle event, an +IllegalArgumentException+ is thrown.
130
131 [[builtin_event]]
132
133 ==== The built-in +Event+
134
135 The container must provide a built-in bean with:
136
137 * +Event<X>+ in its set of bean types, for every Java type +X+ that does not contain a type variable,
138 * every event qualifier type in its set of qualifier types,
139 * scope +@Dependent+,
140 * no bean name, and
141 * an implementation provided automatically by the container.
142
143
144 If an injection point of raw type +Event+ is defined, the container automatically detects the problem and treats it as a definition error.
145
146 The built-in implementation must be a passivation capable dependency, as defined in <<passivation_capable_dependency>>.
147
148 [[observer_resolution]]
149
150 === Observer resolution
151
152 The process of matching an event to its observer methods is called _observer resolution_. The container considers event type and qualifiers when resolving observers.
153
154 Observer resolution usually occurs at runtime.
155
156 An event is delivered to an observer method if:
157
158 * The observer method belongs to an enabled bean.
159 * An event type is assignable to the observed event type, taking type parameters into consideration.
160 * The observer method has no event qualifiers or has a subset of the event qualifiers. An observer method has an event qualifier if it has an observed event qualifier with (a) the same type and (b) the same annotation member value for each member which is not annotated [email protected]+.
161 * Either the event is not a container lifecycle event, as defined in <<init_events>>, or the observer method belongs to an extension.
162
163
164 If the runtime type of the event object contains an unresolvable type variable, the container must throw an +IllegalArgumentException+.
165
166 For a custom implementation of the +ObserverMethod+ interface defined in <<observer_method>>, the container must call +getObservedType()+ and +getObservedQualifiers()+ to determine the observed event type and qualifiers.
167
168 [[observers_assignability]]
169
170 ==== Assignability of type variables, raw and parameterized types
171
172 An event type is considered assignable to a type variable if the event type is assignable to the upper bound, if any.
173
174 A parameterized event type is considered assignable to a raw observed event type if the raw types are identical.
175
176 A parameterized event type is considered assignable to a parameterized observed event type if they have identical raw type and for each parameter:
177
178 * the observed event type parameter is an actual type with identical raw type to the event type parameter, and, if the type is parameterized, the event type parameter is assignable to the observed event type parameter according to these rules, or
179 * the observed event type parameter is a wildcard and the event type parameter is assignable to the upper bound, if any, of the wildcard and assignable from the lower bound, if any, of the wildcard, or
180 * the observed event type parameter is a type variable and the event type parameter is assignable to the upper bound, if any, of the type variable.
181
182 [[event_qualifier_types_with_members]]
183
184 ==== Event qualifier types with members
185
186 As usual, the qualifier type may have annotation members:
187
188 [source, java]
189 ----
190 @Qualifier
191 @Target(PARAMETER)
192 @Retention(RUNTIME)
193 public @interface Role {
194 String value();
195 }
196 ----
197
198 Consider the following event:
199
200 [source, java]
201 ----
202 @Inject Event<LoggedInEvent> loggedInEvent;
203 ...
204 public void login() {
205 final User user = ...;
206 loggedInEvent.select(new RoleQualifier() { public String value() { return user.getRole(); } }).fire(new LoggedInEvent(user));
207 }
208 ----
209
210 Where +RoleQualifier+ is an implementation of the qualifier type +Role+:
211
212 [source, java]
213 ----
214 public abstract class RoleQualifier
215 extends AnnotationLiteral<Role>
216 implements Role {}
217 ----
218
219 Then the following observer method will always be notified of the event:
220
221 [source, java]
222 ----
223 public void afterLogin(@Observes LoggedInEvent event) { ... }
224 ----
225
226 Whereas this observer method may or may not be notified, depending upon the value of +user.getRole()+:
227
228 [source, java]
229 ----
230 public void afterAdminLogin(@Observes @Role("admin") LoggedInEvent event) { ... }
231 ----
232
233 As usual, the container uses +equals()+ to compare event qualifier type member values.
234
235 [[multiple_event_qualifiers]]
236
237 ==== Multiple event qualifiers
238
239 An event parameter may have multiple qualifiers.
240
241 [source, java]
242 ----
243 public void afterDocumentUpdatedByAdmin(@Observes @Updated @ByAdmin Document doc) { ... }
244 ----
245
246 Then this observer method will only be notified if all the observed event qualifiers are specified when the event is fired:
247
248 [source, java]
249 ----
250 @Inject Event<Document> documentEvent;
251 ...
252 documentEvent.select(new UpdatedQualifier(), new ByAdminQualifier()).fire(document);
253 ----
254
255 Other, less specific, observers will also be notified of this event:
256
257 [source, java]
258 ----
259 public void afterDocumentUpdated(@Observes @Updated Document doc) { ... }
260 ----
261
262 [source, java]
263 ----
264 public void afterDocumentEvent(@Observes Document doc) { ... }
265 ----
266
267 [[observer_methods]]
268
269 === Observer methods
270
271 An observer method allows the application to receive and respond to event notifications.
272
273 An observer method is a non-abstract method of a managed bean class or session bean class (or of an extension, as defined in <<init_events>>). An observer method may be either static or non-static. If the bean is a session bean, the observer method must be either a business method of the EJB or a static method of the bean class.
274
275 There may be arbitrarily many observer methods with the same event parameter type and qualifiers.
276
277 A bean (or extension) may declare multiple observer methods.
278
279 [[observer_method_event_parameter]]
280
281 ==== Event parameter of an observer method
282
283 Each observer method must have exactly one _event parameter_, of the same type as the event type it observes. When searching for observer methods for an event, the container considers the type and qualifiers of the event parameter.
284
285 If the event parameter does not explicitly declare any qualifier, the observer method observes events with no qualifier.
286
287 The event parameter type may contain a type variable or wildcard.
288
289 The event parameter may be an array type whose component type contains a type variable or a wildcard.
290
291 [[observes]]
292
293 ==== Declaring an observer method
294
295 An observer method may be declared by annotating a parameter [email protected]+ of a default-access, public, protected or private method. That parameter is the event parameter. The declared type of the parameter is the observed event type.
296
297 [source, java]
298 ----
299 public void afterLogin(@Observes LoggedInEvent event) { ... }
300 ----
301
302 If a method has more than one parameter annotated +@Observes+, the container automatically detects the problem and treats it as a definition error.
303
304 Observed event qualifiers may be declared by annotating the event parameter:
305
306 [source, java]
307 ----
308 public void afterLogin(@Observes @Admin LoggedInEvent event) { ... }
309 ----
310
311 If an observer method is annotated +@Produces+ or +@Inject+ or has a parameter annotated +@Disposes+, the container automatically detects the problem and treats it as a definition error.
312
313 If a non-static method of a session bean class has a parameter annotated +@Observes+, and the method is not a business method of the EJB, the container automatically detects the problem and treats it as a definition error.
314
315 Interceptors and decorators may not declare observer methods. If an interceptor or decorator has a method with a parameter annotated +@Observes+, the container automatically detects the problem and treats it as a definition error.
316
317 In addition to the event parameter, observer methods may declare additional parameters, which may declare qualifiers. These additional parameters are injection points.
318
319 [source, java]
320 ----
321 public void afterLogin(@Observes LoggedInEvent event, @Manager User user, Logger log) { ... }
322 ----
323
324 [[event_metadata]]
325
326 ==== The +EventMetadata+ interface
327
328 The interface +javax.enterprise.inject.spi.EventMetadata+ provides access to metadata about an observed event.
329
330 [source, java]
331 ----
332 public interface EventMetadata {
333 public Set<Annotation> getQualifiers();
334 public InjectionPoint getInjectionPoint();
335 public Type getType();
336 }
337 ----
338
339 * +getQualifiers()+ returns the set of qualifiers with which the event was fired.
340 * +getInjectionPoint()+ returns the +InjectionPoint+ from which this event payload was fired, or +null+ if it was fired from +BeanManager.fireEvent(...)+.
341 * +getType()+ returns the type representing runtime class of the event object with type variables resolved.
342
343 The container must provide a bean with scope +@Dependent+, bean type +EventMetadata+ and qualifier +@Default+, allowing observer methods to obtain information about the events they observe.
344
345 If an injection point of type +EventMetadata+ and qualifier +@Default+ which is not a parameter of an observer method exists, the container automatically detects the problem and treats it as a definition error.
346
347 [source, java]
348 ----
349 public void afterLogin(@Observes LoggedInEvent event, EventMetadata metadata) { ... }
350 ----
351
352 [[conditional_observer_methods]]
353
354 ==== Conditional observer methods
355
356 A _conditional observer method_ is an observer method which is notified of an event only if an instance of the bean that defines the observer method already exists in the current context.
357
358 A conditional observer method may be declared by specifying +receive=IF_EXISTS+.
359
360 [source, java]
361 ----
362 public void refreshOnDocumentUpdate(@Observes(receive=IF_EXISTS) @Updated Document doc) { ... }
363 ----
364
365 Beans with scope +@Dependent+ may not have conditional observer methods. If a bean with scope +@Dependent+ has an observer method declared +receive=IF_EXISTS+, the container automatically detects the problem and treats it as a definition error.
366
367 The enumeration +javax.enterprise.event.Reception+ identifies the possible values of +receive+:
368
369 [source, java]
370 ----
371 public enum Reception { IF_EXISTS, ALWAYS }
372 ----
373
374 [[transactional_observer_methods]]
375
376 ==== Transactional observer methods
377
378 _Transactional observer methods_ are observer methods which receive event notifications during the before or after completion phase of the transaction in which the event was fired. If no transaction is in progress when the event is fired, they are notified at the same time as other observers.
379
380 * A _before completion_ observer method is called during the before completion phase of the transaction.
381 * An _after completion_ observer method is called during the after completion phase of the transaction.
382 * An _after success_ observer method is called during the after completion phase of the transaction, only when the transaction completes successfully.
383 * An _after failure_ observer method is called during the after completion phase of the transaction, only when the transaction fails.
384
385
386 The enumeration +javax.enterprise.event.TransactionPhase+ identifies the kind of transactional observer method:
387
388 [source, java]
389 ----
390 public enum TransactionPhase {
391 IN_PROGRESS,
392 BEFORE_COMPLETION,
393 AFTER_COMPLETION,
394 AFTER_FAILURE,
395 AFTER_SUCCESS
396 }
397 ----
398
399 A transactional observer method may be declared by specifying any value other than +IN_PROGRESS+ for +during+:
400
401 [source, java]
402 ----
403 void onDocumentUpdate(@Observes(during=AFTER_SUCCESS) @Updated Document doc) { ... }
404 ----
405
406 [[observer_notification]]
407
408 === Observer notification
409
410 When an event is fired by the application, the container must:
411
412 * determine the observer methods for that event according to the rules of observer resolution defined by <<observer_resolution>>, then,
413 * for each observer method, either invoke the observer method immediately, or register the observer method for later invocation during the transaction completion phase, using a JTA +Synchronization+.
414
415
416 The container calls observer methods as defined in <<observers_method_invocation>>.
417
418 * If the observer method is a transactional observer method and there is currently a JTA transaction in progress, the container calls the observer method during the appropriate transaction completion phase.
419 * If there is no context active for the scope to which the bean declaring the observer method belongs, then the observer method should not be called.
420 * Otherwise, the container calls the observer immediately.
421
422
423 The order in which observer methods are called is not defined, and so portable applications should not rely upon the order in which observers are called.
424
425 Any observer method called before completion of a transaction may call +setRollbackOnly()+ to force a transaction rollback. An observer method may not directly initiate, commit or rollback JTA transactions.
426
427 Observer methods may throw exceptions:
428
429 * If the observer method is a transactional observer method, any exception is caught and logged by the container.
430 * Otherwise, the exception aborts processing of the event. No other observer methods of that event will be called. The +BeanManager.fireEvent()+ or +Event.fire()+ method rethrows the exception. If the exception is a checked exception, it is wrapped and rethrown as an (unchecked) +ObserverException+.
431
432
433 For a custom implementation of the +ObserverMethod+ interface defined in <<observer_method>>, the container must call +getTransactionPhase()+ to determine if the observer method is transactional observer method, and +notify()+ to invoke the method.
434
435 [[observer_method_invocation_context]]
436
437 ==== Observer method invocation context
438
439 The transaction context, client security context and lifecycle contexts active when an observer method is invoked depend upon what kind of observer method it is.
440
441 * If the observer method is a before completion transactional observer method, it is called within the context of the transaction that is about to complete and with the same client security context and lifecycle contexts.
442 * Otherwise, if the observer method is any other kind of transactional observer method, it is called in an unspecified transaction context, but with the same client security context and lifecycle contexts as the transaction that just completed.
443 * Otherwise, the observer method is called in the same transaction context, client security context and lifecycle contexts as the invocation of +Event.fire()+ or +BeanManager.fireEvent()+.
444
445
446 Of course, the transaction and security contexts for a business method of a session bean also depend upon the transaction attribute and +@RunAs+ descriptor, if any.
447