/
TimerServiceImpl.java
1159 lines (1040 loc) · 43.7 KB
/
TimerServiceImpl.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
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
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.ejb3.timerservice;
import org.jboss.as.ejb3.component.EJBComponent;
import org.jboss.as.ejb3.component.TimerServiceRegistry;
import org.jboss.as.ejb3.component.allowedmethods.AllowedMethodsInformation;
import org.jboss.as.ejb3.component.allowedmethods.MethodType;
import org.jboss.as.ejb3.component.entity.EntityBeanComponent;
import org.jboss.as.ejb3.component.singleton.SingletonComponent;
import org.jboss.as.ejb3.component.stateful.CurrentSynchronizationCallback;
import org.jboss.as.ejb3.context.CurrentInvocationContext;
import org.jboss.as.ejb3.timerservice.persistence.TimerPersistence;
import org.jboss.as.ejb3.timerservice.spi.ScheduleTimer;
import org.jboss.as.ejb3.timerservice.spi.TimedObjectInvoker;
import org.jboss.as.ejb3.timerservice.task.TimerTask;
import org.jboss.invocation.InterceptorContext;
import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import javax.ejb.EJBException;
import javax.ejb.ScheduleExpression;
import javax.ejb.Timer;
import javax.ejb.TimerConfig;
import javax.ejb.TimerHandle;
import javax.ejb.TimerService;
import javax.transaction.RollbackException;
import javax.transaction.Status;
import javax.transaction.Synchronization;
import javax.transaction.SystemException;
import javax.transaction.Transaction;
import javax.transaction.TransactionManager;
import javax.transaction.TransactionSynchronizationRegistry;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import static org.jboss.as.ejb3.EjbLogger.ROOT_LOGGER;
import static org.jboss.as.ejb3.EjbMessages.MESSAGES;
/**
* MK2 implementation of EJB3.1 {@link TimerService}
*
* @author <a href="mailto:cdewolf@redhat.com">Carlo de Wolf</a>
* @version $Revision: $
*/
public class TimerServiceImpl implements TimerService, Service<TimerService> {
/**
* inactive timer states
*/
private static final Set<TimerState> ineligibleTimerStates;
/**
* Logger
*/
private static final Logger logger = Logger.getLogger(TimerServiceImpl.class);
public static final ServiceName SERVICE_NAME = ServiceName.of("ejb3", "timerService");
/**
* The service name this timer service is registered under
*/
private final ServiceName serviceName;
private final InjectedValue<EJBComponent> ejbComponentInjectedValue = new InjectedValue<EJBComponent>();
private final InjectedValue<ExecutorService> executorServiceInjectedValue = new InjectedValue<ExecutorService>();
private final InjectedValue<java.util.Timer> timerInjectedValue = new InjectedValue<java.util.Timer>();
private final InjectedValue<TimedObjectInvoker> timedObjectInvoker = new InjectedValue<TimedObjectInvoker>();
/**
* Auto timers that should be added on startup
*/
private final Map<Method, List<AutoTimer>> autoTimers;
/**
* Used for persistent timers
*/
private final InjectedValue<TimerPersistence> timerPersistence = new InjectedValue<TimerPersistence>();
/**
* All timers which were created by this {@link TimerService}
*/
private final Map<String, TimerImpl> timers = Collections.synchronizedMap(new HashMap<String, TimerImpl>());
/**
* Holds the {@link java.util.concurrent.Future} of each of the timer tasks that have been scheduled
*/
private final Map<String, java.util.TimerTask> scheduledTimerFutures = new HashMap<String, java.util.TimerTask>();
/**
* Key that is used to store timers that are waiting on transaction completion in the transaction local
*/
private static final Object waitingOnTxCompletionKey = new Object();
private TransactionManager transactionManager;
private TransactionSynchronizationRegistry tsr;
private final TimerServiceRegistry timerServiceRegistry;
private volatile boolean started = false;
static {
final Set<TimerState> states = new HashSet<TimerState>();
states.add(TimerState.CANCELED);
states.add(TimerState.EXPIRED);
ineligibleTimerStates = Collections.unmodifiableSet(states);
}
/**
* Creates a {@link TimerServiceImpl}
*
* @param autoTimers
* @param serviceName
* @throws IllegalArgumentException If either of the passed param is null
* @deprecated Use {@link #TimerServiceImpl(java.util.Map, org.jboss.msc.service.ServiceName, org.jboss.as.ejb3.component.TimerServiceRegistry)} instead
*/
@Deprecated
public TimerServiceImpl(final Map<Method, List<AutoTimer>> autoTimers, final ServiceName serviceName) {
this(autoTimers, serviceName, null);
}
/**
* Creates a {@link TimerServiceImpl}
*
* @param autoTimers The auto timers associated with this timer service
* @param serviceName The service name of this timer service
* @param registry The {@link TimerServiceRegistry} which has the knowledge of other timer services belonging to the EJB module to which this
* timer service belongs.
*/
public TimerServiceImpl(final Map<Method, List<AutoTimer>> autoTimers, final ServiceName serviceName, final TimerServiceRegistry registry) {
this.autoTimers = autoTimers;
this.serviceName = serviceName;
this.timerServiceRegistry = registry;
}
@Override
public synchronized void start(final StartContext context) throws StartException {
logger.debug("Starting timerservice for timedObjectId: " + getInvoker().getTimedObjectId());
final EJBComponent component = ejbComponentInjectedValue.getValue();
this.transactionManager = component.getTransactionManager();
this.tsr = component.getTransactionSynchronizationRegistry();
final TimedObjectInvoker invoker = timedObjectInvoker.getValue();
if (invoker == null) {
throw MESSAGES.invokerIsNull();
}
final List<ScheduleTimer> timers = new ArrayList<ScheduleTimer>();
for (Map.Entry<Method, List<AutoTimer>> entry : autoTimers.entrySet()) {
for (AutoTimer timer : entry.getValue()) {
timers.add(new ScheduleTimer(entry.getKey(), timer.getScheduleExpression(), timer.getTimerConfig()));
}
}
// restore the timers
started = true;
restoreTimers(timers);
// register ourselves to the TimerServiceRegistry (if any)
if (timerServiceRegistry != null) {
timerServiceRegistry.registerTimerService(this);
}
}
@Override
public synchronized void stop(final StopContext context) {
// un-register ourselves to the TimerServiceRegistry (if any)
if (timerServiceRegistry != null) {
timerServiceRegistry.unRegisterTimerService(this);
}
suspendTimers();
timerPersistence.getValue().timerUndeployed(timedObjectInvoker.getValue().getTimedObjectId());
started = false;
this.transactionManager = null;
}
@Override
public synchronized TimerService getValue() throws IllegalStateException, IllegalArgumentException {
return this;
}
/**
* {@inheritDoc}
*/
@Override
public Timer createCalendarTimer(ScheduleExpression schedule) throws IllegalArgumentException,
IllegalStateException, EJBException {
return this.createCalendarTimer(schedule, null);
}
/**
* {@inheritDoc}
*/
@Override
public Timer createCalendarTimer(ScheduleExpression schedule, TimerConfig timerConfig)
throws IllegalArgumentException, IllegalStateException, EJBException {
assertTimerServiceState();
Serializable info = timerConfig == null ? null : timerConfig.getInfo();
boolean persistent = timerConfig == null || timerConfig.isPersistent();
return this.createCalendarTimer(schedule, info, persistent, null);
}
/**
* {@inheritDoc}
*/
@Override
public Timer createIntervalTimer(Date initialExpiration, long intervalDuration, TimerConfig timerConfig)
throws IllegalArgumentException, IllegalStateException, EJBException {
assertTimerServiceState();
if (initialExpiration == null) {
throw MESSAGES.initialExpirationIsNullCreatingTimer();
}
if (initialExpiration.getTime() < 0) {
throw MESSAGES.invalidInitialExpiration("initialExpiration.getTime()");
}
if (intervalDuration < 0) {
throw MESSAGES.invalidInitialExpiration("intervalDuration");
}
return this.createTimer(initialExpiration, intervalDuration, timerConfig.getInfo(), timerConfig.isPersistent());
}
/**
* {@inheritDoc}
*/
@Override
public Timer createIntervalTimer(long initialDuration, long intervalDuration, TimerConfig timerConfig)
throws IllegalArgumentException, IllegalStateException, EJBException {
assertTimerServiceState();
if (initialDuration < 0) {
throw MESSAGES.invalidInitialExpiration("intervalDuration");
}
if (intervalDuration < 0) {
throw MESSAGES.invalidInitialExpiration("intervalDuration");
}
return this.createIntervalTimer(new Date(System.currentTimeMillis() + initialDuration), intervalDuration, timerConfig);
}
/**
* {@inheritDoc}
*/
@Override
public Timer createSingleActionTimer(Date expiration, TimerConfig timerConfig) throws IllegalArgumentException,
IllegalStateException, EJBException {
assertTimerServiceState();
if (expiration == null) {
throw MESSAGES.expirationIsNull();
}
if (expiration.getTime() < 0) {
throw MESSAGES.invalidExpirationActionTimer();
}
return this.createTimer(expiration, 0, timerConfig.getInfo(), timerConfig.isPersistent());
}
/**
* {@inheritDoc}
*/
@Override
public Timer createSingleActionTimer(long duration, TimerConfig timerConfig) throws IllegalArgumentException,
IllegalStateException, EJBException {
assertTimerServiceState();
if (duration < 0)
throw MESSAGES.invalidDurationActionTimer();
return createTimer(new Date(System.currentTimeMillis() + duration), 0, timerConfig.getInfo(), timerConfig
.isPersistent());
}
/**
* {@inheritDoc}
*/
@Override
public Timer createTimer(long duration, Serializable info) throws IllegalArgumentException, IllegalStateException,
EJBException {
assertTimerServiceState();
if (duration < 0)
throw MESSAGES.invalidDurationTimer();
return createTimer(new Date(System.currentTimeMillis() + duration), 0, info, true);
}
/**
* {@inheritDoc}
*/
@Override
public Timer createTimer(Date expiration, Serializable info) throws IllegalArgumentException, IllegalStateException,
EJBException {
assertTimerServiceState();
if (expiration == null) {
throw MESSAGES.expirationDateIsNull();
}
if (expiration.getTime() < 0) {
throw MESSAGES.invalidExpirationTimer();
}
return this.createTimer(expiration, 0, info, true);
}
/**
* {@inheritDoc}
*/
@Override
public Timer createTimer(long initialDuration, long intervalDuration, Serializable info)
throws IllegalArgumentException, IllegalStateException, EJBException {
assertTimerServiceState();
if (initialDuration < 0) {
throw MESSAGES.invalidInitialDurationTimer();
}
if (intervalDuration < 0) {
throw MESSAGES.invalidIntervalTimer();
}
return this.createTimer(new Date(System.currentTimeMillis() + initialDuration), intervalDuration, info, true);
}
/**
* {@inheritDoc}
*/
@Override
public Timer createTimer(Date initialExpiration, long intervalDuration, Serializable info)
throws IllegalArgumentException, IllegalStateException, EJBException {
assertTimerServiceState();
if (initialExpiration == null) {
throw MESSAGES.initialExpirationDateIsNull();
}
if (initialExpiration.getTime() < 0) {
throw MESSAGES.invalidExpirationTimer();
}
if (intervalDuration < 0) {
throw MESSAGES.invalidIntervalDurationTimer();
}
return this.createTimer(initialExpiration, intervalDuration, info, true);
}
public TimerImpl loadAutoTimer(ScheduleExpression schedule,
TimerConfig timerConfig, Method timeoutMethod) {
return this.createCalendarTimer(schedule, timerConfig.getInfo(), timerConfig.isPersistent(), timeoutMethod);
}
/**
* {@inheritDoc}
*/
@Override
public Collection<Timer> getTimers() throws IllegalStateException, EJBException {
assertTimerServiceState();
Object pk = currentPrimaryKey();
final Set<Timer> activeTimers = new HashSet<Timer>();
// get all active timers for this timerservice
for (final TimerImpl timer : this.timers.values()) {
if (timer.isActive()) {
if (timer.getPrimaryKey() == null || timer.getPrimaryKey().equals(pk)) {
activeTimers.add(timer);
}
}
}
// get all active timers which are persistent, but haven't yet been
// persisted (waiting for tx to complete) that are in the current transaction
for (final TimerImpl timer : getWaitingOnTxCompletionTimers().values()) {
if (timer.isActive()) {
if (timer.getPrimaryKey() == null || timer.getPrimaryKey().equals(pk)) {
activeTimers.add(timer);
}
}
}
return activeTimers;
}
/**
* {@inheritDoc}
*/
@Override
public Collection<Timer> getAllTimers() throws IllegalStateException, EJBException {
// query the registry
if (this.timerServiceRegistry != null) {
return this.timerServiceRegistry.getAllActiveTimers();
}
// if we don't have the registry (shouldn't really happen) which stores the timer services applicable for the EJB module to which
// this timer service belongs, then let's at least return the active timers that are applicable only for this timer service
return this.getTimers();
}
/**
* Create a {@link javax.ejb.Timer}
*
* @param initialExpiration The {@link java.util.Date} at which the first timeout should occur.
* <p>If the date is in the past, then the timeout is triggered immediately
* when the timer moves to {@link TimerState#ACTIVE}</p>
* @param intervalDuration The interval (in milliseconds) between consecutive timeouts for the newly created timer.
* <p>Cannot be a negative value. A value of 0 indicates a single timeout action</p>
* @param info {@link java.io.Serializable} info that will be made available through the newly created timer's {@link javax.ejb.Timer#getInfo()} method
* @param persistent True if the newly created timer has to be persistent
* @return Returns the newly created timer
* @throws IllegalArgumentException If <code>initialExpiration</code> is null or <code>intervalDuration</code> is negative
* @throws IllegalStateException If this method was invoked during a lifecycle callback on the EJB
*/
private Timer createTimer(Date initialExpiration, long intervalDuration, Serializable info, boolean persistent) {
if (this.isLifecycleCallbackInvocation() && !this.isSingletonBeanInvocation()) {
throw MESSAGES.failToCreateTimerDoLifecycle();
}
if (initialExpiration == null) {
throw MESSAGES.initialExpirationIsNull();
}
if (intervalDuration < 0) {
throw MESSAGES.invalidIntervalDuration();
}
// create an id for the new timer instance
UUID uuid = UUID.randomUUID();
// create the timer
TimerImpl timer = TimerImpl.builder()
.setNewTimer(true)
.setId(uuid.toString())
.setInitialDate(initialExpiration)
.setRepeatInterval(intervalDuration)
.setInfo(info)
.setPersistent(persistent)
.setPrimaryKey(currentPrimaryKey())
.setTimerState(TimerState.CREATED)
.setTimedObjectId(getInvoker().getTimedObjectId())
.build(this);
// now "start" the timer. This involves, moving the timer to an ACTIVE state
// and scheduling the timer task
this.persistTimer(timer, true);
this.startTimer(timer);
// return the newly created timer
return timer;
}
/**
* @return The primary key of the current EJB, or null if not applicable
*/
private Object currentPrimaryKey() {
final InterceptorContext context = CurrentInvocationContext.get();
if (context == null) {
return null;
}
return context.getPrivateData(EntityBeanComponent.PRIMARY_KEY_CONTEXT_KEY);
}
/**
* Creates a calendar based {@link javax.ejb.Timer}
*
* @param schedule The {@link javax.ejb.ScheduleExpression} which will be used for creating scheduled timer tasks
* for a calendar based timer
* @param info {@link java.io.Serializable} info that will be made available through the newly created timer's {@link javax.ejb.Timer#getInfo()} method
* @param persistent True if the newly created timer has to be persistent
* @return Returns the newly created timer
* @throws IllegalArgumentException If the passed <code>schedule</code> is null
* @throws IllegalStateException If this method was invoked during a lifecycle callback on the EJB
*/
private TimerImpl createCalendarTimer(ScheduleExpression schedule,
Serializable info, boolean persistent, Method timeoutMethod) {
if (this.isLifecycleCallbackInvocation() && !this.isSingletonBeanInvocation()) {
throw MESSAGES.failToCreateTimerDoLifecycle();
}
if (schedule == null) {
throw MESSAGES.scheduleIsNull();
}
// generate a id for the timer
UUID uuid = UUID.randomUUID();
// create the timer
TimerImpl timer = CalendarTimer.builder()
.setAutoTimer(timeoutMethod != null)
.setScheduleExprSecond(schedule.getSecond())
.setScheduleExprMinute(schedule.getMinute())
.setScheduleExprHour(schedule.getHour())
.setScheduleExprDayOfWeek(schedule.getDayOfWeek())
.setScheduleExprDayOfMonth(schedule.getDayOfMonth())
.setScheduleExprMonth(schedule.getMonth())
.setScheduleExprYear(schedule.getYear())
.setScheduleExprStartDate(schedule.getStart())
.setScheduleExprEndDate(schedule.getEnd())
.setScheduleExprTimezone(schedule.getTimezone())
.setTimeoutMethod(timeoutMethod)
.setTimerState(TimerState.CREATED)
.setId(uuid.toString())
.setPersistent(persistent)
.setPrimaryKey(currentPrimaryKey())
.setTimedObjectId(getInvoker().getTimedObjectId())
.setInfo(info)
.setNewTimer(true)
.build(this);
this.persistTimer(timer, true);
// now "start" the timer. This involves, moving the timer to an ACTIVE state
// and scheduling the timer task
this.startTimer(timer);
// return the timer
return timer;
}
public TimerImpl getTimer(final String timedObjectId, final String timerId) {
return timers.get(timerId);
}
/**
* Returns the {@link TimedObjectInvoker} to which this timer service belongs
*
* @return
*/
public TimedObjectInvoker getInvoker() {
return timedObjectInvoker.getValue();
}
/**
* Returns the {@link javax.ejb.Timer} corresponding to the passed {@link javax.ejb.TimerHandle}
*
* @param handle The {@link javax.ejb.TimerHandle} for which the {@link javax.ejb.Timer} is being looked for
*/
public TimerImpl getTimer(TimerHandle handle) {
TimerHandleImpl timerHandle = (TimerHandleImpl) handle;
TimerImpl timer = timers.get(timerHandle.getId());
if (timer != null) {
return timer;
}
return getWaitingOnTxCompletionTimers().get(timerHandle.getId());
}
/**
* @return Returns the current transaction, if any. Else returns null.
* @throws javax.ejb.EJBException If there is any system level exception
*/
protected Transaction getTransaction() {
try {
return transactionManager.getTransaction();
} catch (SystemException e) {
throw new EJBException(e);
}
}
/**
* Persists the passed <code>timer</code>.
* <p/>
* <p>
* If the passed timer is null or is non-persistent (i.e. {@link javax.ejb.Timer#isPersistent()} returns false),
* then this method acts as a no-op
* </p>
*
* @param timer
*/
public void persistTimer(final TimerImpl timer, boolean newTimer) {
if (timer == null) {
return;
}
if (timer.isTimerPersistent()) {
try {
if (timerPersistence.getOptionalValue() == null) {
ROOT_LOGGER.timerPersistenceNotEnable();
return;
}
if (newTimer) {
timerPersistence.getValue().addTimer(timer);
} else {
timerPersistence.getValue().persistTimer(timer);
}
} catch (Throwable t) {
this.setRollbackOnly();
throw new RuntimeException(t);
}
}
}
public void cancelTimer(final TimerImpl timer) {
timer.lock();
boolean release = true;
try {
// first check whether the timer has expired or has been cancelled
timer.assertTimerState();
boolean startedInTx = getWaitingOnTxCompletionTimers().containsKey(timer.getId());
if (timer.getState() != TimerState.EXPIRED) {
timer.setTimerState(TimerState.CANCELED);
}
if (transactionActive() && !startedInTx) {
registerSynchronization(new TimerRemoveSynchronization(timer));
release = false;
} else {
// cancel any scheduled Future for this timer
this.cancelTimeout(timer);
}
// persist changes
persistTimer(timer, false);
} finally {
if (release) {
timer.unlock();
}
}
}
public void expireTimer(final TimerImpl timer) {
cancelTimeout(timer);
timer.setTimerState(TimerState.EXPIRED);
timers.remove(timer.getId());
}
/**
* Suspends any currently scheduled tasks for {@link javax.ejb.Timer}s
* <p>
* Note that, suspend does <b>not</b> cancel the {@link javax.ejb.Timer}. Instead,
* it just cancels the <b>next scheduled timeout</b>. So once the {@link javax.ejb.Timer}
* is restored (whenever that happens), the {@link javax.ejb.Timer} will continue to
* timeout at appropriate times.
* </p>
*/
public void suspendTimers() {
// get all active timers (persistent/non-persistent inclusive)
Collection<Timer> timers = this.getTimers();
for (Timer timer : timers) {
if (!(timer instanceof TimerImpl)) {
continue;
}
// suspend the timer
((TimerImpl) timer).suspend();
}
}
/**
* Restores persisted timers, corresponding to this timerservice, which are eligible for any new timeouts.
* <p>
* This includes timers whose {@link TimerState} is <b>neither</b> of the following:
* <ul>
* <li>{@link TimerState#CANCELED}</li>
* <li>{@link TimerState#EXPIRED}</li>
* </ul>
* </p>
* <p>
* All such restored timers will be schedule for their next timeouts.
* </p>
*
* @param autoTimers
*/
public void restoreTimers(final List<ScheduleTimer> autoTimers) {
// get the persisted timers which are considered active
List<TimerImpl> restorableTimers = this.getActivePersistentTimers();
//timers are removed from the list as they are loaded
final List<ScheduleTimer> newAutoTimers = new LinkedList<ScheduleTimer>(autoTimers);
ROOT_LOGGER.debug("Found " + restorableTimers.size() + " active persistentTimers for timedObjectId: "
+ getInvoker().getTimedObjectId());
// now "start" each of the restorable timer. This involves, moving the timer to an ACTIVE state
// and scheduling the timer task
for (final TimerImpl activeTimer : restorableTimers) {
if (activeTimer.isAutoTimer()) {
CalendarTimer calendarTimer = (CalendarTimer) activeTimer;
boolean found = false;
//so we know we have an auto timer. We need to try and match it up with the auto timers.
ListIterator<ScheduleTimer> it = newAutoTimers.listIterator();
while (it.hasNext()) {
ScheduleTimer timer = it.next();
final String methodName = timer.getMethod().getName();
final String[] params = new String[timer.getMethod().getParameterTypes().length];
for (int i = 0; i < timer.getMethod().getParameterTypes().length; ++i) {
params[i] = timer.getMethod().getParameterTypes()[i].getName();
}
if (doesTimeoutMethodMatch(calendarTimer.getTimeoutMethod(), methodName, params)) {
//the timers have the same method.
//now lets make sure the schedule is the same
// and the timer does not change the persistence
if (this.doesScheduleMatch(calendarTimer.getScheduleExpression(), timer.getScheduleExpression()) && timer.getTimerConfig().isPersistent()) {
it.remove();
found = true;
break;
}
}
}
if (!found) {
activeTimer.setTimerState(TimerState.CANCELED);
} else {
startTimer(activeTimer);
ROOT_LOGGER.debug("Started timer: " + activeTimer);
}
this.persistTimer(activeTimer, false);
} else if (!ineligibleTimerStates.contains(activeTimer.getState())) {
startTimer(activeTimer);
}
ROOT_LOGGER.debug("Started timer: " + activeTimer);
}
for (ScheduleTimer timer : newAutoTimers) {
this.loadAutoTimer(timer.getScheduleExpression(), timer.getTimerConfig(), timer.getMethod());
}
}
/**
* Registers a timer with a transaction (if any in progress) and then moves
* the timer to a active state, so that it becomes eligible for timeouts
*/
protected void startTimer(TimerImpl timer) {
// if there's no transaction, then trigger a schedule immidiately.
// Else, the timer will be scheduled on tx synchronization callback
if (!transactionActive()) {
this.timers.put(timer.getId(), timer);
timer.setTimerState(TimerState.ACTIVE);
// create and schedule a timer task
timer.scheduleTimeout(true);
} else {
addWaitingOnTxCompletionTimer(timer);
registerSynchronization(new TimerCreationTransactionSynchronization(timer));
}
}
private void registerSynchronization(Synchronization synchronization) {
try {
final Transaction tx = this.getTransaction();
// register for lifecycle events of transaction
tx.registerSynchronization(synchronization);
} catch (RollbackException e) {
throw new EJBException(e);
} catch (SystemException e) {
throw new EJBException(e);
}
}
/**
* @return true if the transaction is in a state where synchronizations can be registered
*/
boolean transactionActive() {
final Transaction currentTx = getTransaction();
if (currentTx != null) {
try {
int status = currentTx.getStatus();
if (status == Status.STATUS_MARKED_ROLLBACK || status == Status.STATUS_ROLLEDBACK ||
status == Status.STATUS_ROLLING_BACK || status == Status.STATUS_NO_TRANSACTION ||
status == Status.STATUS_UNKNOWN || status == Status.STATUS_COMMITTED
|| isBeforeCompletion()) {
return false;
} else {
return true;
}
} catch (SystemException e) {
throw new RuntimeException(e);
}
} else {
return false;
}
}
private boolean isBeforeCompletion() {
final CurrentSynchronizationCallback.CallbackType type = CurrentSynchronizationCallback.get();
if (type != null) {
return type == CurrentSynchronizationCallback.CallbackType.BEFORE_COMPLETION;
}
return false;
}
/**
* Returns true if the {@link CurrentInvocationContext} represents a lifecycle
* callback invocation. Else returns false.
* <p>
* This method internally relies on {@link CurrentInvocationContext#get()} to obtain
* the current invocation context.
* <ul>
* <li>If the context is available then it looks for the method that was invoked.
* The absence of a method indicates a lifecycle callback.</li>
* <li>If the context is <i>not</i> available, then this method returns false (i.e.
* it doesn't consider the current invocation as a lifecycle callback). This is
* for convenience, to allow the invocation of {@link javax.ejb.TimerService} methods
* in the absence of {@link CurrentInvocationContext}</li>
* </ul>
* <p/>
* </p>
*
* @return
*/
protected boolean isLifecycleCallbackInvocation() {
final InterceptorContext currentInvocationContext = CurrentInvocationContext.get();
if (currentInvocationContext == null) {
return false;
}
// If the method in current invocation context is null,
// then it represents a lifecycle callback invocation
Method invokedMethod = currentInvocationContext.getMethod();
if (invokedMethod == null) {
// it's a lifecycle callback
return true;
}
// not an lifecycle callback
return false;
}
/**
* Creates and schedules a {@link org.jboss.as.ejb3.timerservice.task.TimerTask} for the next timeout of the passed <code>timer</code>
*/
protected void scheduleTimeout(TimerImpl timer, boolean newTimer) {
synchronized (scheduledTimerFutures) {
if (!newTimer && !scheduledTimerFutures.containsKey(timer.getId())) {
//this timer has been cancelled by another thread. We just return
return;
}
Date nextExpiration = timer.getNextExpiration();
if (nextExpiration == null) {
ROOT_LOGGER.nextExpirationIsNull(timer);
return;
}
// create the timer task
final TimerTask<?> timerTask = timer.getTimerTask();
// find out how long is it away from now
long delay = nextExpiration.getTime() - System.currentTimeMillis();
// if in past, then trigger immediately
if (delay < 0) {
delay = 0;
}
long intervalDuration = timer.getInterval();
final Task task = new Task(timerTask);
if (intervalDuration > 0) {
ROOT_LOGGER.debug("Scheduling timer " + timer + " at fixed rate, starting at " + delay
+ " milliseconds from now with repeated interval=" + intervalDuration);
// schedule the task
this.timerInjectedValue.getValue().scheduleAtFixedRate(task, delay, intervalDuration);
// maintain it in timerservice for future use (like cancellation)
this.scheduledTimerFutures.put(timer.getId(), task);
} else {
ROOT_LOGGER.debug("Scheduling a single action timer " + timer + " starting at " + delay + " milliseconds from now");
// schedule the task
this.timerInjectedValue.getValue().schedule(task, delay);
// maintain it in timerservice for future use (like cancellation)
this.scheduledTimerFutures.put(timer.getId(), task);
}
}
}
/**
* Cancels any scheduled {@link java.util.concurrent.Future} corresponding to the passed <code>timer</code>
*
* @param timer
*/
protected void cancelTimeout(final TimerImpl timer) {
synchronized (this.scheduledTimerFutures) {
java.util.TimerTask timerTask = this.scheduledTimerFutures.remove(timer.getId());
if (timerTask != null) {
timerTask.cancel();
}
}
}
/**
* Returns an unmodifiable view of timers in the current transaction that are waiting for the transaction
* to finish
*/
private Map<String, TimerImpl> getWaitingOnTxCompletionTimers() {
Map<String, TimerImpl> timers = null;
if (getTransaction() != null) {
timers = (Map<String, TimerImpl>) tsr.getResource(waitingOnTxCompletionKey);
}
return timers == null ? Collections.<String, TimerImpl>emptyMap() : timers;
}
private void addWaitingOnTxCompletionTimer(final TimerImpl timer) {
Map<String, TimerImpl> timers = (Map<String, TimerImpl>) tsr.getResource(waitingOnTxCompletionKey);
if (timers == null) {
tsr.putResource(waitingOnTxCompletionKey, timers = new HashMap<String, TimerImpl>());
}
timers.put(timer.getId(), timer);
}
private boolean isSingletonBeanInvocation() {
return ejbComponentInjectedValue.getValue() instanceof SingletonComponent;
}
private List<TimerImpl> getActivePersistentTimers() {
// we need only those timers which correspond to the
// timed object invoker to which this timer service belongs. So
// first get hold of the timed object id
final String timedObjectId = this.getInvoker().getTimedObjectId();
// timer states which do *not* represent an active timer
if (timerPersistence.getOptionalValue() == null) {
//if the persistence setting is null then there are no persistent timers
return Collections.emptyList();
}
final List<TimerImpl> persistedTimers = timerPersistence.getValue().loadActiveTimers(timedObjectId, this);
final List<TimerImpl> activeTimers = new ArrayList<TimerImpl>();
for (final TimerImpl persistedTimer : persistedTimers) {
if (ineligibleTimerStates.contains(persistedTimer.getState())) {
continue;
}
// add it to the list of timers which will be restored
activeTimers.add(persistedTimer);
}
return activeTimers;
}
private boolean doesTimeoutMethodMatch(final Method timeoutMethod, final String timeoutMethodName, final String[] methodParams) {
if (timeoutMethod.getName().equals(timeoutMethodName) == false) {
return false;
}
final Class<?>[] timeoutMethodParams = timeoutMethod.getParameterTypes();
return this.methodParamsMatch(timeoutMethodParams, methodParams);
}
private boolean doesScheduleMatch(final ScheduleExpression expression1, final ScheduleExpression expression2) {
if (!same(expression1.getDayOfMonth(), expression2.getDayOfMonth())) {
return false;
}
if (!same(expression1.getDayOfWeek(), expression2.getDayOfWeek())) {
return false;
}
if (!same(expression1.getEnd(), expression2.getEnd())) {
return false;
}
if (!same(expression1.getHour(), expression2.getHour())) {
return false;
}
if (!same(expression1.getMinute(), expression2.getMinute())) {
return false;
}
if (!same(expression1.getMonth(), expression2.getMonth())) {
return false;
}
if (!same(expression1.getSecond(), expression2.getSecond())) {
return false;
}
if (!same(expression1.getStart(), expression2.getStart())) {
return false;
}
if (!same(expression1.getTimezone(), expression2.getTimezone())) {
return false;
}
if (!same(expression1.getYear(), expression2.getYear())) {
return false;
}
return true;
}
private boolean same(Object i1, Object i2) {
if (i1 == null && i2 != null) {
return false;
}
if (i2 == null && i1 != null) {
return false;
}
if (i1 == null && i2 == null) {
return true;
}
return i1.equals(i2);
}
private boolean methodParamsMatch(Class<?>[] methodParams, String[] otherMethodParams) {
if (otherMethodParams == null) {
otherMethodParams = new String[0];
}
if (methodParams.length != otherMethodParams.length) {
return false;
}
for (int i = 0; i < methodParams.length; i++) {
if (!methodParams[i].getName().equals(otherMethodParams[i])) {
return false;
}
}
return true;