forked from actframework/actframework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventBus.java
More file actions
1522 lines (1386 loc) · 52.9 KB
/
EventBus.java
File metadata and controls
1522 lines (1386 loc) · 52.9 KB
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package act.event;
/*-
* #%L
* ACT Framework
* %%
* Copyright (C) 2014 - 2017 ActFramework
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
import act.Destroyable;
import act.app.App;
import act.app.AppServiceBase;
import act.app.event.SysEvent;
import act.app.event.SysEventId;
import act.app.event.SysEventListener;
import act.inject.DependencyInjectionBinder;
import act.inject.DependencyInjector;
import act.job.JobManager;
import org.osgl.$;
import org.osgl.logging.LogManager;
import org.osgl.logging.Logger;
import org.osgl.util.C;
import org.osgl.util.E;
import org.osgl.util.S;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
/**
* The event bus manages event binding and distribution.
*/
@ApplicationScoped
public class EventBus extends AppServiceBase<EventBus> {
// The key to index adhoc event listeners
private static class Key {
private enum IdType {
STRING, ENUM, CLASS
}
private static final Class[] EMPTY_ARG_LIST = new Class[0];
// the event identifier, could be
// 1. a specific string value
// 2. a specific enum value
// 3. an Enum class
// 4. a class extends EventObject
private Object id;
private IdType idType;
private Class[] argTypes;
private boolean varargs;
private Object[] args;
Key(Object id, SimpleEventListener eventListener) {
setId(id);
setArgTypes(eventListener);
}
Key(Object id, List<Class> argTypeList, Object[] args) {
this(id, argTypeList, args, false);
}
Key(Object id, List<Class> argTypeList, Object[] args, boolean varargs) {
setId(id);
this.argTypes = convert(argTypeList);
this.args = args;
this.varargs = varargs;
}
private void setArgTypes(SimpleEventListener eventListener) {
List<Class> argTypeList = eventListener.argumentTypes();
if (null == argTypeList || argTypeList.isEmpty()) {
this.argTypes = EMPTY_ARG_LIST;
return;
}
Class<?> arg0Type = argTypeList.get(0);
this.argTypes = convert(argTypeList);
int varargsIdx = 1;
if (this.id != arg0Type && !arg0Type.isInstance(id)) {
E.illegalArgumentIf(idType == IdType.CLASS, "The first argument in the event listener argument list must be event when binding to an event class (Enum or EventObject). \n\t listener: %s \n\t event: %s", eventListener, this.id);
varargsIdx = 0;
}
this.varargs = (varargsIdx + 1) == argTypeList.size() && Object[].class == argTypeList.get(varargsIdx);
}
private void setId(Object id) {
this.idType = typeOf(id);
this.id = IdType.CLASS == this.idType && !(id instanceof Class) ? id.getClass() : id;
}
static IdType typeOf(Object id) {
if (id instanceof String) {
return IdType.STRING;
} else if (Enum.class.isInstance(id)) {
return IdType.ENUM;
} else {
Class<?> type = id instanceof Class ? (Class<?>) id : id.getClass();
if (Enum.class.isAssignableFrom(type) || EventObject.class.isAssignableFrom(type)) {
return IdType.CLASS;
} else {
throw E.unexpected("Invalid event type: %s", id);
}
}
}
private static Class[] convert(List<Class> argList) {
int sz = argList.size();
Class[] ca = argList.toArray(new Class[sz]);
for (int i = 0; i < sz; ++i) {
ca[i] = $.wrapperClassOf(ca[i]);
}
return ca;
}
private static Class<?> VARARG_TYPE = Object[].class;
private static ConcurrentMap<Class, Class> typeMap = new ConcurrentHashMap<>();
// checkout https://github.com/actframework/actframework/issues/518
private static Class effectiveTypeOf(Object o) {
return effectiveTypeOf(o.getClass());
}
private static Class effectiveTypeOf(Class<?> type) {
if (null == type || Object.class == type) {
return type;
}
Class mappedType = typeMap.get(type);
if (null == mappedType) {
int modifiers = type.getModifiers();
if (!Modifier.isPublic(modifiers)
|| type.isAnonymousClass()
|| type.isLocalClass()
|| type.isMemberClass()) {
Class[] ca = type.getInterfaces();
if (ca.length > 0) {
for (Class intf: ca) {
if (Modifier.isPublic(intf.getModifiers())) {
mappedType = intf;
}
}
}
if (null == mappedType) {
Class<?> parent = type.getSuperclass();
mappedType = (null == parent || Object.class == parent) ? type : effectiveTypeOf(parent);
}
typeMap.putIfAbsent(type, mappedType);
} else {
typeMap.putIfAbsent(type, type);
mappedType = type;
}
}
return mappedType;
}
// create list of keys from event triggering id and argument list
static List<Key> keysOf(Class<?> idClass, Object id, Object[] args, EventBus eventBus) {
List<Key> keys = new ArrayList<>();
List<Class> argTypes = new ArrayList<>();
List<Class> varArgTypes = new ArrayList<>();
varArgTypes.add(VARARG_TYPE);
for (Object arg: args) {
if (null == arg) {
argTypes = null;
break;
}
argTypes.add(effectiveTypeOf(arg));
}
IdType type = typeOf(id);
if (IdType.STRING == type) {
if (!eventBus.stringsWithAdhocListeners.contains(id)) {
return C.list();
}
if (null != argTypes) {
keys.add(new Key(id, argTypes, args));
}
keys.add(new Key(id, varArgTypes, new Object[]{args}));
} else if (IdType.CLASS == type) {
if (!eventBus.classesWithAdhocListeners.contains(idClass)) {
return C.list();
}
varArgTypes.add(0, idClass);
Object[] varArgs = new Object[2];
varArgs[0] = id;
varArgs[1] = args;
keys.add(new Key(id, varArgTypes, varArgs));
if (null != argTypes) {
Object[] finalArgs = $.concat(new Object[]{id}, args);
argTypes.add(0, idClass);
keys.add(new Key(id, argTypes, finalArgs));
}
} else {
// the enum value
if (eventBus.enumsWithAdhocListeners.contains(id)) {
keys.add(new Key(id, varArgTypes, new Object[]{args}));
if (null != argTypes) {
keys.add(new Key(id, argTypes, args));
}
}
// the enum class
if (eventBus.classesWithAdhocListeners.contains(id.getClass())) {
List<Class> varArgTypesForClass = new ArrayList<>(2);
Object[] varArgs = new Object[2];
varArgs[0] = id;
varArgs[1] = args;
varArgTypesForClass.add(id.getClass());
varArgTypesForClass.add(VARARG_TYPE);
keys.add(new Key(id.getClass(), varArgTypesForClass, varArgs, true));
if (null != argTypes) {
List<Class> argTypesForClass = new ArrayList<>(1 + argTypes.size());
argTypesForClass.add(id.getClass());
argTypesForClass.addAll(argTypes);
keys.add(new Key(id.getClass(), argTypesForClass, $.concat(new Object[]{id}, args), true));
}
}
}
return keys;
}
@Override
public int hashCode() {
return $.hc(id, argTypes);
}
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (obj instanceof Key) {
Key that = $.cast(obj);
return $.eq(that.id, this.id) && $.eq2(that.argTypes, this.argTypes);
}
return false;
}
@Override
public String toString() {
return !varargs ? S.fmt("(%s, %s)", id, $.toString2(argTypes)) :
S.fmt("(%s, ...)", id);
}
}
private abstract static class EventContext<T> {
boolean asyncForAsync = true;
boolean asyncForSync = false;
Class<? extends T> eventType;
List<Key> keys;
List<Key> keysForOnceBus;
T event;
Object[] args;
EventContext(T event, Object[] args) {
this.event = event;
this.args = args;
}
EventContext(boolean asyncForAsync, boolean asyncForSync, T event, Object[] args) {
this(event, args);
this.asyncForAsync = asyncForAsync;
this.asyncForSync = asyncForSync;
}
final Class<? extends T> eventType() {
if (null == eventType) {
eventType = lookupEventType();
}
return eventType;
}
List<Key> keys(EventBus eventBus) {
if (eventBus.once) {
if (null == keysForOnceBus) {
keysForOnceBus = Key.keysOf(eventType(), event, args, eventBus);
}
return keysForOnceBus;
} else {
if (null == keys) {
keys = Key.keysOf(eventType(), event, args, eventBus);
}
return keys;
}
}
boolean hasArgs() {
return 0 < args.length;
}
boolean shouldCallActEventListeners(EventBus eventBus) {
return !hasArgs() && eventBus.eventsWithActListeners.contains(eventType());
}
Class<? extends T> lookupEventType() {
return $.cast(event.getClass());
}
abstract boolean shouldCallAdhocEventListeners(EventBus eventBus);
}
private static class EnumEventContext extends EventContext<Enum> {
EnumEventContext(Enum event, Object[] args) {
super(event, args);
}
EnumEventContext(boolean asyncForAsync, boolean asyncForSync, Enum event, Object[] args) {
super(asyncForAsync, asyncForSync, event, args);
}
@Override
Class<? extends Enum> lookupEventType() {
return event.getDeclaringClass();
}
@Override
boolean shouldCallAdhocEventListeners(EventBus eventBus) {
return eventBus.hasAdhocEventListenerFor(event);
}
}
private static class StringEventContext extends EventContext<String> {
StringEventContext(String event, Object[] args) {
super(event, args);
}
StringEventContext(boolean asyncForAsync, boolean asyncForSync, String event, Object[] args) {
super(asyncForAsync, asyncForSync, event, args);
}
@Override
boolean shouldCallAdhocEventListeners(EventBus eventBus) {
return eventBus.hasAdhocEventListenerFor(event);
}
}
private static class EventObjectContext<T extends EventObject> extends EventContext<T> {
EventObjectContext(T event, Object[] args) {
super(event, args);
}
EventObjectContext(boolean asyncForAsync, boolean asyncForSync, T event, Object[] args) {
super(asyncForAsync, asyncForSync, event, args);
}
@Override
Class<? extends T> lookupEventType() {
return $.cast(ActEvent.typeOf(event));
}
@Override
boolean shouldCallAdhocEventListeners(EventBus eventBus) {
return eventBus.hasAdhocEventListenerFor(event);
}
}
private static class ActEventContext extends EventObjectContext<ActEvent<?>> {
ActEventContext(ActEvent<?> event, Object[] args) {
super(event, args);
}
ActEventContext(boolean asyncForAsync, boolean asyncForSync, ActEvent<?> event, Object[] args) {
super(asyncForAsync, asyncForSync, event, args);
}
@Override
Class<? extends ActEvent<?>> lookupEventType() {
return ActEvent.typeOf(event);
}
}
private static final Logger LOGGER = LogManager.get(EventBus.class);
// is this event bus for one time event listener?
private boolean once;
// index SysEvent by SysEventId.ordinal()
private final SysEvent[] sysEventLookup;
// stores sys event listeners, the listener list indexed by event ID ordinal
private final List[] sysEventListeners;
// stores async sys event listeners, the listener list indexed by event ID ordinal
private final List[] asyncSysEventListeners;
// stores the associations from event type to event listeners
private final ConcurrentMap<Class<? extends EventObject>, List<ActEventListener>> actEventListeners;
// stores the associations from event type to async event listeners
private final ConcurrentMap<Class<? extends EventObject>, List<ActEventListener>> asyncActEventListeners;
// stores the association from Key and ad hoc event listeners
private final ConcurrentMap<Key, List<SimpleEventListener>> adhocEventListeners;
// stores the association from Key and async ad hoc event listeners
private final ConcurrentMap<Key, List<SimpleEventListener>> asyncAdhocEventListeners;
// so we can quickly identify if it needs to go ahead to look for listeners
private final Set<Class<?>> classesWithAdhocListeners = new HashSet<>();
private final Set<Enum> enumsWithAdhocListeners = new HashSet<>();
private final Set<String> stringsWithAdhocListeners = new HashSet<>();
private final Set<Class<? extends EventObject>> eventsWithActListeners = new HashSet<>();
// is this event bus for one time event listeners?
private EventBus onceBus;
private EventBus(App app, boolean once) {
super(app, true);
sysEventLookup = initSysEventLookup(app);
sysEventListeners = initAppListenerArray();
asyncSysEventListeners = initAppListenerArray();
actEventListeners = new ConcurrentHashMap<>();
asyncActEventListeners = new ConcurrentHashMap<>();
adhocEventListeners = new ConcurrentHashMap<>();
asyncAdhocEventListeners = new ConcurrentHashMap<>();
loadDefaultEventListeners();
if (!once) {
onceBus = new EventBus(app, true);
onceBus.once = true;
}
}
@Inject
public EventBus(App app) {
this(app, false);
}
@Override
protected void releaseResources() {
if (null != onceBus) {
onceBus.releaseResources();
}
releaseSysEventListeners(sysEventListeners);
releaseSysEventListeners(asyncSysEventListeners);
releaseActEventListeners(actEventListeners);
releaseActEventListeners(asyncActEventListeners);
releaseAdhocEventListeners(adhocEventListeners);
releaseAdhocEventListeners(asyncAdhocEventListeners);
}
/**
* Override parent implementation so that if this
* event bus is a one time event bus, it will prepend
* `[once]` into the message been logged
*
* @param msg
* the message
* @param args
* the message arguments
*/
@Override
protected void trace(String msg, Object... args) {
msg = S.fmt(msg, args);
if (once) {
msg = S.builder("[once]").append(msg).toString();
}
super.trace(msg);
}
/**
* Bind an {@link SysEventListener} to a {@link SysEventId}.
*
* If `@Async` annotation is presented on the `sysEventListener`'s class,
* it will bind the listener to the async repo, and it will be invoked
* asynchronously if event triggered.
*
* **Note** this method is not supposed to be called by user application
* directly.
*
* @param sysEventId
* the {@link SysEventId system event ID}
* @param sysEventListener
* an instance of {@link SysEventListener}
* @return this event bus instance
*/
@SuppressWarnings("unchecked")
public synchronized EventBus bind(final SysEventId sysEventId, final SysEventListener<?> sysEventListener) {
boolean async = isAsync(sysEventListener.getClass());
return _bind(async ? asyncSysEventListeners : sysEventListeners, sysEventId, sysEventListener);
}
/**
* Bind an {@link ActEventListener} to an event type extended from {@link EventObject}.
*
* If either `eventType` or the class of `eventListener` has `@Async` annotation presented,
* it will bind the listener into the async repo. When event get triggered the listener
* will be invoked asynchronously.
*
* @param eventType
* the target event type - should be a sub class of {@link EventObject}
* @param eventListener
* an instance of {@link ActEventListener} or it's sub class
* @return this event bus instance
*/
public EventBus bind(Class<? extends EventObject> eventType, ActEventListener eventListener) {
boolean async = isAsync(eventListener.getClass()) || isAsync(eventType);
return _bind(async ? asyncActEventListeners : actEventListeners, eventType, eventListener, 0);
}
/**
* Bind an {@link ActEventListener} to an event type extended from {@link EventObject} with
* time expiration `ttl` specified.
*
* If `ttl` is `0` or negative number, then the event listener will never get expired.
*
* If either `eventType` or the class of `eventListener` has `@Async` annotation presented,
* it will bind the listener into the async repo. When event get triggered the listener
* will be invoked asynchronously.
*
* @param eventType
* the target event type - should be a sub class of {@link EventObject}
* @param eventListener
* an instance of {@link ActEventListener} or it's sub class
* @param ttl
* the number of seconds this binding should live
* @return this event bus instance
*/
public EventBus bind(Class<? extends EventObject> eventType, ActEventListener eventListener, int ttl) {
boolean async = isAsync(eventListener.getClass()) || isAsync(eventType);
return _bind(async ? asyncActEventListeners : actEventListeners, eventType, eventListener, ttl);
}
/**
* Bind a {@link SimpleEventListener} to an object. The object could be one of
*
* * a specific string value
* * a specific enum value
* * an Enum typed class
* * an EventObject typed class
*
* If either `event` or the the method backed the `eventListener` has `@Async`
* annotation presented, it will bind the listener into the async repo. When
* event get triggered the listener will be invoked asynchronously.
*
* **Note** this method is not supposed to be called by user application directly.
*
* @param event
* the target event object
* @param eventListener
* a {@link SimpleEventListener} instance
* @return this event bus instance
* @see SimpleEventListener
*/
public EventBus bind(Object event, final SimpleEventListener eventListener) {
return _bind(event, eventListener, eventListener.isAsync() || _isAsync(event));
}
/**
* Bind an {@link SysEventListener} to a {@link SysEventId} asynchronously.
*
* **Note** this method is not supposed to be called by user application
* directly.
*
* @param sysEventId
* the {@link SysEventId system event ID}
* @param sysEventListener
* an instance of {@link SysEventListener}
* @return this event bus instance
*/
public synchronized EventBus bindAsync(SysEventId sysEventId, SysEventListener sysEventListener) {
return _bind(asyncSysEventListeners, sysEventId, sysEventListener);
}
/**
* Bind a {@link ActEventListener eventListener} to an event type extended
* from {@link EventObject} asynchronously.
*
* @param eventType
* the target event type - should be a sub class of {@link EventObject}
* @param eventListener
* the listener - an instance of {@link ActEventListener} or it's sub class
* @return this event bus instance
* @see #bind(Class, ActEventListener)
*/
public EventBus bindAsync(Class<? extends EventObject> eventType, ActEventListener eventListener) {
return _bind(asyncActEventListeners, eventType, eventListener, 0);
}
/**
* Bind a {@link ActEventListener eventListener} to
* {@link EventObject class} asynchronously with time expiration
* specified.
*
* @param eventType
* the target event type - should be a sub class of {@link EventObject}
* @param eventListener
* the listener - an instance of {@link ActEventListener} or it's sub class
* @param ttl
* the number of seconds this binding should live
* @return this event bus instance
* @see #bind(Class, ActEventListener)
*/
public EventBus bindAsync(Class<? extends EventObject> eventType, ActEventListener eventListener, int ttl) {
return _bind(asyncActEventListeners, eventType, eventListener, ttl);
}
public EventBus bindAsync(Object event, final SimpleEventListener eventListener) {
return _bind(event, eventListener, true);
}
/**
* Bind an {@link SysEventListener} to a {@link SysEventId} synchronously.
*
* **Note** this method is not supposed to be called by user application
* directly.
*
* @param sysEventId
* the {@link SysEventId system event ID}
* @param sysEventListener
* an instance of {@link SysEventListener}
* @return this event bus instance
* @see #bind(SysEventId, SysEventListener)
*/
public synchronized EventBus bindSync(SysEventId sysEventId, SysEventListener sysEventListener) {
return _bind(sysEventListeners, sysEventId, sysEventListener);
}
/**
* Bind a {@link ActEventListener eventListener} to an event type extended
* from {@link EventObject} synchronously.
*
* @param eventType
* the target event type - should be a sub class of {@link EventObject}
* @param eventListener
* the listener - an instance of {@link ActEventListener} or it's sub class
* @return this event bus instance
* @see #bind(Class, ActEventListener)
*/
public EventBus bindSync(Class<? extends EventObject> eventType, ActEventListener eventListener) {
return _bind(actEventListeners, eventType, eventListener, 0);
}
/**
* Bind a {@link ActEventListener eventListener} to
* {@link EventObject class} synchronously with time expiration
* specified.
*
* @param eventType
* the target event type - should be a sub class of {@link EventObject}
* @param eventListener
* the listener - an instance of {@link ActEventListener} or it's sub class
* @param ttl
* the number of seconds this binding should live
* @return this event bus instance
* @see #bind(Class, ActEventListener)
*/
public EventBus bindSync(final Class<? extends EventObject> eventType, final ActEventListener eventListener, int ttl) {
return _bind(actEventListeners, eventType, eventListener, ttl);
}
/**
* Emit a system event by {@link SysEventId event ID}.
*
* This will invoke the synchronous bound event listeners synchronously and
* asynchronous bound event listeners asynchronously.
*
* **Note** this method shall not be used by application developer.
*
* @param eventId
* the {@link SysEventId system event ID}
* @return
* this event bus instance
*/
public synchronized EventBus emit(SysEventId eventId) {
if (isDestroyed()) {
return this;
}
if (null != onceBus) {
onceBus.emit(eventId);
}
return _emit(true, false, eventId);
}
/**
* Emit an enum event with parameters supplied.
*
* This will invoke all {@link SimpleEventListener} bound to the specific
* enum value and all {@link SimpleEventListener} bound to the enum class
* given the listeners has the matching argument list.
*
* For example, given the following enum definition:
*
* ```java
* public enum UserActivity {LOGIN, LOGOUT}
* ```
*
* We have the following simple event listener methods:
*
* ```java
* {@literal @}OnEvent
* public void handleUserActivity(UserActivity, User user) {...}
*
* {@literal @}OnUserActivity(UserActivity.LOGIN)
* public void logUserLogin(User user, long timestamp) {...}
*
* {@literal @}OnUserActivity(UserActivity.LOGOUT)
* public void logUserLogout(User user) {...}
* ```
*
* The following code will invoke `logUserLogin` method:
*
* ```java
* User user = ...;
* eventBus.emit(UserActivity.LOGIN, user, System.currentTimeMills());
* ```
*
* The `handleUserActivity` is not invoked because
*
* * The method parameter `(UserActivity, User, long)` does not match the declared argument list `(UserActivity, User)`
*
* While the following code will invoke both `handleUserActivity` and `logUserLogout` methods:
*
* ```java
* User user = ...;
* eventBus.emit(UserActivity.LOGOUT, user);
* ```
*
* The `logUserLogin` method will not be invoked because
*
* 1. the method is bound to `UserActivity.LOGIN` enum value specifically, while `LOGOUT` is triggered
* 2. the method has a `long timestamp` in the argument list and it is not passed to `eventBus.emit`
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see SimpleEventListener
*/
public EventBus emit(Enum<?> event, Object... args) {
return _emitWithOnceBus(eventContext(event, args));
}
/**
* Emit a string event with parameters.
*
* This will invoke all {@link SimpleEventListener} bound to the specified
* string value given the listeners has the matching argument list.
*
* For example, suppose we have the following simple event listener methods:
*
* ```java
* {@literal @}On("USER-LOGIN")
* public void logUserLogin(User user, long timestamp) {...}
*
* {@literal @}On("USER-LOGIN")
* public void checkDuplicateLoginAttempts(User user, Object... args) {...}
*
* {@literal @}On("USER-LOGIN")
* public void foo(User user) {...}
* ```
*
* The following code will invoke `logUserLogin` and `checkDuplicateLoginAttempts` methods:
*
* ```java
* User user = ...;
* eventBus.emit("USER-LOGIN", user, System.currentTimeMills());
* ```
*
* The `foo(User)` will not invoked because:
*
* * The parameter list `(User, long)` does not match the declared argument list `(User)`.
* Here the `String` in the parameter list is taken out because it is used to indicate
* the event, instead of being passing through to the event handler method.
* * The method `checkDuplicateLoginAttempts(User, Object ...)` will be invoked because
* it declares a varargs typed arguments, meaning it matches any parameters passed in.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see SimpleEventListener
*/
public EventBus emit(String event, Object... args) {
return _emitWithOnceBus(eventContext(event, args));
}
/**
* Emit an event object with parameters.
*
* This will invoke all {@link SimpleEventListener} bound to the event object
* class given the listeners has the matching argument list.
*
* If there is no parameter passed in, i.e. `args.length == 0`, then it will
* also invoke all the {@link ActEventListener} bound to the event class.
*
* For example, suppose we have the following Event defined:
*
* ```java
* public class UserActivityEvent extends ActEvent<User> {
* public UserActivityEvent(User user) {super(user);}
* }
* ```
*
* And we have the following event handler defined:
*
* ```java
* {@literal @}OnEvent
* public void logUserLogin(UserActivityEvent event, long timestamp) {...}
*
* {@literal @}OnEvent
* public void checkDuplicateLoginAttempts(UserActivityEvent, Object... args) {...}
*
* {@literal @}OnEvent
* public void foo(UserActivityEvent event) {...}
* ```
*
* The following code will invoke `logUserLogin` and `checkDuplicateLoginAttempts` methods:
*
* ```java
* User user = ...;
* eventBus.emit(new UserActivityEvent(user), System.currentTimeMills());
* ```
*
* The `foo(UserActivityEvent)` will not invoked because:
*
* * The parameter list `(UserActivityEvent, long)` does not match the declared
* argument list `(UserActivityEvent)`. Here the `String` in the parameter
* list is taken out because it is used to indicate the event, instead of being
* passing through to the event handler method.
* * The method `checkDuplicateLoginAttempts(UserActivityEvent, Object ...)` will
* be invoked because it declares a varargs typed arguments, meaning it matches
* any parameters passed in.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see SimpleEventListener
*/
public EventBus emit(EventObject event, Object... args) {
return _emitWithOnceBus(eventContext(event, args));
}
/**
* Overload {@link #emit(EventObject, Object...)} for performance tuning.
* @see #emit(EventObject, Object...)
*/
public EventBus emit(ActEvent event, Object... args) {
return _emitWithOnceBus(eventContext(event, args));
}
/**
* Emit a system event by {@link SysEventId event ID} and force event listeners
* be invoked asynchronously without regarding to how listeners are bound.
*
* **Note** this method shall not be used by application developer.
*
* @param eventId
* the {@link SysEventId system event ID}
* @return
* this event bus instance
* @see #emit(SysEventId)
*/
public synchronized EventBus emitAsync(SysEventId eventId) {
if (isDestroyed()) {
return this;
}
if (null != onceBus) {
onceBus.emit(eventId);
}
return _emit(true, true, eventId);
}
/**
* Emit an enum event with parameters and force all listeners to be called asynchronously.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see #emit(Enum, Object...)
*/
public EventBus emitAsync(Enum<?> event, Object... args) {
return _emitWithOnceBus(eventContextAsync(event, args));
}
/**
* Emit a string event with parameters and force all listeners to be called asynchronously.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see #emit(String, Object...)
*/
public EventBus emitAsync(String event, Object... args) {
return _emitWithOnceBus(eventContextAsync(event, args));
}
/**
* Emit a event object with parameters and force all listeners to be called asynchronously.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see #emit(EventObject, Object...)
*/
public EventBus emitAsync(EventObject event, Object... args) {
return _emitWithOnceBus(eventContextAsync(event, args));
}
/**
* Overload {@link #emitAsync(EventObject, Object...)} for performance
* tuning.
* @see #emitAsync(EventObject, Object...)
*/
public EventBus emitAsync(ActEvent event, Object... args) {
return _emitWithOnceBus(eventContextAsync(event, args));
}
/**
* Emit a system event by {@link SysEventId event ID} and force event listeners
* be invoked synchronously without regarding to how listeners are bound.
*
* **Note** this method shall not be used by application developer.
*
* @param eventId
* the {@link SysEventId system event ID}
* @return
* this event bus instance
* @see #emit(SysEventId)
*/
public synchronized EventBus emitSync(SysEventId eventId) {
if (isDestroyed()) {
return this;
}
if (null != onceBus) {
onceBus.emit(eventId);
}
return _emit(false, false, eventId);
}
/**
* Emit an enum event with parameters and force all listener to be called synchronously.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see #emit(Enum, Object...)
*/
public EventBus emitSync(Enum<?> event, Object... args) {
return _emitWithOnceBus(eventContextSync(event, args));
}
/**
* Emit a string event with parameters and force all listener to be called synchronously.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see #emit(String, Object...)
*/
public EventBus emitSync(String event, Object... args) {
return _emitWithOnceBus(eventContextSync(event, args));
}
/**
* Emit a event object with parameters and force all listeners to be called synchronously.
*
* @param event
* the target event
* @param args
* the arguments passed in
* @see #emit(EventObject, Object...)
*/
public EventBus emitSync(EventObject event, Object... args) {
return _emitWithOnceBus(eventContextSync(event, args));
}
/**
* Overload {@link #emitSync(EventObject, Object...)} for performance tuning.
* @see #emitSync(EventObject, Object...)
*/
public EventBus emitSync(ActEvent event, Object... args) {
return _emitWithOnceBus(eventContextSync(event, args));
}
/**
* Alias of {@link #emit(SysEventId)}.
*/
public EventBus trigger(SysEventId eventId) {
return emit(eventId);
}
/**
* Bind an {@link OnceEventListenerBase once event listener} to an {@link EventObject event object type}
*
* @param eventType
* the event object type
* @param listener