/
ExecutionEntity.java
1401 lines (1159 loc) · 46.2 KB
/
ExecutionEntity.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
/* 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.
*/
package org.activiti.engine.impl.persistence.entity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.activiti.engine.EngineServices;
import org.activiti.engine.impl.bpmn.parser.BpmnParse;
import org.activiti.engine.impl.bpmn.parser.EventSubscriptionDeclaration;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.db.DbSqlSession;
import org.activiti.engine.impl.db.HasRevision;
import org.activiti.engine.impl.db.PersistentObject;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.jobexecutor.AsyncContinuationJobHandler;
import org.activiti.engine.impl.jobexecutor.TimerDeclarationImpl;
import org.activiti.engine.impl.pvm.PvmActivity;
import org.activiti.engine.impl.pvm.PvmException;
import org.activiti.engine.impl.pvm.PvmExecution;
import org.activiti.engine.impl.pvm.PvmProcessDefinition;
import org.activiti.engine.impl.pvm.PvmProcessElement;
import org.activiti.engine.impl.pvm.PvmProcessInstance;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.delegate.ActivityExecution;
import org.activiti.engine.impl.pvm.delegate.ExecutionListenerExecution;
import org.activiti.engine.impl.pvm.delegate.SignallableActivityBehavior;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.impl.pvm.process.ProcessDefinitionImpl;
import org.activiti.engine.impl.pvm.process.ScopeImpl;
import org.activiti.engine.impl.pvm.process.TransitionImpl;
import org.activiti.engine.impl.pvm.runtime.AtomicOperation;
import org.activiti.engine.impl.pvm.runtime.InterpretableExecution;
import org.activiti.engine.impl.pvm.runtime.OutgoingExecution;
import org.activiti.engine.impl.pvm.runtime.StartingExecution;
import org.activiti.engine.impl.util.BitMaskUtil;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.Job;
import org.activiti.engine.runtime.ProcessInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Tom Baeyens
* @author Daniel Meyer
* @author Falko Menge
* @author Saeid Mirzaei
*/
public class ExecutionEntity extends VariableScopeImpl implements ActivityExecution, ExecutionListenerExecution, Execution, PvmExecution, ProcessInstance, InterpretableExecution, PersistentObject, HasRevision {
private static final long serialVersionUID = 1L;
private static Logger log = LoggerFactory.getLogger(ExecutionEntity.class);
// Persistent refrenced entities state //////////////////////////////////////
protected static final int EVENT_SUBSCRIPTIONS_STATE_BIT = 1;
protected static final int TASKS_STATE_BIT = 2;
protected static final int JOBS_STATE_BIT = 3;
// current position /////////////////////////////////////////////////////////
protected ProcessDefinitionImpl processDefinition;
/** current activity */
protected ActivityImpl activity;
/** current transition. is null when there is no transition being taken. */
protected TransitionImpl transition = null;
/** transition that will be taken. is null when there is no transition being taken. */
protected TransitionImpl transitionBeingTaken = null;
/** the process instance. this is the root of the execution tree.
* the processInstance of a process instance is a self reference. */
protected ExecutionEntity processInstance;
/** the parent execution */
protected ExecutionEntity parent;
/** nested executions representing scopes or concurrent paths */
protected List<ExecutionEntity> executions;
/** super execution, not-null if this execution is part of a subprocess */
protected ExecutionEntity superExecution;
/** reference to a subprocessinstance, not-null if currently subprocess is started from this execution */
protected ExecutionEntity subProcessInstance;
protected StartingExecution startingExecution;
// state/type of execution //////////////////////////////////////////////////
/** indicates if this execution represents an active path of execution.
* Executions are made inactive in the following situations:
* <ul>
* <li>an execution enters a nested scope</li>
* <li>an execution is split up into multiple concurrent executions, then the parent is made inactive.</li>
* <li>an execution has arrived in a parallel gateway or join and that join has not yet activated/fired.</li>
* <li>an execution is ended.</li>
* </ul>*/
protected boolean isActive = true;
protected boolean isScope = true;
protected boolean isConcurrent = false;
protected boolean isEnded = false;
protected boolean isEventScope = false;
// events ///////////////////////////////////////////////////////////////////
protected String eventName;
protected PvmProcessElement eventSource;
protected int executionListenerIndex = 0;
// associated entities /////////////////////////////////////////////////////
// (we cache associated entities here to minimize db queries)
protected List<EventSubscriptionEntity> eventSubscriptions;
protected List<JobEntity> jobs;
protected List<TaskEntity> tasks;
protected List<IdentityLinkEntity> identityLinks;
protected int cachedEntityState;
// cascade deletion ////////////////////////////////////////////////////////
protected boolean deleteRoot;
protected String deleteReason;
// replaced by //////////////////////////////////////////////////////////////
/** when execution structure is pruned during a takeAll, then
* the original execution has to be resolved to the replaced execution.
* @see {@link #takeAll(List, List)} {@link OutgoingExecution} */
protected ExecutionEntity replacedBy;
// atomic operations ////////////////////////////////////////////////////////
/** next operation. process execution is in fact runtime interpretation of the process model.
* each operation is a logical unit of interpretation of the process. so sequentially processing
* the operations drives the interpretation or execution of a process.
* @see AtomicOperation
* @see #performOperation(AtomicOperation) */
protected AtomicOperation nextOperation;
protected boolean isOperating = false;
protected int revision = 1;
protected int suspensionState = SuspensionState.ACTIVE.getStateCode();
/**
* persisted reference to the processDefinition.
*
* @see #processDefinition
* @see #setProcessDefinition(ProcessDefinitionImpl)
* @see #getProcessDefinition()
*/
protected String processDefinitionId;
/**
* persisted reference to the current position in the diagram within the
* {@link #processDefinition}.
*
* @see #activity
* @see #setActivity(ActivityImpl)
* @see #getActivity()
*/
protected String activityId;
/**
* The name of the current activity position
*/
protected String activityName;
/**
* persisted reference to the process instance.
*
* @see #getProcessInstance()
*/
protected String processInstanceId;
/**
* persisted reference to the business key.
*/
protected String businessKey;
/**
* persisted reference to the parent of this execution.
*
* @see #getParent()
* @see #setParent(ExecutionEntity)
*/
protected String parentId;
/**
* persisted reference to the super execution of this execution
*
* @See {@link #getSuperExecution()}
* @see #setSuperExecution(ExecutionEntity)
*/
protected String superExecutionId;
protected boolean forcedUpdate;
protected List<VariableInstanceEntity> queryVariables;
public ExecutionEntity() {
}
public ExecutionEntity(ActivityImpl activityImpl) {
this.startingExecution = new StartingExecution(activityImpl);
}
/** creates a new execution. properties processDefinition, processInstance and activity will be initialized. */
public ExecutionEntity createExecution() {
// create the new child execution
ExecutionEntity createdExecution = newExecution();
// manage the bidirectional parent-child relation
ensureExecutionsInitialized();
executions.add(createdExecution);
createdExecution.setParent(this);
// initialize the new execution
createdExecution.setProcessDefinition(getProcessDefinition());
createdExecution.setProcessInstance(getProcessInstance());
createdExecution.setActivity(getActivity());
if (log.isDebugEnabled()) {
log.debug("Child execution {} created with parent ", createdExecution, this);
}
return createdExecution;
}
public PvmProcessInstance createSubProcessInstance(PvmProcessDefinition processDefinition) {
ExecutionEntity subProcessInstance = newExecution();
// manage bidirectional super-subprocess relation
subProcessInstance.setSuperExecution(this);
this.setSubProcessInstance(subProcessInstance);
// Initialize the new execution
subProcessInstance.setProcessDefinition((ProcessDefinitionImpl) processDefinition);
subProcessInstance.setProcessInstance(subProcessInstance);
Context.getCommandContext().getHistoryManager()
.recordSubProcessInstanceStart(this, subProcessInstance);
return subProcessInstance;
}
protected ExecutionEntity newExecution() {
ExecutionEntity newExecution = new ExecutionEntity();
newExecution.executions = new ArrayList<ExecutionEntity>();
Context
.getCommandContext()
.getDbSqlSession()
.insert(newExecution);
return newExecution;
}
// scopes ///////////////////////////////////////////////////////////////////
@SuppressWarnings("unchecked")
public void initialize() {
log.debug("initializing {}", this);
ScopeImpl scope = getScopeObject();
ensureParentInitialized();
// initialize the lists of referenced objects (prevents db queries)
variableInstances = new HashMap<String, VariableInstanceEntity>();
eventSubscriptions = new ArrayList<EventSubscriptionEntity>();
jobs = new ArrayList<JobEntity>();
tasks = new ArrayList<TaskEntity>();
// Cached entity-state initialized to null, all bits are zore, indicating NO entities present
cachedEntityState = 0;
List<TimerDeclarationImpl> timerDeclarations = (List<TimerDeclarationImpl>) scope.getProperty(BpmnParse.PROPERTYNAME_TIMER_DECLARATION);
if (timerDeclarations!=null) {
for (TimerDeclarationImpl timerDeclaration : timerDeclarations) {
TimerEntity timer = timerDeclaration.prepareTimerEntity(this);
Context
.getCommandContext()
.getJobEntityManager()
.schedule(timer);
}
}
// create event subscriptions for the current scope
List<EventSubscriptionDeclaration> eventSubscriptionDeclarations = (List<EventSubscriptionDeclaration>) scope.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_DECLARATION);
if(eventSubscriptionDeclarations != null) {
for (EventSubscriptionDeclaration eventSubscriptionDeclaration : eventSubscriptionDeclarations) {
if(!eventSubscriptionDeclaration.isStartEvent()) {
EventSubscriptionEntity eventSubscriptionEntity = eventSubscriptionDeclaration.prepareEventSubscriptionEntity(this);
eventSubscriptionEntity.insert();
}
}
}
}
public void start() {
if(startingExecution == null && isProcessInstanceType()) {
startingExecution = new StartingExecution(processDefinition.getInitial());
}
performOperation(AtomicOperation.PROCESS_START);
}
public void destroy() {
log.debug("destroying {}", this);
ensureParentInitialized();
deleteVariablesInstanceForLeavingScope();
setScope(false);
}
/** removes an execution. if there are nested executions, those will be ended recursively.
* if there is a parent, this method removes the bidirectional relation
* between parent and this execution. */
public void end() {
isActive = false;
isEnded = true;
performOperation(AtomicOperation.ACTIVITY_END);
}
// methods that translate to operations /////////////////////////////////////
public void signal(String signalName, Object signalData) {
ensureActivityInitialized();
SignallableActivityBehavior activityBehavior = (SignallableActivityBehavior) activity.getActivityBehavior();
try {
activityBehavior.signal(this, signalName, signalData);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PvmException("couldn't process signal '"+signalName+"' on activity '"+activity.getId()+"': "+e.getMessage(), e);
}
}
public void take(PvmTransition transition) {
if (this.transition!=null) {
throw new PvmException("already taking a transition");
}
if (transition==null) {
throw new PvmException("transition is null");
}
setActivity((ActivityImpl)transition.getSource());
setTransition((TransitionImpl) transition);
performOperation(AtomicOperation.TRANSITION_NOTIFY_LISTENER_END);
}
public void executeActivity(PvmActivity activity) {
setActivity((ActivityImpl) activity);
performOperation(AtomicOperation.ACTIVITY_START);
}
public List<ActivityExecution> findInactiveConcurrentExecutions(PvmActivity activity) {
List<ActivityExecution> inactiveConcurrentExecutionsInActivity = new ArrayList<ActivityExecution>();
List<ActivityExecution> otherConcurrentExecutions = new ArrayList<ActivityExecution>();
if (isConcurrent()) {
List< ? extends ActivityExecution> concurrentExecutions = getParent().getAllChildExecutions();
for (ActivityExecution concurrentExecution: concurrentExecutions) {
if (concurrentExecution.getActivity()==activity) {
if (!concurrentExecution.isActive()) {
inactiveConcurrentExecutionsInActivity.add(concurrentExecution);
}
} else {
otherConcurrentExecutions.add(concurrentExecution);
}
}
} else {
if (!isActive()) {
inactiveConcurrentExecutionsInActivity.add(this);
} else {
otherConcurrentExecutions.add(this);
}
}
if (log.isDebugEnabled()) {
log.debug("inactive concurrent executions in '{}': {}", activity, inactiveConcurrentExecutionsInActivity);
log.debug("other concurrent executions: {}", otherConcurrentExecutions);
}
return inactiveConcurrentExecutionsInActivity;
}
protected List<ExecutionEntity> getAllChildExecutions() {
List<ExecutionEntity> childExecutions = new ArrayList<ExecutionEntity>();
for (ExecutionEntity childExecution : getExecutions()) {
childExecutions.add(childExecution);
childExecutions.addAll(childExecution.getAllChildExecutions());
}
return childExecutions;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void takeAll(List<PvmTransition> transitions, List<ActivityExecution> recyclableExecutions) {
transitions = new ArrayList<PvmTransition>(transitions);
recyclableExecutions = (recyclableExecutions!=null ? new ArrayList<ActivityExecution>(recyclableExecutions) : new ArrayList<ActivityExecution>());
if (recyclableExecutions.size()>1) {
for (ActivityExecution recyclableExecution: recyclableExecutions) {
if (((ExecutionEntity)recyclableExecution).isScope()) {
throw new PvmException("joining scope executions is not allowed");
}
}
}
ExecutionEntity concurrentRoot = ((isConcurrent && !isScope) ? getParent() : this);
List<ExecutionEntity> concurrentActiveExecutions = new ArrayList<ExecutionEntity>();
List<ExecutionEntity> concurrentInActiveExecutions = new ArrayList<ExecutionEntity>();
for (ExecutionEntity execution: concurrentRoot.getExecutions()) {
if (execution.isActive()) {
concurrentActiveExecutions.add(execution);
} else {
concurrentInActiveExecutions.add(execution);
}
}
if (log.isDebugEnabled()) {
log.debug("transitions to take concurrent: {}", transitions);
log.debug("active concurrent executions: {}", concurrentActiveExecutions);
}
if ( (transitions.size()==1)
&& (concurrentActiveExecutions.isEmpty())
&& allExecutionsInSameActivity(concurrentInActiveExecutions)
) {
List<ExecutionEntity> recyclableExecutionImpls = (List) recyclableExecutions;
recyclableExecutions.remove(concurrentRoot);
for (ExecutionEntity prunedExecution: recyclableExecutionImpls) {
// End the pruned executions if necessary.
// Some recyclable executions are inactivated (joined executions)
// Others are already ended (end activities)
if (!prunedExecution.isEnded()) {
log.debug("pruning execution {}", prunedExecution);
prunedExecution.remove();
}
}
log.debug("activating the concurrent root {} as the single path of execution going forward", concurrentRoot);
concurrentRoot.setActive(true);
concurrentRoot.setActivity(activity);
concurrentRoot.setConcurrent(false);
concurrentRoot.take(transitions.get(0));
} else {
List<OutgoingExecution> outgoingExecutions = new ArrayList<OutgoingExecution>();
recyclableExecutions.remove(concurrentRoot);
log.debug("recyclable executions for reuse: {}", recyclableExecutions);
// first create the concurrent executions
while (!transitions.isEmpty()) {
PvmTransition outgoingTransition = transitions.remove(0);
ExecutionEntity outgoingExecution = null;
if (recyclableExecutions.isEmpty()) {
outgoingExecution = concurrentRoot.createExecution();
log.debug("new {} with parent {} created to take transition {}",
outgoingExecution, outgoingExecution.getParent(), outgoingTransition);
} else {
outgoingExecution = (ExecutionEntity) recyclableExecutions.remove(0);
log.debug("recycled {} to take transition {}", outgoingExecution, outgoingTransition);
}
outgoingExecution.setActive(true);
outgoingExecution.setScope(false);
outgoingExecution.setConcurrent(true);
outgoingExecution.setTransitionBeingTaken((TransitionImpl) outgoingTransition);
outgoingExecutions.add(new OutgoingExecution(outgoingExecution, outgoingTransition, true));
}
// prune the executions that are not recycled
for (ActivityExecution prunedExecution: recyclableExecutions) {
log.debug("pruning execution {}", prunedExecution);
prunedExecution.end();
}
// then launch all the concurrent executions
for (OutgoingExecution outgoingExecution: outgoingExecutions) {
outgoingExecution.take();
}
}
}
protected boolean allExecutionsInSameActivity(List<ExecutionEntity> executions) {
if (executions.size() > 1) {
String activityId = executions.get(0).getActivityId();
for (ExecutionEntity execution : executions) {
String otherActivityId = execution.getActivityId();
if (!execution.isEnded) {
if ( (activityId == null && otherActivityId != null)
|| (activityId != null && otherActivityId == null)
|| (activityId != null && otherActivityId!= null && !otherActivityId.equals(activityId))) {
return false;
}
}
}
}
return true;
}
public void performOperation(AtomicOperation executionOperation) {
if(executionOperation.isAsync(this)) {
scheduleAtomicOperationAsync(executionOperation);
} else {
performOperationSync(executionOperation);
}
}
protected void performOperationSync(AtomicOperation executionOperation) {
Context
.getCommandContext()
.performOperation(executionOperation, this);
}
protected void scheduleAtomicOperationAsync(AtomicOperation executionOperation) {
MessageEntity message = new MessageEntity();
message.setExecution(this);
message.setExclusive(getActivity().isExclusive());
message.setJobHandlerType(AsyncContinuationJobHandler.TYPE);
// At the moment, only AtomicOperationTransitionCreateScope can be performed asynchronously,
// so there is no need to pass it to the handler
Context
.getCommandContext()
.getJobEntityManager()
.send(message);
}
public boolean isActive(String activityId) {
return findExecution(activityId)!=null;
}
public void inactivate() {
this.isActive = false;
}
// executions ///////////////////////////////////////////////////////////////
/** ensures initialization and returns the non-null executions list */
public List<ExecutionEntity> getExecutions() {
ensureExecutionsInitialized();
return executions;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
protected void ensureExecutionsInitialized() {
if (executions==null) {
this.executions = (List) Context
.getCommandContext()
.getExecutionEntityManager()
.findChildExecutionsByParentExecutionId(id);
}
}
public void setExecutions(List<ExecutionEntity> executions) {
this.executions = executions;
}
/** searches for an execution positioned in the given activity */
public ExecutionEntity findExecution(String activityId) {
if ( (getActivity()!=null)
&& (getActivity().getId().equals(activityId))
) {
return this;
}
for (ExecutionEntity nestedExecution : getExecutions()) {
ExecutionEntity result = nestedExecution.findExecution(activityId);
if (result != null) {
return result;
}
}
return null;
}
public List<String> findActiveActivityIds() {
List<String> activeActivityIds = new ArrayList<String>();
collectActiveActivityIds(activeActivityIds);
return activeActivityIds;
}
protected void collectActiveActivityIds(List<String> activeActivityIds) {
ensureActivityInitialized();
if (isActive && activity!=null) {
activeActivityIds.add(activity.getId());
}
ensureExecutionsInitialized();
for (ExecutionEntity execution: executions) {
execution.collectActiveActivityIds(activeActivityIds);
}
}
// bussiness key ////////////////////////////////////////////////////////////
public String getBusinessKey() {
return businessKey;
}
public void setBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
public String getProcessBusinessKey() {
return getProcessInstance().getBusinessKey();
}
// process definition ///////////////////////////////////////////////////////
/** ensures initialization and returns the process definition. */
public ProcessDefinitionImpl getProcessDefinition() {
ensureProcessDefinitionInitialized();
return processDefinition;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
/** for setting the process definition, this setter must be used as subclasses can override */
protected void ensureProcessDefinitionInitialized() {
if ((processDefinition == null) && (processDefinitionId != null)) {
ProcessDefinitionEntity deployedProcessDefinition = Context
.getProcessEngineConfiguration()
.getDeploymentManager()
.findDeployedProcessDefinitionById(processDefinitionId);
setProcessDefinition(deployedProcessDefinition);
}
}
public void setProcessDefinition(ProcessDefinitionImpl processDefinition) {
this.processDefinition = processDefinition;
this.processDefinitionId = processDefinition.getId();
}
// process instance /////////////////////////////////////////////////////////
/** ensures initialization and returns the process instance. */
public ExecutionEntity getProcessInstance() {
ensureProcessInstanceInitialized();
return processInstance;
}
protected void ensureProcessInstanceInitialized() {
if ((processInstance == null) && (processInstanceId != null)) {
processInstance = Context
.getCommandContext()
.getExecutionEntityManager()
.findExecutionById(processInstanceId);
}
}
public void setProcessInstance(InterpretableExecution processInstance) {
this.processInstance = (ExecutionEntity) processInstance;
if (processInstance != null) {
this.processInstanceId = this.processInstance.getId();
}
}
public boolean isProcessInstanceType() {
return parentId == null;
}
// activity /////////////////////////////////////////////////////////////////
/** ensures initialization and returns the activity */
public ActivityImpl getActivity() {
ensureActivityInitialized();
return activity;
}
/** must be called before the activity member field or getActivity() is called */
protected void ensureActivityInitialized() {
if ((activity == null) && (activityId != null)) {
activity = getProcessDefinition().findActivity(activityId);
}
}
public void setActivity(ActivityImpl activity) {
this.activity = activity;
if (activity != null) {
this.activityId = activity.getId();
this.activityName = (String) activity.getProperty("name");
} else {
this.activityId = null;
this.activityName = null;
}
}
// parent ///////////////////////////////////////////////////////////////////
/** ensures initialization and returns the parent */
public ExecutionEntity getParent() {
ensureParentInitialized();
return parent;
}
protected void ensureParentInitialized() {
if (parent == null && parentId != null) {
parent = Context
.getCommandContext()
.getExecutionEntityManager()
.findExecutionById(parentId);
}
}
public void setParent(InterpretableExecution parent) {
this.parent = (ExecutionEntity) parent;
if (parent != null) {
this.parentId = ((ExecutionEntity)parent).getId();
} else {
this.parentId = null;
}
}
// super- and subprocess executions /////////////////////////////////////////
public String getSuperExecutionId() {
return superExecutionId;
}
public ExecutionEntity getSuperExecution() {
ensureSuperExecutionInitialized();
return superExecution;
}
public void setSuperExecution(ExecutionEntity superExecution) {
this.superExecution = superExecution;
if (superExecution != null) {
superExecution.setSubProcessInstance(null);
}
if (superExecution != null) {
this.superExecutionId = ((ExecutionEntity)superExecution).getId();
} else {
this.superExecutionId = null;
}
}
protected void ensureSuperExecutionInitialized() {
if (superExecution == null && superExecutionId != null) {
superExecution = Context
.getCommandContext()
.getExecutionEntityManager()
.findExecutionById(superExecutionId);
}
}
public ExecutionEntity getSubProcessInstance() {
ensureSubProcessInstanceInitialized();
return subProcessInstance;
}
public void setSubProcessInstance(InterpretableExecution subProcessInstance) {
this.subProcessInstance = (ExecutionEntity) subProcessInstance;
}
protected void ensureSubProcessInstanceInitialized() {
if (subProcessInstance == null) {
subProcessInstance = Context
.getCommandContext()
.getExecutionEntityManager()
.findSubProcessInstanceBySuperExecutionId(id);
}
}
// scopes ///////////////////////////////////////////////////////////////////
protected ScopeImpl getScopeObject() {
ScopeImpl scope = null;
if (isProcessInstanceType()) {
scope = getProcessDefinition();
} else {
scope = getActivity();
}
return scope;
}
public boolean isScope() {
return isScope;
}
public void setScope(boolean isScope) {
this.isScope = isScope;
}
// customized persistence behaviour /////////////////////////////////////////
public void remove() {
ensureParentInitialized();
if (parent!=null) {
parent.ensureExecutionsInitialized();
parent.executions.remove(this);
}
// delete all the variable instances
ensureVariableInstancesInitialized();
deleteVariablesInstanceForLeavingScope();
// delete all the tasks
removeTasks(null);
// remove all jobs
removeJobs();
// remove all event subscriptions for this scope, if the scope has event subscriptions:
removeEventSubscriptions();
// remove event scopes:
removeEventScopes();
// remove identity links
removeIdentityLinks();
// finally delete this execution
Context.getCommandContext()
.getDbSqlSession()
.delete(this);
}
public void destroyScope(String reason) {
if(log.isDebugEnabled()) {
log.debug("performing destroy scope behavior for execution {}", this);
}
// remove all child executions and sub process instances:
List<InterpretableExecution> executions = new ArrayList<InterpretableExecution>(getExecutions());
for (InterpretableExecution childExecution : executions) {
if (childExecution.getSubProcessInstance()!=null) {
childExecution.getSubProcessInstance().deleteCascade(reason);
}
childExecution.deleteCascade(reason);
}
removeTasks(reason);
removeJobs();
// Daniel thought this would be needed, but it seems not: removeEventSubscriptions();
}
private void removeEventScopes() {
List<InterpretableExecution> childExecutions = new ArrayList<InterpretableExecution>(getExecutions());
for (InterpretableExecution childExecution : childExecutions) {
if(childExecution.isEventScope()) {
log.debug("removing eventScope {}", childExecution);
childExecution.destroy();
childExecution.remove();
}
}
}
private void removeEventSubscriptions() {
for (EventSubscriptionEntity eventSubscription : getEventSubscriptions()) {
if (replacedBy != null) {
eventSubscription.setExecution((ExecutionEntity) replacedBy);
} else {
eventSubscription.delete();
}
}
}
private void removeJobs() {
for (Job job: getJobs()) {
if (replacedBy!=null) {
((JobEntity)job).setExecution((ExecutionEntity) replacedBy);
} else {
((JobEntity)job).delete();
}
}
}
private void removeTasks(String reason) {
if(reason == null) {
reason = TaskEntity.DELETE_REASON_DELETED;
}
for (TaskEntity task : getTasks()) {
if (replacedBy!=null) {
if(task.getExecution() == null || task.getExecution() != replacedBy) {
// All tasks should have been moved when "replacedBy" has been set. Just in case tasks where added,
// wo do an additional check here and move it
task.setExecution(replacedBy);
this.replacedBy.addTask(task);
}
} else {
Context.getCommandContext()
.getTaskEntityManager()
.deleteTask(task, reason, false);
}
}
}
public ExecutionEntity getReplacedBy() {
return replacedBy;
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public void setReplacedBy(InterpretableExecution replacedBy) {
this.replacedBy = (ExecutionEntity) replacedBy;
CommandContext commandContext = Context.getCommandContext();
DbSqlSession dbSqlSession = commandContext.getDbSqlSession();
// update the related tasks
for (TaskEntity task: getTasks()) {
task.setExecutionId(replacedBy.getId());
task.setExecution(this.replacedBy);
// update the related local task variables
List<VariableInstanceEntity> variables = (List) commandContext
.getVariableInstanceEntityManager()
.findVariableInstancesByTaskId(task.getId());
for (VariableInstanceEntity variable : variables) {
variable.setExecution(this.replacedBy);
}
this.replacedBy.addTask(task);
}
// All tasks have been moved to 'replacedBy', safe to clear the list
this.tasks.clear();
tasks = dbSqlSession.findInCache(TaskEntity.class);
for (TaskEntity task: tasks) {
if (id.equals(task.getExecutionId())) {
task.setExecutionId(replacedBy.getId());
}
}
// update the related jobs
List<JobEntity> jobs = getJobs();
for (JobEntity job: jobs) {
job.setExecution((ExecutionEntity) replacedBy);
}
// update the related event subscriptions
List<EventSubscriptionEntity> eventSubscriptions = getEventSubscriptions();
for (EventSubscriptionEntity subscriptionEntity: eventSubscriptions) {
subscriptionEntity.setExecution((ExecutionEntity) replacedBy);
}
// update the related process variables
List<VariableInstanceEntity> variables = (List) commandContext
.getVariableInstanceEntityManager()
.findVariableInstancesByExecutionId(id);
for (VariableInstanceEntity variable: variables) {
variable.setExecutionId(replacedBy.getId());
}
variables = dbSqlSession.findInCache(VariableInstanceEntity.class);
for (VariableInstanceEntity variable: variables) {
if (id.equals(variable.getExecutionId())) {
variable.setExecutionId(replacedBy.getId());
}
}
commandContext.getHistoryManager()
.recordExecutionReplacedBy(this, replacedBy);
}
// variables ////////////////////////////////////////////////////////////////
@Override
protected void initializeVariableInstanceBackPointer(VariableInstanceEntity variableInstance) {
variableInstance.setProcessInstanceId(processInstanceId);
variableInstance.setExecutionId(id);
}
@Override
protected List<VariableInstanceEntity> loadVariableInstances() {
return Context
.getCommandContext()
.getVariableInstanceEntityManager()
.findVariableInstancesByExecutionId(id);