ludc
2025-01-16 986aa62ed00bee39363bab41b4eeb8259d446efd
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
/*
 * JBoss, Home of Professional Open Source
 * Copyright 2005, JBoss Inc., and individual contributors as indicated
 * by the @authors tag. See the copyright.txt 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.jbpm.pvm.internal.model;
 
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
import java.util.StringTokenizer;
 
import org.jbpm.api.Execution;
import org.jbpm.api.JbpmException;
import org.jbpm.api.activity.ActivityExecution;
import org.jbpm.api.job.Job;
import org.jbpm.api.job.Timer;
import org.jbpm.api.listener.EventListenerExecution;
import org.jbpm.api.model.Event;
import org.jbpm.api.model.OpenExecution;
import org.jbpm.api.task.Assignable;
import org.jbpm.api.task.AssignmentHandler;
import org.jbpm.internal.log.Log;
import org.jbpm.pvm.internal.client.ClientProcessDefinition;
import org.jbpm.pvm.internal.client.ClientProcessInstance;
import org.jbpm.pvm.internal.env.Context;
import org.jbpm.pvm.internal.env.EnvironmentImpl;
import org.jbpm.pvm.internal.env.ExecutionContext;
import org.jbpm.pvm.internal.history.HistoryEvent;
import org.jbpm.pvm.internal.history.events.ActivityEnd;
import org.jbpm.pvm.internal.history.events.ActivityStart;
import org.jbpm.pvm.internal.history.events.AutomaticEnd;
import org.jbpm.pvm.internal.history.events.DecisionEnd;
import org.jbpm.pvm.internal.history.events.ProcessInstanceCreate;
import org.jbpm.pvm.internal.history.events.ProcessInstanceEnd;
import org.jbpm.pvm.internal.id.DbidGenerator;
import org.jbpm.pvm.internal.id.IdComposer;
import org.jbpm.pvm.internal.job.JobImpl;
import org.jbpm.pvm.internal.job.MessageImpl;
import org.jbpm.pvm.internal.model.op.AtomicOperation;
import org.jbpm.pvm.internal.model.op.MoveToChildActivity;
import org.jbpm.pvm.internal.model.op.Signal;
import org.jbpm.pvm.internal.script.ScriptManager;
import org.jbpm.pvm.internal.session.DbSession;
import org.jbpm.pvm.internal.session.MessageSession;
import org.jbpm.pvm.internal.session.RepositorySession;
import org.jbpm.pvm.internal.session.TimerSession;
import org.jbpm.pvm.internal.task.AssignableDefinitionImpl;
import org.jbpm.pvm.internal.task.SwimlaneDefinitionImpl;
import org.jbpm.pvm.internal.task.SwimlaneImpl;
import org.jbpm.pvm.internal.type.Variable;
import org.jbpm.pvm.internal.util.EqualsUtil;
import org.jbpm.pvm.internal.util.Priority;
import org.jbpm.pvm.internal.wire.usercode.UserCodeReference;
 
/**
 * @author Tom Baeyens
 */
public class ExecutionImpl extends ScopeInstanceImpl 
                           implements ClientProcessInstance,
                                      ActivityExecution, 
                                      EventListenerExecution, 
                                      Serializable {
 
  private static final long serialVersionUID = 1L;
 
  private static final Log log = Log.getLog(ExecutionImpl.class.getName());
  
  /** an optional name for this execution.  can be used to 
   * differentiate concurrent paths of execution like e.g. 
   * the 'shipping' and 'billing' paths. */
  protected String name;
 
  /** a key for this execution. typically this is an externally provided reference 
   * that is unique within the scope of the process definition.  */
  protected String key;
 
  /** a unique id for this execution. */
  protected String id;
 
  /** are concurrent executions that related to this execution. */
  protected Collection<ExecutionImpl> executions = new ArrayList<ExecutionImpl>();
 
  /** the parent child relation of executions is convenient for some forms of
   * concurrency. */
  protected ExecutionImpl parent = null;
  protected ExecutionImpl processInstance;
  
  /** the super process link in case this is a sub process execution */  
  protected ExecutionImpl superProcessExecution;
  
  /** the sub process link in case of sub process execution */
  protected ExecutionImpl subProcessInstance;
 
  /** swimlanes */
  protected Map<String, SwimlaneImpl> swimlanes = new HashMap<String, SwimlaneImpl>();
 
  /** reference to the current activity instance history record */
  protected Long historyActivityInstanceDbid;
  
  /** start time of the activity for history purposes (not persisted) */
  protected Date historyActivityStart;
 
  protected int priority = Priority.NORMAL;
 
  protected Map<String, Variable> systemVariables = new HashMap<String, Variable>();
 
  // persistent indicators of the current position ////////////////////////////
  
  /** persistent process definition reference */
  protected String processDefinitionId;
  
  /** persistent activity reference */
  protected String activityName;
 
  // transient cached indicators of the current position //////////////////////
 
  /** transient cached process definition.  persistence is managed in {@link #processDefinitionId} */
  protected ProcessDefinitionImpl processDefinition;
  
  /** transient cached current activity pointer.  persistence is managed in {@link #activityName} */
  private ActivityImpl activity;
 
  /** transition is not to be made persistable by default */
  protected TransitionImpl transition;
 
  protected EventImpl event;
 
  protected AtomicOperation eventCompletedOperation;
 
  protected int eventListenerIndex;
 
  protected ObservableElementImpl eventSource;
 
  // cached named executions //////////////////////////////////////////////////
  
  /** caches the child executions by execution name.  This member might be
   * null and is only created from the executions in case its needed.  Note
   * that not all executions are forced to have a name and duplicates are allowed.
   * In case the {@link #executions} change, the executionsMap can be nulled or
   * also updated (but a check needs to be added whether it exists). */
  protected transient Map<String, Execution> executionsMap = null;
 
  /** the queue of atomic operations to be performed for this execution. */
  protected Queue<AtomicOperation> atomicOperations;
 
  public enum Propagation {
    UNSPECIFIED, WAIT, EXPLICIT
  }
  protected Propagation propagation = null;
 
  // construction /////////////////////////////////////////////////////////////
  
  public void initializeProcessInstance(ProcessDefinitionImpl processDefinition, String key) {
    setProcessDefinition(processDefinition);
    setActivity ( (ActivityImpl) processDefinition.getInitial() );
    this.processInstance = this;
    this.state = STATE_CREATED;
    this.key = key;
 
    save();
    composeIds();
    
    HistoryEvent.fire(new ProcessInstanceCreate(), this);
  }
 
  protected void save() {
    this.dbid = DbidGenerator.getDbidGenerator().getNextId();
    DbSession dbSession = EnvironmentImpl.getFromCurrent(DbSession.class, false);
    if (dbSession!=null) {
      dbSession.save(this);
    }
  }
 
  protected void composeIds() {
    this.id = IdComposer.getIdComposer().createId(processDefinition, parent, this);
  }
 
 
  // execution method : start /////////////////////////////////////////////////
 
  public void start() {
    if (!STATE_CREATED.equals(state)) {
      throw new JbpmException(toString()+" is already begun: "+state);
    }
    this.state = STATE_ACTIVE_ROOT;
    ExecutionImpl scopedExecution = initializeScopes();
    
    fire(Event.START, getProcessDefinition());
    if (getActivity()!=null) {
      scopedExecution.performAtomicOperation(AtomicOperation.EXECUTE_ACTIVITY);
    }
  }
 
  protected ExecutionImpl initializeScopes() {
    LinkedList<ActivityImpl> enteredActivities = new LinkedList<ActivityImpl>();
 
    ActivityImpl initial = getProcessDefinition().getInitial();
    ExecutionImpl scopedExecution = null;
    
    if (initial!=null) {
      enteredActivities.add(initial);
      ActivityImpl parentActivity = initial.getParentActivity();
      while (parentActivity!=null) {
        enteredActivities.addFirst(parentActivity);
        parentActivity = parentActivity.getParentActivity();
      }
      
      scopedExecution = this;
 
      initializeVariables(getProcessDefinition(), this);
      initializeTimers(getProcessDefinition());
      
      for (ActivityImpl enteredActivity: enteredActivities) {
        if (enteredActivity.isLocalScope()) {
          scopedExecution.setActivity(enteredActivity);
          scopedExecution = scopedExecution.createScope(enteredActivity);
        }
      }
      
      scopedExecution.setActivity(initial);
    }
    return scopedExecution;
  }
 
  public ExecutionImpl createScope(ScopeElementImpl scope) {
    ExecutionImpl child = createExecution(scope.getName());
    
    setState(STATE_INACTIVE_SCOPE);
    child.setState(STATE_ACTIVE_ROOT);
    
    // copy the current state from the child execution to the parent execution
    child.setActivity(getActivity());
    child.setTransition(getTransition());
    child.setPropagation(getPropagation());
    
    child.initializeVariables(scope, this);
    child.initializeTimers(scope);
    
    return child;
  }
  
  public ExecutionImpl destroyScope(CompositeElementImpl scope) {
    destroyTimers(scope);
    
    // copy the current state from the child execution to the parent execution
    parent.setActivity(getActivity());
    parent.setTransition(getTransition());
    parent.setPropagation(getPropagation());
    
    ExecutionImpl parentsParent = parent.getParent();
    if ( (parentsParent!=null)
         && (STATE_INACTIVE_CONCURRENT_ROOT.equals(parentsParent.getState()))
       ) {
      parent.setState(STATE_ACTIVE_CONCURRENT);
    } else {
      parent.setState(STATE_ACTIVE_ROOT);
    }
    
    // capture the parent execution cause the 
    // subsequent invocation of end() will set the parent to null
    ExecutionImpl parent = this.parent;
    
    end();
 
    return parent;
  }
  
  
  protected void destroyTimers(CompositeElementImpl scope) {
    TimerSession timerSession = EnvironmentImpl.getFromCurrent(TimerSession.class, false);
    if (timerSession!=null) {
      log.debug("destroying timers of "+this);
      List<Timer> timers = timerSession.findTimersByExecution(this);
      for (Timer timer: timers) {
        
        Job job = EnvironmentImpl.getFromCurrent(JobImpl.class, false);
        if (timer!=job) {
          timerSession.cancel(timer);
        }
      }
    }
  }
 
  
  // basic object methods /////////////////////////////////////////////////////
 
  public String toString() {
    if (getId()!=null) {
      return "execution["+id+"]";
    }
    if (parent==null) {
      return "process-instance";
    }
    return "execution";
  }
  
  // execution method : end ///////////////////////////////////////////////////
 
  public void end() {
    end(Execution.STATE_ENDED);
  }
 
  public void end(String state) {
    if (state==null) {
      throw new JbpmException("state is null");
    }
 
    if (state.equals(STATE_CREATED)
        || state.equals(STATE_ACTIVE_ROOT)
        || state.equals(STATE_ACTIVE_CONCURRENT)
        || state.equals(STATE_INACTIVE_CONCURRENT_ROOT)
        || state.equals(STATE_INACTIVE_SCOPE)
        || state.equals(STATE_INACTIVE_JOIN)
        || state.equals(STATE_SUSPENDED)
        || state.equals(STATE_ASYNC)) {
      throw new JbpmException("invalid end state: "+state);
    }
      
    if (log.isDebugEnabled()) {
      if (state==STATE_ENDED) {
        log.debug(toString()+" ends");
      } else {
        log.debug(toString()+" ends with state "+state);
      }
    }
    
    // end all child executions
   // making a copy of the executions to prevent ConcurrentMoidificationException
    List<ExecutionImpl> executionsToEnd = new ArrayList<ExecutionImpl>(executions);
    for (ExecutionImpl child: executionsToEnd) {
      child.end(state);
    }
    
    setState(state);
 
    this.propagation = Propagation.EXPLICIT;
    
    DbSession dbSession = EnvironmentImpl.getFromCurrent(DbSession.class, false);
 
    if (parent!=null) {
      parent.removeExecution(this);
      if (dbSession!=null) {
        dbSession.delete(this);
      }
      
    } else { // this is a process instance
      HistoryEvent.fire(new ProcessInstanceEnd(), this);
      fire(Event.END, getProcessDefinition());
 
      if (superProcessExecution!=null) {
        log.trace(toString()+" signals super process execution");
        superProcessExecution.signal();
 
      } else if (dbSession!=null) {
        dbSession.deleteProcessInstance(id, false);
      }
    }
  }
  
  public void end(OpenExecution executionToEnd) {
    ((ExecutionImpl)executionToEnd).end();
  }
 
  public void end(OpenExecution executionToEnd, String state) {
    ((ExecutionImpl)executionToEnd).end(state);
  }
 
 
  // execution method : signal ////////////////////////////////////////////////
 
  public void signal() {
    signal(null, (Map<String,?>)null);
  }
 
  public void signal(String signal) {
    signal(signal, (Map<String,?>)null);
  }
  
  public void signal(Map<String, ?> parameters) {
    signal(null, parameters);
  }
 
  public void signal(String signal, Map<String, ?> parameters) {
    checkActive();
    if (getProcessDefinition().isSuspended()) {
      throw new JbpmException("process definition "+getProcessDefinition().getId()+" is suspended");
    }
    propagation = Propagation.EXPLICIT;
    if (getActivity()!=null) {
      performAtomicOperation(new Signal(signal, parameters));
    } else if (transition!=null) {
      performAtomicOperation(AtomicOperation.TRANSITION_START_ACTIVITY);
    } else {
      throw new JbpmException("execution is not in a activity or in a transition");
    }
  }
  
  public void signal(Execution execution) {
    ((ExecutionImpl)execution).signal(null, (Map<String,?>)null);
  }
 
  public void signal(String signalName, Execution execution) {
    ((ExecutionImpl)execution).signal(signalName, (Map<String,?>)null);
  }
 
  public void signal(Map<String, ?> parameters, Execution execution) {
    ((ExecutionImpl)execution).signal(null, parameters);
  }
 
  public void signal(String signalName, Map<String, ?> parameters, Execution execution) {
    ((ExecutionImpl)execution).signal(signalName, parameters);
  }
 
  // execution method : take ////////////////////////////////////////////////
  
  /** @see Execution#takeDefaultTransition() */
  public void takeDefaultTransition() {
    TransitionImpl defaultTransition = getActivity().getDefaultOutgoingTransition();
    if (defaultTransition==null) {
      throw new JbpmException("there is no default transition in "+getActivity());
    }
    take(defaultTransition);
  }
 
  /** @see Execution#take(String) */
  public void take(String transitionName) {
    if (getActivity()==null) {
      throw new JbpmException(toString()+" is not positioned in activity");
    }
    TransitionImpl transition = findTransition(transitionName);
    if (transition==null) {
      throw new JbpmException("there is no transition "+transitionName+" in "+getActivity());
    }
    take(transition);
  }
 
  /** @see Execution#takeDefaultTransition() */
  public void take(Transition transition) {
    checkActive();
 
    setPropagation(Propagation.EXPLICIT);
 
    setTransition((TransitionImpl) transition);
    
    fire(Event.END, getActivity(), AtomicOperation.TRANSITION_END_ACTIVITY);
  }
 
  public void take(Transition transition, Execution execution) {
    ((ExecutionImpl)execution).take(transition);
  }
 
  // execution method : execute ///////////////////////////////////////////////
 
  /** @see Execution#execute(String) */
  public void execute(String activityName) {
    if (getActivity()==null) {
      throw new JbpmException("activity is null");
    }
    Activity nestedActivity = getActivity().getActivity(activityName);
    if (nestedActivity==null) {
      throw new JbpmException("activity "+activityName+" doesn't exist in "+getActivity());
    }
    execute(nestedActivity);
  }
  
  /** @see Execution#execute(Activity) */
  public void execute(Activity activity) {
    if (activity==null) {
      throw new JbpmException("activity is null");
    }
    checkActive();
    
    this.propagation = Propagation.EXPLICIT;
    performAtomicOperation(new MoveToChildActivity((ActivityImpl) activity));
  }
  
  // execution method : waitForSignal /////////////////////////////////////////
  
  public void waitForSignal() {
    propagation = Propagation.WAIT;
  }
  
  // execution method : proceed ///////////////////////////////////////////////
 
  public void proceed() {
    checkActive();
 
    // in graph based processDefinition languages we assume that a
    // default transition is available
    TransitionImpl defaultTransition = findDefaultTransition();
    if (defaultTransition!=null) {
      take(defaultTransition);
      
    // in block structured processDefinition languages we assume that 
    // there is no default transition and that there is a 
    // parent activity of the current activity
    } else {
      ActivityImpl parentActivity = getActivity().getParentActivity();
 
      // if there is a parent activity
      if (parentActivity!=null) {
        // propagate to the parent
        performAtomicOperation(AtomicOperation.PROPAGATE_TO_PARENT);
        
      }  else {
        // When we don't know how to proceed, i don't know if it's best to 
        // throw new PvmException("don't know how to proceed");
        // or to end the execution.  Because of convenience for testing, 
        // I opted to end the execution.
        end();
      }
    }
  }
 
  public void setActivity(Activity activity, Execution execution) {
    ((ExecutionImpl)execution).setActivity(activity);
  }
 
  public void setActivity(Activity activity) {
    setActivity((ActivityImpl) activity);
  }
 
  // events ///////////////////////////////////////////////////////////////////
  
  public void fire(String eventName, ObservableElement eventSource) {
    fire(eventName, (ObservableElementImpl) eventSource, null);
  }
 
  public void fire(String eventName, ObservableElementImpl observableElement, AtomicOperation eventCompletedOperation) {
    EventImpl event = findEvent(observableElement, eventName);
    if (event!=null) {
      setEvent(event);
      setEventSource(observableElement);
      setEventListenerIndex(0);
      setEventCompletedOperation(eventCompletedOperation);
      performAtomicOperation(AtomicOperation.EXECUTE_EVENT_LISTENER);
    } else {
      if (eventCompletedOperation!=null) {
        performAtomicOperationSync(eventCompletedOperation);
      }
    }
  }
  
  public static EventImpl findEvent(ObservableElementImpl observableElement, String eventName) {
    if (observableElement==null) {
      return null;
    }
    
    EventImpl event = observableElement.getEvent(eventName);
    if (event!=null) {
      return event;
    }
    
    return findEvent(observableElement.getParent(), eventName);
  }
 
  // execution : internal methods /////////////////////////////////////////////
 
  public void moveTo(ActivityImpl destination) {
    // move the execution to the destination
    setActivity(destination);
    transition = null;
  }
 
  public ExecutionImpl startActivity(ActivityImpl activity) {
    ExecutionImpl propagatingExecution = this;
    if (activity.isLocalScope()) {
      propagatingExecution = createScope(activity);
    }
    fire(Event.START, activity);
    return propagatingExecution;
  }
 
  public ExecutionImpl endActivity(ActivityImpl activity) {
    ExecutionImpl propagatingExecution = this;
    fire(Event.END, activity);
    if (activity.isLocalScope()) {
      propagatingExecution = destroyScope(activity);
    }
    return propagatingExecution;
  }
 
  // asynchronous continuations ////////////////////////////////////////////////  
 
  public synchronized void performAtomicOperation(AtomicOperation operation) {
    if (operation.isAsync(this)) {
      sendContinuationMessage(operation);
    } else {
      performAtomicOperationSync(operation);
    }
  }
  
  public void sendContinuationMessage(AtomicOperation operation) {
    EnvironmentImpl environment = EnvironmentImpl.getCurrent();
    MessageSession messageSession = environment.get(MessageSession.class);
    if (messageSession==null) {
      throw new JbpmException("no message-session configured to send asynchronous continuation message");
    }
    MessageImpl<?> asyncMessage = operation.createAsyncMessage(this);
    setState(Execution.STATE_ASYNC);
    messageSession.send(asyncMessage);
  }
 
  public void performAtomicOperationSync(AtomicOperation operation) {
    if (atomicOperations==null) {
      
      // initialise the fifo queue of atomic operations
      atomicOperations = new LinkedList<AtomicOperation>();
      atomicOperations.offer(operation);
      
      ExecutionContext originalExecutionContext = null; 
      ExecutionContext executionContext = null;
      EnvironmentImpl environment = EnvironmentImpl.getCurrent();
      if (environment!=null) {
        originalExecutionContext = (ExecutionContext) environment.getContext(Context.CONTEXTNAME_EXECUTION);
        if ( (originalExecutionContext!=null)
             && (originalExecutionContext.getExecution()==this)
           ) {
          originalExecutionContext = null;
        } else {
          executionContext = new ExecutionContext(this);
          environment.setContext(executionContext);
        }
      }
      
      try {
        while (! atomicOperations.isEmpty()) {
          AtomicOperation atomicOperation = atomicOperations.poll();
          atomicOperation.perform(this);
        }
 
      } catch (RuntimeException e ) {
        throw e;
      } finally {
        atomicOperations = null;
        
        if (executionContext!=null) {
          environment.removeContext(executionContext);
        }
        if (originalExecutionContext!=null) {
          environment.setContext(originalExecutionContext);
        }
      }
    } else {
      atomicOperations.offer(operation);
    }
  }
 
  public void handleException(ObservableElementImpl observableElement,
                              EventImpl event,
                              EventListenerReference eventListenerReference,
                              Exception exception,
                              String rethrowMessage) {
    
    List<ProcessElementImpl> processElements = new ArrayList<ProcessElementImpl>();
    if (eventListenerReference!=null) {
      processElements.add(eventListenerReference);
    }
    if (event!=null) {
      processElements.add(event);
    }
    while (observableElement!=null) {
      processElements.add(observableElement);
      observableElement = observableElement.getParent();
    }
    
    for (ProcessElementImpl processElement: processElements) {
      List<ExceptionHandlerImpl> exceptionHandlers = processElement.getExceptionHandlers();
      if (exceptionHandlers!=null) {
        for (ExceptionHandlerImpl exceptionHandler: exceptionHandlers) {
          if (exceptionHandler.matches(exception)) {
            try {
              exceptionHandler.handle(this, exception);
              return;
            } catch (Exception rethrowException) {
              if (!exceptionHandler.isRethrowMasked()) {
                exception = rethrowException;
              }
            }
            break;
          }
        }
      }
    }
 
    log.trace("rethrowing exception cause no exception handler for "+exception);
    ExceptionHandlerImpl.rethrow(exception, rethrowMessage+": "+exception.getMessage());
  }
  
  
  // tasks ////////////////////////////////////////////////////////////////////
 
  /** tasks and swimlane assignment.
   * SwimlaneDefinitionImpl is base class for TaskDefinitionImpl.
   * Both Task and Swimlane implement Assignable. */
  public void initializeAssignments(AssignableDefinitionImpl assignableDefinition, Assignable assignable) {
    String assigneeExpression = assignableDefinition.getAssigneeExpression();
    if (assigneeExpression!=null) {
      String assignee = resolveAssignmentExpression(assigneeExpression, 
                                                    assignableDefinition.getAssigneeExpressionLanguage());
      assignable.setAssignee(assignee);
      
      if (log.isTraceEnabled()) log.trace("task "+name+" assigned to "+assignee+" using expression "+assigneeExpression);
    }
    
    String candidateUsersExpression = assignableDefinition.getCandidateUsersExpression();
    if (candidateUsersExpression!=null) {
      String candidateUsers = 
          resolveAssignmentExpression(candidateUsersExpression, 
                                      assignableDefinition.getCandidateUsersExpressionLanguage());
      StringTokenizer tokenizer = new StringTokenizer(candidateUsers, ",");
      while (tokenizer.hasMoreTokens()) {
        String candidateUser = tokenizer.nextToken().trim();
        assignable.addCandidateUser(candidateUser);
      }
    }
  
    String candidateGroupsExpression = assignableDefinition.getCandidateGroupsExpression();
    if (candidateGroupsExpression!=null) {
      String candidateGroups = 
            resolveAssignmentExpression(candidateGroupsExpression, 
                                        assignableDefinition.getCandidateGroupsExpressionLanguage());
      StringTokenizer tokenizer = new StringTokenizer(candidateGroups, ",");
      while (tokenizer.hasMoreTokens()) {
        String candidateGroup = tokenizer.nextToken();
        assignable.addCandidateGroup(candidateGroup);
      }
    }
    
    UserCodeReference assignmentHandlerReference = assignableDefinition.getAssignmentHandlerReference();
    if (assignmentHandlerReference!=null) {
      AssignmentHandler assignmentHandler = (AssignmentHandler) assignmentHandlerReference.getObject(this.getProcessDefinition());
      if (assignmentHandler!=null) {
        try {
          assignmentHandler.assign(assignable, this);
        } catch (Exception e) {
          throw new JbpmException("assignment handler threw exception: " + e, e);
        }
      }
    }
  }
 
  protected String resolveAssignmentExpression(String expression, String expressionLanguage) {
    ScriptManager scriptManager = EnvironmentImpl.getFromCurrent(ScriptManager.class);
    Object result = scriptManager.evaluateExpression(expression, expressionLanguage);
    if ( (result ==null)
         || (result instanceof String)
       ) {
      return (String) result;
    }
    throw new JbpmException("result of assignment expression "+expression+" is "+result+" ("+result.getClass().getName()+") instead of String");
  }
  
  // swimlanes ////////////////////////////////////////////////////////////////
  
  public void addSwimlane(SwimlaneImpl swimlane) {
    swimlanes.put(swimlane.getName(), swimlane);
    swimlane.setExecution(this);
  }
  
  public SwimlaneImpl getSwimlane(String swimlaneName) {
    return swimlanes.get(swimlaneName);
  }
  
  public void removeSwimlane(SwimlaneImpl swimlane) {
      swimlanes.remove(swimlane.getName());
      swimlane.setExecution(null);
  }
 
  public SwimlaneImpl getInitializedSwimlane(SwimlaneDefinitionImpl swimlaneDefinition) {
    String swimlaneName = swimlaneDefinition.getName();
    SwimlaneImpl swimlane = swimlanes.get(swimlaneName);
    if (swimlane==null) {
      swimlane = createSwimlane(swimlaneName);
      initializeAssignments(swimlaneDefinition, swimlane);
    }
 
    return swimlane;
  }
 
  public SwimlaneImpl createSwimlane(String swimlaneName) {
    SwimlaneImpl swimlane = new SwimlaneImpl();
    long dbid = EnvironmentImpl.getFromCurrent(DbidGenerator.class).getNextId();
    swimlane.setDbid(dbid);
    swimlane.setName(swimlaneName);
    swimlane.setExecution(this);
    swimlanes.put(swimlaneName, swimlane);
    return swimlane;
  }
  
  // child executions /////////////////////////////////////////////////////////
 
  public ExecutionImpl createExecution() {
    return createExecution(null);
  }
 
  public ExecutionImpl createExecution(String name) {
    // when an activity calls createExecution, propagation is explicit.
    // this means that the default propagation (proceed()) will not be called 
    propagation = Propagation.EXPLICIT;
 
    // create new execution
    ExecutionImpl childExecution = newChildExecution();
    // initialize child execution 
    childExecution.setProcessDefinition(getProcessDefinition());
    childExecution.processInstance = this.processInstance;
    childExecution.name = name;
    
    childExecution.save();
    // make sure that child execution are saved before added to a persistent collection
    // cause of the 'assigned' id strategy, adding the childExecution to the persistent collection 
    // before the dbid is assigned will result in identifier of an instance of ExecutionImpl altered from 0 to x
    addExecution(childExecution);
    // composeIds uses the parent so the childExecution has to be added before the ids are composed
    childExecution.composeIds();
 
    log.debug("created "+childExecution);
 
    return childExecution;
  }
 
  protected ExecutionImpl newChildExecution() {
    return new ExecutionImpl();
  }
 
  public void addExecution(ExecutionImpl execution) {
    execution.setParent(this);
    executions.add(execution);
    executionsMap = null;
  }
 
  /** @see Execution#getExecution(String) */
  public ExecutionImpl getExecution(String name) {
    Map<String, Execution> executionsMap = getExecutionsMap();
    return (ExecutionImpl) (executionsMap!=null ? executionsMap.get(name) : null);
  }
 
  public void removeExecution(ExecutionImpl child) {
    if (executions.contains(child)) {
      if (executions.remove(child)) {
        child.setParent(null);
 
        // invalidate the executionsMap cache
        executionsMap = null;
      } else {
        throw new JbpmException(child+" is not a child execution of "+this);
      }
    }
  }
 
  public Map<String, Execution> getExecutionsMap() {
    if ((executionsMap==null)) {
      // initialize executionsMap cache
      executionsMap = new HashMap<String, Execution>();
      for(ExecutionImpl execution: executions) {
        String executionName = execution.getName();
        // the next test makes sure that the first execution wins
        // in case there are multiple executions with the same name
        if (! executionsMap.containsKey(executionName)) {
          executionsMap.put(executionName, execution);
        }
      }
    }
    return executionsMap;
  }
  
  public boolean hasExecution(String name) {
    return ( (getExecutionsMap()!=null)
             && executionsMap.containsKey(name)
           );
  }
 
  public boolean isActive(String activityName) {
    return findActiveActivityNames().contains(activityName);
  }
 
  public Set<String> findActiveActivityNames() {
    return addActiveActivityNames(new HashSet<String>());
  }
 
  protected Set<String> addActiveActivityNames(Set<String> activityNames) {
    if ( ( (state.equals(STATE_ACTIVE_ROOT)) || (state.equals(STATE_ACTIVE_CONCURRENT)) )
         && 
         (activityName!=null)
       ) {
      activityNames.add(activityName);
    }
  
    for (ExecutionImpl childExecution: executions) {
      childExecution.addActiveActivityNames(activityNames);
    }
  
    return activityNames;
  }
 
  public ExecutionImpl findActiveExecutionIn(String activityName) {
    if ( activityName.equals(this.activityName)
         && isActive()) {
      return this;
    }
 
    for (ExecutionImpl childExecution: executions) {
      ExecutionImpl found = childExecution.findActiveExecutionIn(activityName);
      if (found!=null) {
        return found;
      }
    }
 
    return null;
  }
  
  // system variables /////////////////////////////////////////////////////////
  
  public void createSystemVariable(String key, Object value) {
    createSystemVariable(key, value, null);
  }
 
  public void createSystemVariable(String key, Object value, String typeName) {
    Variable variable = createVariableObject(key, value, typeName, false);
    systemVariables.put(variable.getKey(), variable);
  }
 
  public void setSystemVariable(String key, Object value) {
    Variable variable = systemVariables.get(key);
    if (variable!=null) {
      log.debug("setting system variable '"+key+"' in '"+this+"' to value '"+value+"'");
      variable.setValue(value, this);
    } else {
      log.debug("creating system variable '"+key+"' in '"+this+"' to value '"+value+"'");
      createSystemVariable(key, value, null);
    }
  }
  
  public Object getSystemVariable(String key) {
    Variable variable = systemVariables.get(key);
    if (variable!=null) {
      return variable.getValue(this);
    }
    return null;
  }
  
  public boolean removeSystemVariable(String key) {
    if (systemVariables.containsKey(key)) {
      return (systemVariables.remove(key)!=null);
    }
    return false;
  }
 
  // sub process creation /////////////////////////////////////////////////////
 
  public ClientProcessInstance createSubProcessInstance(ClientProcessDefinition processDefinition) {
    return createSubProcessInstance(processDefinition, null);
  }
  
  public ClientProcessInstance createSubProcessInstance(ClientProcessDefinition processDefinition, String key) {
    if (subProcessInstance!=null) {
      throw new JbpmException(toString()+" already has a sub process instance: "+subProcessInstance);
    }
    subProcessInstance = (ExecutionImpl) processDefinition.createProcessInstance(key);
    subProcessInstance.setSuperProcessExecution(this);
    return subProcessInstance;
  }
  
  public ClientProcessInstance startSubProcessInstance(ClientProcessDefinition processDefinition) {
    return startSubProcessInstance(processDefinition, null);
  }
  
  public ClientProcessInstance startSubProcessInstance(ClientProcessDefinition processDefinition, String key) {
    createSubProcessInstance(processDefinition, key);
    subProcessInstance.start();
    return subProcessInstance;
  }
 
  // state mgmt ///////////////////////////////////////////////////////////////
 
  /** @see Execution#suspend() */
  public void suspend() {
    super.suspend();
    this.propagation = Propagation.EXPLICIT;
    DbSession dbSession = EnvironmentImpl.getFromCurrent(DbSession.class, false);
    if (dbSession!=null) {
      dbSession.cascadeExecutionSuspend(this);
    }
  }
 
  /** @see Execution#resume() */
  public void resume() {
    super.resume();
    DbSession hibernatePvmDbSession = EnvironmentImpl.getFromCurrent(DbSession.class, false);
    if (hibernatePvmDbSession!=null) {
      hibernatePvmDbSession.cascadeExecutionResume(this);
    }
  }
 
  protected void checkActive() {
    if (!isActive()) {
      throw new JbpmException(toString()+" is not active: "+state);
    }
  }
  
  public boolean isEnded() {
    if (Execution.STATE_ENDED.equals(state)) {
      return true;
    }
    if (Execution.STATE_CREATED.equals(state)) {
      return false;
    }
    if (Execution.STATE_ACTIVE_ROOT.equals(state)) {
      return false;
    }
    if (Execution.STATE_ACTIVE_CONCURRENT.equals(state)) {
      return false;
    }
    if (Execution.STATE_INACTIVE_CONCURRENT_ROOT.equals(state)) {
      return false;
    }
    if (Execution.STATE_INACTIVE_SCOPE.equals(state)) {
      return false;
    }
    if (Execution.STATE_SUSPENDED.equals(state)) {
      return false;
    }
    if (Execution.STATE_ASYNC.equals(state)) {
      return false;
    }
    return true;
  }
 
  ////////////////////////////////////////////////////////////////////////////////
 
  // overriding the ScopeInstanceImpl methods /////////////////////////////////
  
  public ScopeInstanceImpl getParentVariableScope() {
    return parent;
  }
 
  public ExecutionImpl getTimerExecution() {
    return this;
  }
 
  // overridable by process languages /////////////////////////////////////////
  
  /** by default this will use {@link ActivityImpl#findOutgoingTransition(String)} to 
   * search for the outgoing transition, which includes a search over the parent chain 
   * of the current activity.  This method allows process languages to overwrite this default 
   * implementation of the transition lookup by transitionName.*/
  protected TransitionImpl findTransition(String transitionName) {
    return getActivity().findOutgoingTransition(transitionName);
  }
 
  protected TransitionImpl findDefaultTransition() {
    return getActivity().findDefaultTransition();
  }
  
  // history //////////////////////////////////////////////////////////////////
 
  public void historyAutomatic() {
    HistoryEvent.fire(new AutomaticEnd(), this);
  }
 
  public void historyDecision(String transitionName) {
    HistoryEvent.fire(new DecisionEnd(transitionName), this);
  }
  
  public void historyActivityStart() {
    HistoryEvent.fire(new ActivityStart(), this);
  }
 
  public void historyActivityEnd() {
    HistoryEvent.fire(new ActivityEnd(), this);
  }
 
  public void historyActivityEnd(String transitionName) {
    HistoryEvent.fire(new ActivityEnd(transitionName), this);
  }
 
  // equals ///////////////////////////////////////////////////////////////////
  // hack to support comparing hibernate proxies against the real objects
  // since this always falls back to ==, we don't need to overwrite the hashcode
  public boolean equals(Object o) {
    return EqualsUtil.equals(this, o);
  }
  
  // process definition getter and setter /////////////////////////////////////
  // this getter and setter is special because persistence is based on the   // 
  // process definition id.                                                  //
  /////////////////////////////////////////////////////////////////////////////
  
  
  public ProcessDefinitionImpl getProcessDefinition() {
    if ( (processDefinition==null)
         && (processDefinitionId!=null) 
       ) {
      RepositorySession repositorySession = EnvironmentImpl.getFromCurrent(RepositorySession.class);
      processDefinition = (ProcessDefinitionImpl) repositorySession.findProcessDefinitionById(processDefinitionId);
      if (processDefinition==null) {
        throw new JbpmException("couldn't find process definition "+processDefinitionId+" in the repository");
      }
    }
    return processDefinition;
  }
  public void setProcessDefinition(ProcessDefinitionImpl processDefinition) {
    this.processDefinition = processDefinition;
    this.processDefinitionId = processDefinition.getId();
  }
  
  // activity getter and setter ///////////////////////////////////////////////
  // this getter and setter is special because persistence is based on the   // 
  // activity name.                                                          //
  /////////////////////////////////////////////////////////////////////////////
  
  public ActivityImpl getActivity() {
    if ( (activity==null)
         && (activityName!=null)
       ) {
      activity = getProcessDefinition().findActivity(activityName);
    }
    return activity;
  }
  
  public void setActivity(ActivityImpl activity) {
    this.activity = activity;
    if (activity!=null) {
      this.activityName = activity.getName();
    } else {
      this.activityName = null;
    }
  }
 
  public String getActivityName() {
    return activityName;
  }
 
  // special getters and setters /////////////////////////////////////////////////
 
  public boolean hasAsyncEndEvent(List<ActivityImpl> leftActivities) {
    for (ActivityImpl leftActivity : leftActivities) {
      EventImpl endEvent = leftActivity.getEvent(Event.END);
      if ( (endEvent!=null)
           && (endEvent.isAsync())
         ) {
        return true;
      }
    }
    return false;
  }
 
  public boolean getIsProcessInstance() {
    return parent==null;
  }
 
  // getters and setters for scope instance //////////////////////////////////////
  
  public ExecutionImpl getExecution() {
    return this;
  }
 
  // getters and setters /////////////////////////////////////////////////////////
  
  public TransitionImpl getTransition() {
    return transition;
  }
  public void setTransition(TransitionImpl transition) {
    this.transition = transition;
  }
  public EventImpl getEvent() {
    return event;
  }
  public ObservableElementImpl getEventSource() {
    return eventSource;
  }
  public Collection<ExecutionImpl> getExecutions() {
    return (Collection) executions;
  }
  public String getName() {
    return name;
  }
  public ExecutionImpl getParent() {
    return parent;
  }
  public int getPriority() {
    return priority;
  }
  public void setEvent(EventImpl event) {
    this.event = event;
  }
  public void setEventSource(ObservableElementImpl eventSource) {
    this.eventSource = eventSource;
  }
  public void setPriority(int priority) {
    this.priority = priority;
  }
  public ExecutionImpl getProcessInstance() {
    return processInstance;
  }
  public void setProcessInstance(ExecutionImpl processInstance) {
    this.processInstance = processInstance;
  }
  public String getKey() {
    return key;
  }
  public Propagation getPropagation() {
    return propagation;
  }
  public void setPropagation(Propagation propagation) {
    this.propagation = propagation;
  }
  public void setName(String name) {
    this.name = name;
  }
  public void setExecutions(Collection<ExecutionImpl> executions) {
    this.executions = executions;
  }
  public void setParent(ExecutionImpl parent) {
    this.parent = parent;
  }
  public ExecutionImpl getSuperProcessExecution() {
    return superProcessExecution;
  }
  public void setSuperProcessExecution(ExecutionImpl superProcessExecution) {
    this.superProcessExecution = superProcessExecution;
  }
  public ExecutionImpl getSubProcessInstance() {
    return subProcessInstance;
  }
  public void setSubProcessInstance(ExecutionImpl subProcessExecution) {
    this.subProcessInstance = subProcessExecution;
  }
  public void setKey(String key) {
    this.key = key;
  }
  public String getId() {
    return id;
  }
  public void setId(String id) {
    this.id = id;
  }
  public Long getHistoryActivityInstanceDbid() {
    return historyActivityInstanceDbid;
  }
  public void setHistoryActivityInstanceDbid(Long historyActivityInstanceDbid) {
    this.historyActivityInstanceDbid = historyActivityInstanceDbid;
  }
  public Date getHistoryActivityStart() {
    return historyActivityStart;
  }
  public void setHistoryActivityStart(Date historyActivityStart) {
    this.historyActivityStart = historyActivityStart;
  }
  public String getProcessDefinitionId() {
    return processDefinitionId;
  }
  public int getEventListenerIndex() {
    return eventListenerIndex;
  }
  public void setEventListenerIndex(int eventListenerIndex) {
    this.eventListenerIndex = eventListenerIndex;
  }
  public AtomicOperation getEventCompletedOperation() {
    return eventCompletedOperation;
  }
  public void setEventCompletedOperation(AtomicOperation eventCompletedOperation) {
    this.eventCompletedOperation = eventCompletedOperation;
  }
}