KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > shark > WfProcessImpl


1 package org.enhydra.shark;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Collection JavaDoc;
5 import java.util.HashMap JavaDoc;
6 import java.util.HashSet JavaDoc;
7 import java.util.Iterator JavaDoc;
8 import java.util.List JavaDoc;
9 import java.util.Map JavaDoc;
10 import java.util.Set JavaDoc;
11
12 import org.enhydra.shark.api.RootException;
13 import org.enhydra.shark.api.SharkTransaction;
14 import org.enhydra.shark.api.TransactionException;
15 import org.enhydra.shark.api.client.wfbase.BaseException;
16 import org.enhydra.shark.api.client.wfmodel.AlreadyRunning;
17 import org.enhydra.shark.api.client.wfmodel.AlreadySuspended;
18 import org.enhydra.shark.api.client.wfmodel.CannotResume;
19 import org.enhydra.shark.api.client.wfmodel.CannotStart;
20 import org.enhydra.shark.api.client.wfmodel.CannotStop;
21 import org.enhydra.shark.api.client.wfmodel.CannotSuspend;
22 import org.enhydra.shark.api.client.wfmodel.InvalidData;
23 import org.enhydra.shark.api.client.wfmodel.InvalidPerformer;
24 import org.enhydra.shark.api.client.wfmodel.InvalidState;
25 import org.enhydra.shark.api.client.wfmodel.NotRunning;
26 import org.enhydra.shark.api.client.wfmodel.NotSuspended;
27 import org.enhydra.shark.api.client.wfmodel.ResultNotAvailable;
28 import org.enhydra.shark.api.client.wfmodel.TransitionNotAllowed;
29 import org.enhydra.shark.api.client.wfmodel.UpdateNotAllowed;
30 import org.enhydra.shark.api.client.wfmodel.WfCreateProcessEventAudit;
31 import org.enhydra.shark.api.client.wfmodel.WfDataEventAudit;
32 import org.enhydra.shark.api.client.wfmodel.WfEventAudit;
33 import org.enhydra.shark.api.client.wfmodel.WfRequester;
34 import org.enhydra.shark.api.client.wfmodel.WfStateEventAudit;
35 import org.enhydra.shark.api.common.SharkConstants;
36 import org.enhydra.shark.api.internal.instancepersistence.ActivityPersistenceInterface;
37 import org.enhydra.shark.api.internal.instancepersistence.AndJoinEntryInterface;
38 import org.enhydra.shark.api.internal.instancepersistence.PersistenceException;
39 import org.enhydra.shark.api.internal.instancepersistence.PersistentManagerInterface;
40 import org.enhydra.shark.api.internal.instancepersistence.ProcessPersistenceInterface;
41 import org.enhydra.shark.api.internal.instancepersistence.ProcessVariablePersistenceInterface;
42 import org.enhydra.shark.api.internal.limitagent.LimitAgentException;
43 import org.enhydra.shark.api.internal.limitagent.LimitAgentManager;
44 import org.enhydra.shark.api.internal.scripting.Evaluator;
45 import org.enhydra.shark.api.internal.toolagent.ToolAgentGeneralException;
46 import org.enhydra.shark.api.internal.working.WfActivityInternal;
47 import org.enhydra.shark.api.internal.working.WfProcessInternal;
48 import org.enhydra.shark.api.internal.working.WfProcessMgrInternal;
49 import org.enhydra.shark.api.internal.working.WfRequesterInternal;
50 import org.enhydra.shark.utilities.MiscUtilities;
51 import org.enhydra.shark.xpdl.XMLCollectionElement;
52 import org.enhydra.shark.xpdl.XMLUtil;
53 import org.enhydra.shark.xpdl.XPDLConstants;
54 import org.enhydra.shark.xpdl.elements.Activities;
55 import org.enhydra.shark.xpdl.elements.Activity;
56 import org.enhydra.shark.xpdl.elements.ActivitySet;
57 import org.enhydra.shark.xpdl.elements.BlockActivity;
58 import org.enhydra.shark.xpdl.elements.Condition;
59 import org.enhydra.shark.xpdl.elements.ProcessHeader;
60 import org.enhydra.shark.xpdl.elements.Transition;
61 import org.enhydra.shark.xpdl.elements.Transitions;
62 import org.enhydra.shark.xpdl.elements.WorkflowProcess;
63
64 /**
65  * WfProcessImpl - Workflow Process Object implementation
66  * @author Sasa Bojanic, Vladimir Puskas
67  * @version 1.0.1
68  */

69 public class WfProcessImpl extends WfExecutionObjectImpl implements WfProcessInternal {
70
71    private String JavaDoc actRequesterId;
72    private String JavaDoc actRequestersProcessId;
73
74    private String JavaDoc resRequesterId;
75    private String JavaDoc managerName;
76    private String JavaDoc pkgId;
77    private String JavaDoc pDefId;
78    private String JavaDoc mgrVer;
79
80    protected Map JavaDoc processContext;
81
82    // condition evaluation
83
private Evaluator evaluator;
84    private List JavaDoc lastFinishedActivities=new ArrayList JavaDoc();
85    private WfProcessMgrInternal manager;
86    private Map JavaDoc activeActivitiesMap;
87    private Map JavaDoc tmpActivitiesMap;
88    private boolean isRunning=false;
89
90    private long creationTime=Long.MAX_VALUE/2;
91    private long startTime=Long.MAX_VALUE/2;
92
93    protected WorkflowProcess xpdlProcess;
94
95    protected Set JavaDoc variableIdsToPersist=new HashSet JavaDoc();
96    protected Map JavaDoc activityToFollowedTransitions=new HashMap JavaDoc();
97    protected Map JavaDoc newActivityToFollowedTransitions=new HashMap JavaDoc();
98
99    protected SharkTransaction initialTransaction;
100    protected Thread JavaDoc startingThread=null;
101    protected WfActivityInternal actRequester;
102
103    private boolean terminateOrAbortFromActivity=false;
104
105    private String JavaDoc externalRequesterClassName=null;
106
107    protected boolean justCreated=false;
108    protected boolean justCreatedVariables=false;
109    /**
110     * Creates new WfProcessImpl
111     *
112     * @param t a SharkTransaction
113     * @param manager a WfProcessMgrInternal
114     * @param requester a WfRequester
115     * @param key a String
116     *
117     * @exception BaseException
118     *
119     */

120    protected WfProcessImpl(SharkTransaction t,
121                            WfProcessMgrInternal manager,
122                            WfRequesterInternal requester,
123                            String JavaDoc key) throws BaseException {
124       this.key=key;
125       this.manager=manager;
126       this.managerName=manager.name(t);
127       this.justCreated=true;
128       this.justCreatedVariables=true;
129       setXPDLAttribs();
130       if (requester.getExternalRequester(t)!=null) {
131          this.externalRequesterClassName=requester.getExternalRequester(t).getClass().getName();
132       }
133       if (requester !=null && requester instanceof WfActivityInternal) {
134          this.actRequesterId=((WfActivityInternal)requester).key(t);
135          this.actRequestersProcessId=((WfActivityInternal)requester).process_id(t);
136          this.actRequester=(WfActivityInternal)requester;
137          this.resRequesterId=this.actRequester.getResourceRequesterUsername(t);
138          this.initialTransaction=t;
139       } else if (requester !=null && requester instanceof WfDefaultRequester) {
140          this.resRequesterId=((WfDefaultRequester)requester).getResourceRequesterUsername(t);
141       }
142
143       SharkUtilities.addProcessToCache(t,this);
144       name=getProcessDefinition(t).getName();
145       if (name.equals("")) {
146          name=getProcessDefinition(t).getId();
147       }
148       ProcessHeader ph=((WorkflowProcess)getXPDLObject(t)).getProcessHeader();
149       description=ph.getDescription();
150       if (description!=null && description.length()>254) {
151          description=description.substring(0,253);
152       }
153       try {
154          priority=Integer.valueOf(ph.getPriority()).shortValue();
155       } catch (Exception JavaDoc ex) {
156          priority=3;
157       }
158
159       lastStateTime = System.currentTimeMillis();
160       creationTime= lastStateTime;
161       if (SharkEngineManager.getInstance().getEventAuditManager()!=null || externalRequesterClassName!=null) {
162          WfCreateProcessEventAudit cpea=SharkEngineManager
163             .getInstance()
164             .getObjectFactory()
165             .createCreateProcessEventAuditWrapper(t,this,requester);
166          if (externalRequesterClassName!=null) {
167             notifyRequester(t,cpea);
168          }
169          
170       }
171       lastStateEventAudit=SharkEngineManager.
172          getInstance().
173          getObjectFactory().
174          createStateEventAuditWrapper(t,
175                                    this,
176                                    SharkConstants.EVENT_PROCESS_STATE_CHANGED,
177                                    null,
178                                    state);
179       if (externalRequesterClassName!=null) {
180          notifyRequester(t,lastStateEventAudit);
181       }
182       activeActivitiesMap=new HashMap JavaDoc();
183
184       initializeProcessContext(t);
185       if (processContext.size()>0) {
186          variableIdsToPersist.addAll(getContext(t).keySet());
187
188          if (SharkEngineManager.getInstance().getEventAuditManager()!=null || externalRequesterClassName!=null) {
189             WfDataEventAudit dea=SharkEngineManager
190                .getInstance()
191                .getObjectFactory()
192                .createDataEventAuditWrapper(t,
193                                             this,
194                                             SharkConstants.EVENT_PROCESS_CONTEXT_CHANGED,
195                                             null,
196                                             new HashMap JavaDoc(processContext));
197             if (externalRequesterClassName!=null) {
198                notifyRequester(t, dea);
199             }
200          }
201       }
202       activityToFollowedTransitions=new HashMap JavaDoc();
203       try {
204          persist(t);
205          persistProcessContext(t);
206       } catch (TransactionException tme) {
207          throw new BaseException(tme);
208       }
209
210       SharkEngineManager.getInstance().getCallbackUtilities().info("Process "+this+" is created");
211    }
212
213    /**
214     * Used to create object when restoring it from database.
215     */

216    protected WfProcessImpl (ProcessPersistenceInterface po) {
217       restore(po);
218    }
219
220    /**
221     * Retrieve the requestor of this process.
222     *
223     * @param t a SharkTransaction
224     *
225     * @return a WfRequester
226     *
227     * @exception BaseException
228     */

229    public WfRequesterInternal requester (SharkTransaction t) throws BaseException {
230       WfRequesterInternal requester=null;
231       if (this.actRequesterId!=null) {
232          if (actRequester!=null &&
233                 ((initialTransaction!=null && initialTransaction.equals(t)) ||
234                     (startingThread!=null && startingThread.equals(Thread.currentThread())))) {
235             requester=actRequester;
236          } else {
237             WfProcessInternal pReq=SharkUtilities.getProcess(t,this.actRequestersProcessId);
238             if (pReq!=null) {
239                requester=pReq.getActivity(t,this.actRequesterId);
240             }
241          }
242       }
243       WfRequester extReq=null;
244       if (requester==null) {
245          if (externalRequesterClassName!=null) {
246             try {
247                extReq=(WfRequester)Class.forName(externalRequesterClassName).newInstance();
248             } catch (Exception JavaDoc ex) {
249                SharkEngineManager.getInstance().getCallbackUtilities().warn("Can't create external requester - "+externalRequesterClassName+" is not in the classpath, or it doesn't have default constructor.");
250             }
251          }
252          if (this.resRequesterId!=null) {
253             requester=SharkEngineManager.getInstance().getObjectFactory().createDefaultRequester(this.resRequesterId,extReq);
254          } else {
255             //throw new BaseException("Process must have some requester");
256
System.err.println("Process Requester is missing - maybe the parent process is deleted. Empty requester will be returned !");
257             requester=SharkEngineManager.getInstance().getObjectFactory().createDefaultRequester("",extReq);
258             
259          }
260       }
261       return requester;
262    }
263
264    public void setExternalRequesterClassName (SharkTransaction t,String JavaDoc extReqClassName) throws BaseException {
265       this.externalRequesterClassName=extReqClassName;
266       try {
267          persist(t);
268       } catch (TransactionException tme) {
269          throw new BaseException(tme);
270       }
271    }
272
273    /**
274     * Retrieve the no of activities in this process.
275     *
276     * @param t a SharkTransaction
277     *
278     * @return an int
279     *
280     * @exception BaseException
281     *
282     */

283    public int how_many_step (SharkTransaction t) throws BaseException {
284       // TODO: see OMG/WfMC docu which acitivities to consider:
285
// all or active ones only
286
return getActiveActivitiesMap(t).size();
287    }
288
289    /**
290     * Retrieve the WfProcessMgr of this process.
291     *
292     * @param t a SharkTransaction
293     *
294     * @return a WfProcessMgr
295     *
296     * @exception BaseException
297     */

298    public WfProcessMgrInternal manager (SharkTransaction t) throws BaseException {
299       if (manager==null) {
300          manager=SharkUtilities.getProcessMgr(t, managerName);
301          if (manager==null) {
302             throw new BaseException("process "+this+" - can't find manager "+managerName);
303          }
304       }
305       return manager;
306    }
307
308
309    /**
310     * Retrieve the result for this process.
311     *
312     * @param t a SharkTransaction
313     *
314     * @return a Map
315     *
316     * @exception BaseException
317     * @exception ResultNotAvailable
318     */

319    public Map JavaDoc result (SharkTransaction t) throws BaseException, ResultNotAvailable {
320       Map JavaDoc resultSigLHM = manager(t).result_signature(t);
321       Map JavaDoc results = new HashMap JavaDoc();
322
323       if (resultSigLHM != null) {
324          Set JavaDoc resultKeys = resultSigLHM.keySet();
325          Iterator JavaDoc i = resultKeys.iterator();
326          while (i.hasNext()) {
327             String JavaDoc fpId =(String JavaDoc)i.next();
328             try {
329                results.put(fpId,MiscUtilities.cloneWRD(getContext(t).get(fpId)));
330             } catch (Throwable JavaDoc thr) {
331                throw new BaseException(thr);
332             }
333          }
334       }
335       return results;
336    }
337
338    /**
339     * Starts the process.
340     *
341     * @param t a SharkTransaction
342     *
343     * @exception BaseException
344     * @exception CannotStart
345     * @exception AlreadyRunning
346     *
347     */

348    public void start (SharkTransaction t) throws BaseException, CannotStart, AlreadyRunning, ToolAgentGeneralException {
349       if (state(t).equals(SharkConstants.STATE_OPEN_RUNNING)) {
350          throw new AlreadyRunning("The process is already running - can't start again!");
351       }
352       if (state(t).startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
353          throw new CannotStart("The process is closed - can't start it!");
354       }
355
356       if (getProcessDefinition(t).getStartingActivities().size()==0) {
357          throw new CannotStart("There are no starting activities in the process - can't start it!");
358       }
359
360       try {
361          startingThread=Thread.currentThread();
362          initialTransaction=null;
363          change_state(t,SharkConstants.STATE_OPEN_RUNNING);
364          SharkEngineManager.getInstance().getCallbackUtilities().info("Starting Process "+this);
365          run(t, null);
366       } catch (InvalidState is) {
367          throw new CannotStart(is);
368       } catch (TransitionNotAllowed tna) {
369          throw new CannotStart(tna);
370       } catch (ToolAgentGeneralException tage) {
371          try {
372             change_state(t,SharkConstants.STATE_CLOSED_TERMINATED);
373          } catch (Exception JavaDoc ex) {
374             throw new BaseException(ex);
375          }
376          throw tage;
377       } finally{
378          actRequester=null;
379          startingThread=null;
380       }
381
382    }
383
384    /**
385     * Method change_state
386     *
387     * @param t a SharkTransaction
388     * @param new_state a String
389     *
390     * @exception BaseException
391     * @exception InvalidState
392     * @exception TransitionNotAllowed
393     */

394    protected void change_state (SharkTransaction t,String JavaDoc new_state) throws BaseException, InvalidState, TransitionNotAllowed {
395       //System.out.println(this+" - changing state from "+state+" to "+new_state);
396
if (!SharkUtilities.valid_process_states(state(t)).contains(new_state)) {
397          throw new TransitionNotAllowed("Can't change to state "+new_state+", from state "+state+" !");
398       }
399
400       if (new_state.equals(SharkConstants.STATE_OPEN_RUNNING)) {
401          startTime = System.currentTimeMillis();
402          // call the limit agent manager here - this is the only central point
403
// for both automatic and manual activties; start time is set based
404
// on the process start time
405
// NOTE: there is no sense to have limits for automatic activities in
406
// standard shark implementation
407
if (SharkEngineManager.getInstance().getLimitAgentManager()!=null) {
408             this.activateLimitAgent(t);
409          }
410       }
411       // persisting the state change
412
String JavaDoc oldState=state;
413       state=new_state;
414
415       lastStateTime = System.currentTimeMillis();
416       try {
417          persist(t);
418       } catch (TransactionException tme) {
419          throw new BaseException(tme);
420       }
421
422       String JavaDoc eventType=SharkConstants.EVENT_PROCESS_STATE_CHANGED;
423       lastStateEventAudit = SharkEngineManager
424          .getInstance()
425          .getObjectFactory()
426          .createStateEventAuditWrapper(t, this, eventType,oldState,new_state);
427       if (state.startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
428          if (!terminateOrAbortFromActivity && (externalRequesterClassName!=null || actRequesterId!=null)) {
429             notifyRequester(t,lastStateEventAudit);
430          }
431          if (state.equals(SharkConstants.STATE_CLOSED_COMPLETED)) {
432             try {
433                delete(t);
434             } catch (TransactionException te) {
435                throw new BaseException(te);
436             }
437          }
438
439          // cancel the limit agent when we fall out of running state
440
LimitAgentManager mgr = SharkEngineManager.getInstance().getLimitAgentManager();
441          if (mgr != null) {
442             try {
443                mgr.notifyStop(key,null);
444             } catch (LimitAgentException e) {
445                throw new BaseException(e);
446             }
447          }
448       } else {
449          if (externalRequesterClassName!=null) {
450             notifyRequester(t, lastStateEventAudit);
451          }
452       }
453
454    }
455
456    /**
457     * Asignes the new values to some process context variables. The variable
458     * can be given by it's name or it's id.
459     *
460     * @param t a SharkTransaction
461     * @param newValue a Map
462     *
463     * @exception BaseException
464     * @exception InvalidData
465     * @exception UpdateNotAllowed
466     *
467     */

468    public void set_process_context (SharkTransaction t,Map JavaDoc newValue) throws BaseException, InvalidData, UpdateNotAllowed {
469       Map JavaDoc oldValues=new HashMap JavaDoc();
470       Map JavaDoc newChanged=new HashMap JavaDoc();
471       Iterator JavaDoc it=newValue.entrySet().iterator();
472       while (it.hasNext()) {
473          Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
474          String JavaDoc id=(String JavaDoc)me.getKey();
475          Object JavaDoc val=me.getValue();
476          // this happens when passing the OUT type formal param. for the process
477
//if (val==null) continue;
478
if (getContext(t).containsKey(id)) {
479             //type checking
480
Object JavaDoc oldVal=getContext(t).get(id);
481             if (SharkUtilities.checkDataType(t,getProcessDefinition(t),id,oldVal,val)) {
482                //System.out.println("var "+id+"["+oldVal+","+val+"]");
483
if ((oldVal!=null && !oldVal.equals(val)) || (oldVal==null && val!=null)) {
484                   oldValues.put(id,oldVal);
485                   newChanged.put(id,val);
486                }
487             } else {
488                throw new InvalidData("Invalid data type for process variable "+id);
489             }
490          } else {
491             throw new UpdateNotAllowed("Context attribute "+id+" does not exist in process context - adding new attributes to the process context is not allowed");
492          }
493       }
494       
495       if (newChanged.size()>0) {
496          getContext(t).putAll(newChanged);
497          variableIdsToPersist.addAll(newChanged.keySet());
498          persistProcessContext(t);
499          if (SharkEngineManager.getInstance().getEventAuditManager()!=null || externalRequesterClassName!=null) {
500             boolean persistOldEventAuditData=new Boolean JavaDoc(
501                   SharkEngineManager
502                      .getInstance()
503                      .getCallbackUtilities()
504                      .getProperty("PERSIST_OLD_EVENT_AUDIT_DATA","true")).booleanValue();
505             if (!persistOldEventAuditData) {
506                oldValues=null;
507             }
508             WfDataEventAudit dea=SharkEngineManager.getInstance().getObjectFactory().
509                createDataEventAuditWrapper(t, this,
510                                            SharkConstants.EVENT_PROCESS_CONTEXT_CHANGED,
511                                            oldValues,
512                                            newChanged);
513             if (externalRequesterClassName!=null) {
514                notifyRequester(t, dea);
515             }
516          }
517       }
518    }
519
520    /**
521     * Resume this process.
522     */

523    public void resume(SharkTransaction t) throws BaseException, CannotResume, NotSuspended {
524       try {
525          if (!state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
526             throw new NotSuspended("The process is not suspended - can't resume it!");
527          }
528          // if this is a subflow process of suspended activity, and it is
529
// executed as SYNCHRONOUS, do not allow process to resume
530
WfRequesterInternal requester=requester(t);
531          if (requester!=null && (requester instanceof WfActivityInternal)) {
532             WfActivityInternal waImpl=(WfActivityInternal)requester;
533             if (waImpl.state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
534                // Determine subflow type
535
if (waImpl.isPerformerSynchronous(t)) {
536                   SharkEngineManager.getInstance().getCallbackUtilities().error("Process"+toString()+" - Cannot resume because the requester activity is suspended");
537                   throw new CannotResume("Cannot resume - The requester activity is suspended");
538                }
539             }
540          }
541          SharkEngineManager.getInstance().getCallbackUtilities().info("Resuming process "+this);
542          change_state(t, SharkConstants.STATE_OPEN_RUNNING);
543
544          Iterator JavaDoc it=getActiveActivities(t).iterator();
545          while (it.hasNext()) {
546             WfActivityInternal act=(WfActivityInternal)it.next();
547             if (act.state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
548                if (act.block_activity_id(t)==null) {
549                   act.resume(t);
550                }
551             }
552          }
553       } catch (InvalidState is) {
554          throw new CannotResume(is);
555       } catch (TransitionNotAllowed tna) {
556          throw new CannotResume(tna);
557       }
558    }
559
560    /**
561     * Suspend this process.
562     */

563    public void suspend(SharkTransaction t) throws BaseException, CannotSuspend, NotRunning, AlreadySuspended {
564       if (state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
565          throw new AlreadySuspended("The process is already suspended - can't suspend it twice!");
566       }
567       if (state(t).startsWith(SharkConstants.STATEPREFIX_OPEN_NOT_RUNNING)) {
568          throw new NotRunning("The process is not in the running state");
569       }
570       try {
571          SharkEngineManager.getInstance().getCallbackUtilities().info("Suspending process "+this);
572          change_state(t,SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED);
573
574          Iterator JavaDoc it=getActiveActivities(t).iterator();
575          while (it.hasNext()) {
576             WfActivityInternal act=(WfActivityInternal)it.next();
577             String JavaDoc actState=act.state(t);
578             if (!actState.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
579                if (act.block_activity_id(t)==null) {
580                   act.suspend(t);
581                }
582             }
583          }
584       } catch (InvalidState is) {
585          throw new CannotSuspend(is);
586       } catch (TransitionNotAllowed tna) {
587          throw new CannotSuspend(tna);
588       }
589    }
590
591    public void terminateFromActivity (SharkTransaction t) throws BaseException, CannotStop, NotRunning {
592       terminateOrAbortFromActivity=true;
593       terminate(t);
594    }
595
596    /**
597     * Terminate this process.
598     */

599    public void terminate(SharkTransaction t) throws BaseException, CannotStop, NotRunning {
600       try {
601          String JavaDoc stateStr = SharkConstants.STATE_CLOSED_TERMINATED;
602          if (!state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
603             throw new CannotStop("The process is already closed - can't terminate it!");
604          }
605          SharkEngineManager.getInstance().getCallbackUtilities().info("Terminating process "+this);
606
607          change_state(t,stateStr);
608
609          Iterator JavaDoc it=getActiveActivities(t).iterator();
610          while (it.hasNext()) {
611             WfActivityInternal act=(WfActivityInternal)it.next();
612             if (act.block_activity_id(t)==null) {
613                act.terminateFromProcess(t);
614             }
615          }
616          lastFinishedActivities.clear();
617
618          if (activeActivitiesMap!=null) {
619             activeActivitiesMap.clear();
620          }
621
622          //delete(t);
623

624       } catch (InvalidState is) {
625          throw new CannotStop(is);
626       } catch (TransitionNotAllowed tna) {
627          throw new CannotStop(tna);
628       } /*catch (TransactionException tme) {
629        throw new BaseException(tme);
630        }*/

631    }
632
633    public void abortFromActivity (SharkTransaction t) throws BaseException, CannotStop, NotRunning {
634       terminateOrAbortFromActivity=true;
635       abort(t);
636    }
637
638    /**
639     * Abort the execution of this process.
640     *
641     * @param t a SharkTransaction
642     *
643     * @exception BaseException
644     * @exception CannotStop
645     * @exception NotRunning
646     */

647    public void abort(SharkTransaction t) throws BaseException, CannotStop, NotRunning {
648       String JavaDoc stateStr = SharkConstants.STATE_CLOSED_ABORTED;
649       if (!state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
650          throw new CannotStop("The process is already closed - can't abort it!");
651       }
652       try {
653          SharkEngineManager.getInstance().getCallbackUtilities().info("Aborting process "+this);
654          change_state(t,stateStr);
655
656          Iterator JavaDoc it=getActiveActivities(t).iterator();
657
658          while (it.hasNext()) {
659             WfActivityInternal act=(WfActivityInternal)it.next();
660             if (act.block_activity_id(t)==null) {
661                act.abortFromProcess(t);
662             }
663          }
664
665          lastFinishedActivities.clear();
666
667          if (activeActivitiesMap!=null) {
668             activeActivitiesMap.clear();
669          }
670
671          //delete(t);
672

673       } catch (InvalidState is) {
674          throw new CannotStop(is);
675       } catch (TransitionNotAllowed tna) {
676          throw new CannotStop(tna);
677       } /*catch (TransactionException tme) {
678        throw new BaseException(tme);
679        }*/

680    }
681
682    protected void run (SharkTransaction t, WfActivityInternal lastFinishedActivity) throws BaseException, ToolAgentGeneralException {
683       isRunning=true;
684       try {
685          if (lastFinishedActivity==null) {
686             List JavaDoc starts=getProcessDefinition(t).getStartingActivities();
687
688             for (Iterator JavaDoc it=starts.iterator(); it.hasNext();) {
689                String JavaDoc asDefId=null;
690                Activity actDef=(Activity)it.next();
691                Object JavaDoc owner=actDef.getParent().getParent();
692                if (owner instanceof ActivitySet) {
693                   asDefId=((ActivitySet)owner).getId();
694                }
695                startActivity(t,asDefId,actDef,null);
696             }
697             //return;
698
}
699          while (lastFinishedActivities.size()>0) {
700             if (!state.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
701                //System.out.println("QN for lfa "+lastFinishedActivities.get(0));
702
if(!state.startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
703                   queueNext(t, (WfActivityInternal)lastFinishedActivities.get(0));
704                   //System.out.println("QN for lfa "+lastFinishedActivities.get(0)+" finished");
705
}
706                lastFinishedActivities.remove(0);
707             } else {
708                //System.out.println("ELSE");
709
return;
710             }
711          }
712          if (state.startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
713             /*try {
714              delete(t);
715              } catch (TransactionException tme) {
716              throw new BaseException(tme);
717              }*/

718             return;
719          }
720       } finally {
721          isRunning=false;
722       }
723
724    }
725
726    /**
727     * Activates an activity object
728     *
729     * @param t a SharkTransaction
730     * @param actDefId a String
731     * @param blockActId a String
732     *
733     * @exception BaseException
734     */

735    public void start_activity(SharkTransaction t, String JavaDoc actDefId,String JavaDoc blockActId) throws BaseException, ToolAgentGeneralException {
736       if (state(t).startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
737          throw new BaseException("Can't start the activity of closed process!");
738       }
739       WorkflowProcess wp=getProcessDefinition(t);
740
741       Activities acts=null;
742       String JavaDoc asDefId=null;
743       // if we must start activity that is inside some block
744
if (blockActId!=null && blockActId.length()>0) {
745          WfActivityInternal baImpl = getActiveActivity(t, blockActId);
746          if (baImpl!=null) {
747             BlockActivity ba=SharkUtilities.getActivityDefinition(t,baImpl,wp,baImpl.block_activity(t)).getActivityTypes().getBlockActivity();
748             asDefId=ba.getBlockId();
749             ActivitySet aSet=wp.getActivitySet(asDefId);
750             acts=aSet.getActivities();
751          }
752       }
753       if (acts==null) {
754          acts=wp.getActivities();
755       }
756       Activity activity=acts.getActivity(actDefId);
757       WfActivityInternal ba = getActiveActivity(t, blockActId);
758
759       if (state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED)) {
760          try {
761             change_state(t,SharkConstants.STATE_OPEN_RUNNING);
762          } catch (Exception JavaDoc ex) {
763             throw new BaseException(ex);
764          }
765          // call the limit agent manager here
766
if (SharkEngineManager.getInstance().getLimitAgentManager()!=null) {
767             this.activateLimitAgent(t);
768          }
769       }
770
771       startActivity(t,asDefId,activity,ba);
772    }
773
774    /**
775     * Method process_definition_id
776     *
777     * @param t a SharkTransaction
778     *
779     * @return a String
780     *
781     * @exception BaseException
782     */

783    public final String JavaDoc process_definition_id(SharkTransaction t) throws BaseException {
784       return pDefId;
785    }
786
787    public final String JavaDoc manager_name(SharkTransaction t) throws BaseException {
788       return managerName;
789    }
790
791    public final String JavaDoc manager_version (SharkTransaction t) throws BaseException {
792       return mgrVer;
793    }
794
795    // Activates an activity object
796
protected void startActivity(SharkTransaction t,
797                                 String JavaDoc asDefId,
798                                 Activity activity,
799                                 WfActivityInternal blockActivity) throws BaseException, ToolAgentGeneralException {
800       // if activity is already activated (the case when XOR Join is reached twice or
801
// more times, before activity is executed), do nothing
802
if (isActivityDefinitionActive(t,activity,blockActivity)) {
803          SharkEngineManager.getInstance().getCallbackUtilities().warn("Activity "+activity+" is already started - can't start it twice");
804          return;
805       }
806
807       WfActivityInternal act = SharkEngineManager
808          .getInstance()
809          .getObjectFactory()
810          .createActivity(t, this, getNextWorkItemId(activity.getId()), asDefId, activity.getId(), blockActivity);
811       SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - Activity"+act.toString()+" is created");
812       addToActiveActivities(t,activity,act);
813
814       try {
815          //System.out.println("Activating act "+act);
816
act.activate(t);
817          //System.out.println("Finished activation of act "+act);
818
String JavaDoc causeClassName=null;
819          // handling block activity start and exc. handling
820
if (activity.getActivityType()==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
821             try {
822                runBlock(t,activity,act);
823             } catch (ToolAgentGeneralException ex) {
824                causeClassName=SharkUtilities.extractExceptionName(ex);
825                act.setExceptionName(t,causeClassName);
826                act.setToolAgentException(t,ex);
827             }
828          } else {
829             causeClassName=act.getExceptionName(t);
830          }
831
832          if (causeClassName!=null) {
833             if (getExceptionTransFrom(t,act,activity,causeClassName).size()==0) {
834                ToolAgentGeneralException tage=act.getToolAgentException(t);
835                if (tage!=null) {
836                   throw act.getToolAgentException(t);
837                } else {
838                   throw new BaseException("Unexpected exception from WfProcessImpl.startActivity()");
839                }
840             }
841          }
842       } catch (AlreadyRunning ar) {
843          throw new BaseException(ar);
844       } catch (CannotStart e) {
845          throw new BaseException(e);
846       }
847    }
848
849    /**
850     * Receives notification when an activity has completed.
851     */

852    public void activity_complete(SharkTransaction t, WfActivityInternal activity) throws Exception JavaDoc {
853       SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - Activity"+activity.toString()+" is completed.");
854
855       //System.out.println("Activity "+activity+" signals its completion");
856
lastFinishedActivities.add(activity);
857
858       getActiveActivitiesMap(t).remove(activity.key(t));
859
860       if (!isRunning) {
861          //System.out.println("Calling run after completion of Activity "+activity);
862
run(t, activity);
863          //System.out.println("Run after completion of Activity "+activity+"finished");
864
}
865       //System.out.println("Returning to the caller after completion of Activity "+activity+"finished");
866
//SharkServer.getLogger().error("Process"+toString()+" - Exception while completing activity");
867
}
868
869    /**
870     * Receives notification when an activity has terminated.
871     */

872    public void activity_terminate(SharkTransaction t, WfActivityInternal activity) throws Exception JavaDoc {
873       SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - Activity"+activity.toString()+" is terminated.");
874
875       lastFinishedActivities.add(activity);
876       
877       getActiveActivitiesMap(t).remove(activity.key(t));
878       // FIXING BUG WHEN DEADLINE HAPPENS ON BLOCK ACTIVITY
879
Activity activityDefinition=
880          SharkUtilities.
881          getActivityDefinition(t, activity,getProcessDefinition(t), activity.block_activity(t));
882       if (activityDefinition.getActivityType()==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
883          List JavaDoc bas=getAllActiveActivitiesForBlockActivity(t, activity.key(t));
884          Iterator JavaDoc it=bas.iterator();
885          while (it.hasNext()) {
886             WfActivityInternal baMember=(WfActivityInternal)it.next();
887             getActiveActivitiesMap(t).remove(baMember.key(t));
888          }
889       }
890       
891       if (!isRunning) {
892          run(t, activity);
893       }
894    }
895
896    /**
897     * Receives notification when an activity has aborted.
898     */

899    public void activity_abort(SharkTransaction t, WfActivityInternal activity) throws Exception JavaDoc {
900       if (!activity.state(t).equals(SharkConstants.STATE_CLOSED_ABORTED)) {
901          throw new Exception JavaDoc("Activity state is not aborted");
902       }
903       SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - Aborting activity"+activity.toString());
904
905       getActiveActivitiesMap(t).remove(activity.key(t));
906    }
907
908    // Queues the next activities for processing
909
protected void queueNext(SharkTransaction t, WfActivityInternal fromActivity) throws BaseException, ToolAgentGeneralException {
910       //System.err.println("QUEINGNEXT FOR "+fromActivity);
911
// try {
912
WorkflowProcess wp=getProcessDefinition(t);
913       Activity aDef=SharkUtilities.getActivityDefinition(t, fromActivity, wp, fromActivity.block_activity(t));
914       Activities activityDefs;
915       Transitions transitions;
916       // the next transitions from 'fromActivity'
917
List JavaDoc nextTrans;
918       WfActivityInternal blockActivity=fromActivity.block_activity(t);
919       ActivitySet aSet=null;
920       String JavaDoc asDefId=null;
921       if (blockActivity!=null) {
922          aSet=(ActivitySet)aDef.getParent().getParent();
923          asDefId=aSet.getId();
924          activityDefs=aSet.getActivities();
925          transitions=aSet.getTransitions();
926          // all transitions from activity
927
} else {
928          activityDefs=wp.getActivities();
929          transitions=wp.getTransitions();
930       }
931       String JavaDoc causeClassName=fromActivity.getExceptionName(t);
932       boolean checkIfSomethingWrong=true;
933       if (causeClassName==null) {
934          nextTrans=getTransFrom(t,fromActivity,aDef);
935          //System.out.println("NEXTTRANS="+nextTrans);
936
} else {
937          nextTrans=getExceptionTransFrom(t,fromActivity,aDef,causeClassName);
938          //System.out.println("ETs="+nextTrans);
939
if (nextTrans.size()==0) {
940             if (blockActivity!=null && blockActivity.getToolAgentException(t)!=null) {
941                nextTrans=new ArrayList JavaDoc();
942                checkIfSomethingWrong=false;
943             } else {
944                ToolAgentGeneralException tage=blockActivity.getToolAgentException(t);
945                if (tage!=null) {
946                   throw tage;
947                } else {
948                   throw new BaseException("Unexpected exception from WfProcessImpl.queryNext()");
949                }
950             }
951          }
952       }
953
954       // if something went wrong
955
if (checkIfSomethingWrong && nextTrans.size()==0) {
956          //System.out.println("CSW ts0");
957
XMLCollectionElement wpOrASet=wp;
958          if (aSet!=null) {
959             wpOrASet=aSet;
960          }
961          List JavaDoc endingActDefs=null;
962          if (wpOrASet instanceof WorkflowProcess) {
963             endingActDefs=((WorkflowProcess)wpOrASet).getEndingActivities();
964             //System.out.println("ead1="+endingActDefs);
965
} else {
966             endingActDefs=((ActivitySet)wpOrASet).getEndingActivities();
967             //System.out.println("ead2="+endingActDefs);
968
}
969          if (!endingActDefs.contains(aDef)) {
970             String JavaDoc unsatSplitHandling=
971                SharkEngineManager
972                .getInstance()
973                .getCallbackUtilities()
974                .getProperty("SharkKernel.UnsatisfiedSplitConditionsHandling",
975                             SharkConstants.UNSATISFIED_SPLIT_CONDITIONS_HANDLING_FINISH_IF_POSSIBLE);
976             if (unsatSplitHandling.equals(SharkConstants.UNSATISFIED_SPLIT_CONDITIONS_HANDLING_IGNORE)) {
977                SharkEngineManager.getInstance().getCallbackUtilities().warn("Process "+this+" could hang forever in "+fromActivity+" branch, after this activity is finished");
978                return;
979             } else if (unsatSplitHandling.equals(SharkConstants.UNSATISFIED_SPLIT_CONDITIONS_HANDLING_ROLLBACK)) {
980                throw new BaseException("Shark kernel is configured not to allow hanging processes!");
981             } else {
982                // Do nothing - process/block will finish if it can
983
SharkEngineManager.getInstance().getCallbackUtilities().error("Process "+this+" will try to finish after "+fromActivity+" is executed because kernel is configured not to allow hanging and not to rollback");
984             }
985          }
986       }
987
988       if (nextTrans.size() > 0) {
989          //System.out.println("NTS="+nextTrans.size());
990
Iterator JavaDoc it=nextTrans.iterator();
991          while (it.hasNext()) {
992             Transition trans=(Transition)it.next();
993             // Get the activity definition
994
Activity toActivityDef=trans.getToActivity();
995             if (!toActivityDef.isAndTypeJoin() || toActivityDef.getIncomingTransitions().size()==1) {
996                //System.out.println("SA");
997
startActivity(t,asDefId,toActivityDef,blockActivity);
998             } else {
999                //System.out.println("JT");
1000
joinTransition(t,fromActivity,toActivityDef,asDefId);
1001            }
1002         }
1003      } else {
1004         // find if there are active activities in some other branches
1005

1006         // if there are other active activities, do nothing, and if this
1007
// is the last activity within activity set, finish block activity
1008
List JavaDoc actActs=getActiveActivities(t);
1009         //System.out.println("Act acts are "+actActs);
1010
if (actActs.size()>0) {
1011            if (blockActivity!=null) {
1012               for (int i=0; i<actActs.size(); i++) {
1013                  //try {
1014
java.lang.Object JavaDoc ba = getActiveActivity(t,((WfActivityInternal)actActs.get(i)).block_activity_id(t));
1015                  if (ba!=null && ba.equals(blockActivity)) {
1016                     //System.out.println("AA is BA");
1017
return;
1018                  }
1019               }
1020               // the activity set has no more transitions, finish the block activity
1021
try {
1022                  //System.out.println("FBA");
1023
blockActivity.finish(t);
1024               } catch (Exception JavaDoc ex) {
1025                  throw new BaseException("Something went wrong while finishing block activity "+blockActivity,ex);
1026               }
1027               return;
1028            }
1029         } else {
1030            // if this is end of Activity Set, finish the block activity
1031
if (aSet!=null) {
1032               try {
1033                  if (blockActivity.state(t).startsWith(SharkConstants.STATEPREFIX_CLOSED)){
1034                     // this can happen if we have implicit AND split within
1035
// the fully automatic block
1036
//System.out.println("BASCL");
1037
return;
1038                  }
1039                  //System.out.println("FBA2");
1040
blockActivity.finish(t);
1041               } catch (Exception JavaDoc ex) {
1042                  throw new BaseException("Something went wrong while finishing block activity "+blockActivity,ex);
1043               }
1044               return;
1045               // otherwise, finish the process
1046
} else {
1047               //System.out.println("LFAS="+lastFinishedActivities);
1048
if (lastFinishedActivities.size()<=1) {
1049                  SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - No transitions left to follow");
1050
1051                  try {
1052                     change_state(t,SharkConstants.STATE_CLOSED_COMPLETED);
1053                  } catch (Exception JavaDoc ex) {
1054                     throw new BaseException("Something went wrong while changing process state to closed.completed",ex);
1055                  }
1056               }
1057            }
1058         }
1059      }
1060      /* } catch (Throwable tr) {
1061       SharkEngineManager.getInstance().getCallbackUtilities().error("Process"+toString()+" - error while querying");
1062       throw new BaseException("Problems while querying",tr);
1063       }*/

1064   }
1065
1066   // Follows the and-join transition
1067
protected void joinTransition(SharkTransaction t,
1068                                 WfActivityInternal fromActivity,
1069                                 Activity toActivityDef,
1070                                 String JavaDoc asDefId) throws BaseException, ToolAgentGeneralException {
1071
1072
1073      // get all incoming transitions to this activity
1074
List JavaDoc toTrans=toActivityDef.getIncomingTransitions();
1075
1076      int followed=restoreActivityToFollowedTransitionsMap(t,toActivityDef,asDefId);
1077
1078      SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - "+(followed+1)+" of "+toTrans.size()+" transitions followed to activity with definition "+toActivityDef.getId());
1079
1080      // check to see if all transition requirements are met
1081
if (toTrans.size()==followed+1) {
1082         SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - All transition have been followed to activity with definition "+toActivityDef.getId());
1083         Set JavaDoc currentTrans=(Set JavaDoc)newActivityToFollowedTransitions.get(toActivityDef);
1084         if (currentTrans!=null && currentTrans.size()==followed) { // just remove from map - this is all performed in one transaction
1085
newActivityToFollowedTransitions.remove(toActivityDef);
1086         } else { // mark for delete
1087
if (currentTrans!=null) {
1088               currentTrans.clear();
1089            } else {
1090               newActivityToFollowedTransitions.put(toActivityDef,currentTrans);
1091            }
1092         }
1093         //lastFinishedActivities.removeAll(followedActs);
1094
activityToFollowedTransitions.put(toActivityDef,new Integer JavaDoc(0));
1095         try {
1096            persistActivityToFollowedTransitions(t);
1097         } catch (Exception JavaDoc ex) {
1098            throw new BaseException(ex);
1099         }
1100         startActivity(t,asDefId,toActivityDef,getActiveActivity(t, fromActivity.block_activity_id(t)));
1101      } else {
1102         activityToFollowedTransitions.put(toActivityDef,new Integer JavaDoc(followed+1));
1103         Set JavaDoc currentTrans=(Set JavaDoc)newActivityToFollowedTransitions.get(toActivityDef);
1104         if (currentTrans==null) {
1105            currentTrans=new HashSet JavaDoc();
1106            newActivityToFollowedTransitions.put(toActivityDef,currentTrans);
1107         }
1108         currentTrans.add(fromActivity.key(t));
1109         try {
1110            persistActivityToFollowedTransitions(t);
1111         } catch (Exception JavaDoc ex) {
1112            throw new BaseException(ex);
1113         }
1114         //System.err.println("[WfProcess.joinTransition] : Waiting for transitions to finish.");
1115
}
1116   }
1117
1118   // Returns transitions to the next activity or activities to execute, based
1119
// on transition conditions, and split type of fromActivity
1120
// EXCEPTION and DEFAULTEXCEPTION transitions are not returned
1121
protected List JavaDoc getTransFrom(SharkTransaction t,
1122                               WfActivityInternal fromActivity,
1123                               Activity fromActDef) throws BaseException {
1124
1125      List JavaDoc orderedOutTransitions=fromActDef.getNonExceptionalOutgoingTransitions();
1126      List JavaDoc transList = new ArrayList JavaDoc();
1127
1128      boolean isAndSplit=fromActDef.isAndTypeSplit();
1129      Transition otherwiseTransition = null;
1130
1131      Iterator JavaDoc transitions=orderedOutTransitions.iterator();
1132
1133      while (transitions.hasNext()) {
1134         Transition trans=(Transition)transitions.next();
1135         Condition condition = trans.getCondition();
1136         String JavaDoc condType=condition.getType();
1137         if(condType.equals(XPDLConstants.CONDITION_TYPE_OTHERWISE)){
1138            otherwiseTransition = trans;
1139            boolean handleOtherwiseTransitionLast=new Boolean JavaDoc(
1140                  SharkEngineManager.
1141                     getInstance().
1142                     getCallbackUtilities().
1143                     getProperty("SharkKernel.handleOtherwiseTransitionLast","false")).booleanValue();
1144            if (!isAndSplit && !handleOtherwiseTransitionLast) {
1145               break;
1146            } else {
1147               continue;
1148            }
1149         }
1150         boolean evalRes=false;
1151         // user process_context() - we must pass cloned variables
1152
String JavaDoc cond=condition.toValue();
1153         if (cond.trim().length()==0) {
1154            evalRes=true;
1155         } else {
1156            try {
1157               evalRes=evaluator(t).evaluateCondition(t,cond,process_context(t));
1158            } catch (Exception JavaDoc ex) {
1159               throw new BaseException("Exception while evaluating transition condition",ex);
1160            }
1161         }
1162         if(evalRes){
1163            transList.add(trans);
1164            if (!isAndSplit) {
1165               break;
1166            }
1167         }
1168      }
1169
1170      // use otherwise transitions if that is the only one transition
1171
// or if no other transition condition is evaluated to true
1172
// NOTE: this depends on configuration how to handle OTHERWISE transition
1173
if (transList.size() == 0 && otherwiseTransition != null) {
1174         transList.add(otherwiseTransition);
1175         SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - process is proceeding with otherwise transition of Activity"+fromActivity);
1176      }
1177      //System.err.println("[WfProcess.getTransFrom] : Transitions: " + transList.size());
1178

1179      return transList;
1180   }
1181
1182   // Returns exception transition where the process has to go based on
1183
// exception thrown from tool agent
1184
protected List JavaDoc getExceptionTransFrom(SharkTransaction t,
1185                                        WfActivityInternal fromActivity,
1186                                        Activity fromActDef,
1187                                        String JavaDoc exceptionName) throws BaseException {
1188
1189      List JavaDoc outTransitions=fromActDef.getExceptionalOutgoingTransitions();
1190      List JavaDoc transList = new ArrayList JavaDoc();
1191
1192      if (outTransitions.size()==0) return transList;
1193
1194      Transition excTransition = null;
1195      Transition defaultExceptionTransition = null;
1196      Iterator JavaDoc transitions=outTransitions.iterator();
1197
1198      while (transitions.hasNext()) {
1199         Transition trans=(Transition)transitions.next();
1200         Condition condition = trans.getCondition();
1201         String JavaDoc condType=condition.getType();
1202         if(condType.equals(XPDLConstants.CONDITION_TYPE_DEFAULTEXCEPTION)){
1203            defaultExceptionTransition = trans;
1204            continue;
1205         }
1206         boolean evalRes=false;
1207         String JavaDoc cond=condition.toValue();
1208         if (cond.length()==0) {
1209            evalRes=true;
1210         } else {
1211            evalRes=cond.equals(exceptionName);
1212         }
1213         if(evalRes){
1214            excTransition=trans;
1215            break;
1216         }
1217      }
1218
1219      // if there is no exception transition found, and there is no
1220
// default exception transition, try to evaluate conditions
1221
if (excTransition==null && defaultExceptionTransition==null) {
1222         transitions=outTransitions.iterator();
1223         while (transitions.hasNext()) {
1224            Transition trans=(Transition)transitions.next();
1225            Condition condition = trans.getCondition();
1226            boolean evalRes=false;
1227            String JavaDoc cond=condition.toValue();
1228            try {
1229               evalRes=evaluator(t).evaluateCondition(t,cond,process_context(t));
1230            } catch (Exception JavaDoc ex) {
1231               // System.out.println("Condition is not satisfied");
1232
}
1233            if(evalRes){
1234               excTransition=trans;
1235               break;
1236            }
1237         }
1238      }
1239
1240      // use default exception transitions if that is the only one transition
1241
if (excTransition == null && defaultExceptionTransition != null) {
1242         excTransition=defaultExceptionTransition;
1243         SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - process is proceeding with default exception transition of Activity"+fromActivity);
1244      }
1245      //System.err.println("[WfProcess.getTransFrom] : Transitions: " + transList.size());
1246
if (excTransition!=null) {
1247         transList.add(excTransition);
1248      }
1249      return transList;
1250   }
1251
1252   protected void notifyRequester (SharkTransaction t,WfEventAudit event) throws BaseException {
1253      SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - notifying requester of the event");
1254      WfRequesterInternal req=requester(t);
1255// SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - requester found");
1256

1257      if (req != null) {
1258         try {
1259            WfActivityInternal aReq=null;
1260            if (req instanceof WfActivityInternal) {
1261               aReq=(WfActivityInternal)req;
1262            }
1263            if (aReq==null) {
1264               req.receive_event(t,event,this);
1265//SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - ext requester notified");
1266
} else {
1267               // if the requester activity is closed - do not notify it
1268
if ((event instanceof WfStateEventAudit) && aReq.state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
1269                  aReq.receive_event(t,event,this);
1270//SharkEngineManager.getInstance().getCallbackUtilities().info("Process"+toString()+" - act requester notified");
1271
}
1272            }
1273         } catch (InvalidPerformer ip) {
1274            throw new BaseException(ip);
1275         }
1276      }
1277   }
1278   
1279   /**
1280    * Puts the workflow relevant data and formal parameters into process context.
1281    * All data is put into context by id-value pairs.
1282    * The initial value of WRD is set if exist, or default value otherwise.
1283    * The formal parameters are also initialized to the default values.
1284    */

1285   protected void initializeProcessContext(SharkTransaction t) throws BaseException {
1286      // get all data fields (from package, and from process)
1287
processContext=new HashMap JavaDoc();
1288      WorkflowProcess wp=getProcessDefinition(t);
1289      Collection JavaDoc dfsAndFPs=wp.getAllVariables().values();
1290      Iterator JavaDoc itDfs=dfsAndFPs.iterator();
1291      while (itDfs.hasNext()) {
1292         XMLCollectionElement dfOrFp=(XMLCollectionElement)itDfs.next();
1293         Object JavaDoc initVal=SharkUtilities.getInitialValue(dfOrFp,false);
1294         String JavaDoc id=dfOrFp.getId();
1295         //out.println("putting "+dfOrFp.getClass().getName()+" "+id+"into context");
1296
processContext.put(id,initVal);
1297      }
1298   }
1299
1300   /**
1301    * Get the next work item ID. Each work item will have a unique ID.
1302    * @return The work item ID string
1303    */

1304   protected String JavaDoc getNextWorkItemId(String JavaDoc aDefId) throws BaseException {
1305      String JavaDoc id = SharkUtilities.getNextId(SharkConstants.ACTIVITY_ID_NAME);
1306      id=id+"_"+key+"_"+aDefId;
1307      if (id.length()>100) id=id.substring(0,100);
1308      return id;
1309   }
1310
1311   public String JavaDoc toString () {
1312      return "[key="+key+",mgrname="+managerName+"]";
1313   }
1314
1315   /**
1316    * It is assumed that there can't be two or more
1317    * processes having the same key.
1318    */

1319   public boolean equals (java.lang.Object JavaDoc obj) {
1320      if (!(obj instanceof WfProcessImpl)) return false;
1321      return ((WfProcessImpl)obj).key.equals(key);
1322   }
1323
1324   /**
1325    * Returns if there is an active activity for given definition.
1326    */

1327   protected boolean isActivityDefinitionActive (SharkTransaction t,Activity aDef,WfActivityInternal blockActivity) throws BaseException {
1328      String JavaDoc aDefId=aDef.getId();
1329      Iterator JavaDoc it=getActiveActivities(t).iterator();
1330      while (it.hasNext()) {
1331         WfActivityInternal act=(WfActivityInternal)it.next();
1332         if (act.activity_definition_id(t).equals(aDefId) &&
1333                (act.state(t).equals(SharkConstants.STATE_OPEN_RUNNING) ||
1334                    act.state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED))) {
1335
1336            if ((blockActivity!=null && blockActivity.key(t).equals(act.block_activity_id(t))) ||
1337                   (blockActivity==null && act.block_activity_id(t)==null)) {
1338               return true;
1339            }
1340         }
1341      }
1342      return false;
1343   }
1344
1345   /*private WfActivityInternal getLastFinishedActivityForDefinition (SharkTransaction t, Activity actDef) throws BaseException {
1346    WfActivityInternal lfa=null;
1347    Iterator iter=getActivityList(t).iterator();
1348    long maxTime=-1;
1349    while (iter.hasNext()) {
1350    try {
1351    WfActivityInternal act = (WfActivityInternal)iter.next();
1352    Activity aDef=SharkUtilities.getActivityDefinition(t,act,getProcessDefinition(t));
1353    if (aDef.equals(actDef) &&
1354    (act.state(t).equals(SharkConstants.STATE_CLOSED_COMPLETED) || act.state(t).equals(SharkConstants.STATE_CLOSED_TERMINATED))) {
1355    long eTime=act.last_state_time(t).time;
1356    if (maxTime<eTime) {
1357    maxTime=eTime;
1358    lfa=act;
1359    }
1360    }
1361    } catch (Exception ex) {
1362    //ex.printStackTrace();
1363    }
1364    }
1365    return lfa;
1366    }*/

1367
1368   /* *
1369    * Used when restoring engine from database.
1370    * @param vdId The workflow relevant data or formal parameter definition Id
1371    * @param val The value of WRD or FP
1372    */

1373   /*private void restoreContextVariable (String vdId,String val) throws BaseException {
1374    XMLCollectionElement dfOrFp=((DataFields)getProcessDefinition().
1375    get("DataFields")).getDataField(vdId);
1376    if (dfOrFp==null) {
1377    dfOrFp=((FormalParameters)getProcessDefinition().
1378    get("FormalParameters")).getFormalParameter(vdId);
1379    }
1380    if (dfOrFp!=null) {
1381    Object anyVal=SharkWrapperUtilities.getValue(dfOrFp,val);
1382    getProcessContext().put(vdId,anyVal);
1383    }
1384    }*/

1385
1386   protected void setProcessVariables (SharkTransaction t) throws BaseException {
1387      try {
1388         //System.out.println("SPVCVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV");
1389
// initialize context, just to keep the order of variables
1390
processContext=new HashMap JavaDoc();
1391   
1392         PersistentManagerInterface ipm = SharkEngineManager.getInstance()
1393         .getInstancePersistenceManager();
1394
1395         WorkflowProcess wp=getProcessDefinition(t);
1396         List JavaDoc l=new ArrayList JavaDoc(wp.getAllVariables().values());
1397         if (l.size()==0) return;
1398         //System.err.println("INIT PC="+processContext);
1399
Iterator JavaDoc it=l.iterator();
1400         List JavaDoc variableIds=new ArrayList JavaDoc();
1401         while (it.hasNext()) {
1402            XMLCollectionElement dfOrFp=(XMLCollectionElement)it.next();
1403            String JavaDoc vdId=dfOrFp.getId();
1404            variableIds.add(vdId);
1405         }
1406         l=ipm.getProcessVariables(key, variableIds, t);
1407         it=l.iterator();
1408         while (it.hasNext()) {
1409            ProcessVariablePersistenceInterface var=(ProcessVariablePersistenceInterface)it.next();
1410            //System.out.println("Restoring proc var "+var.getDefinitionId()+", val="+var.getValue());
1411
//if (anyVal!=null) {
1412
processContext.put(var.getDefinitionId(),var.getValue());
1413            //}
1414
}
1415      } catch (Exception JavaDoc ex) {
1416         throw new BaseException ("Restoring of process context failed!",ex);
1417      }
1418   }
1419   
1420   protected WorkflowProcess getProcessDefinition (SharkTransaction t) throws BaseException {
1421      if (xpdlProcess==null) {
1422         xpdlProcess=SharkUtilities.getWorkflowProcess(pkgId,mgrVer,pDefId);
1423      }
1424      return xpdlProcess;
1425   }
1426
1427   public void persist(SharkTransaction t) throws TransactionException {
1428      try {
1429         //System.err.println("The proc "+this+" is being persisted with thread "+Thread.currentThread());
1430
//System.err.println("The proc "+key+" is being persisted:");
1431
SharkEngineManager
1432            .getInstance()
1433            .getInstancePersistenceManager()
1434            .persist(createAndFillPersistentObject(), justCreated, t);
1435         //persistProcessContext(t);
1436
//persistActivityToFollowedTransitions(t);
1437
this.justCreated=false;
1438      } catch (Exception JavaDoc pe) {
1439         //pe.printStackTrace();
1440
throw new TransactionException("Exc when persisting process "+key,pe);
1441      }
1442   }
1443
1444   protected void persistProcessContext (SharkTransaction t) throws BaseException {
1445      try {
1446         if (variableIdsToPersist.size()==0) return;
1447         PersistentManagerInterface pmgr = SharkEngineManager
1448            .getInstance()
1449            .getInstancePersistenceManager();
1450         //System.out.println("Persisting proc var map="+getContext(t));
1451
Iterator JavaDoc it=getContext(t).entrySet().iterator();
1452         while (it.hasNext()) {
1453            Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
1454            String JavaDoc defId=(String JavaDoc)me.getKey();
1455            if (variableIdsToPersist.contains(defId)) {
1456               Object JavaDoc val=me.getValue();
1457               ProcessVariablePersistenceInterface var= pmgr.createProcessVariable();
1458               var.setProcessId(key);
1459               var.setDefinitionId(defId);
1460               var.setValue(val);
1461               //System.out.println("Persisting process variable "+defId+", val="+val+" for proc "+key);
1462
pmgr.persist(var, justCreatedVariables, t);
1463            }
1464         }
1465         variableIdsToPersist.clear();
1466         this.justCreatedVariables=false;
1467      } catch (PersistenceException pe) {
1468         throw new BaseException(pe);
1469      }
1470   }
1471
1472   public void delete (SharkTransaction t) throws TransactionException {
1473      //if (isDeleted) return;
1474
// try {System.err.println("Deleting process "+key);}catch (Exception ex){};
1475
//System.err.println("I'm going to delete activities "+getActivityList());
1476

1477      try {
1478         //deleteProcessContext();
1479

1480         //Iterator it=getActivityList(t).iterator();
1481
/*Iterator it=getAllActivities(t).iterator();
1482          while (it.hasNext()) {
1483          ((WfActivityInternal)it.next()).delete(t);
1484          }*/

1485         //activeActivitiesMap=null;
1486
SharkEngineManager
1487            .getInstance()
1488            .getInstancePersistenceManager()
1489            .deleteProcess(key,false,t);
1490
1491         //if (processContext!=null) processContext.clear();
1492
//System.out.println("Removing process "+key+" from cache");
1493
SharkUtilities.removeProcessFromCache(t,this);
1494         //isDeleted=true;
1495
//System.out.println("Deleting of process "+key+" finished");
1496
} catch (Exception JavaDoc ex) {
1497         //ex.printStackTrace();
1498
throw new TransactionException("Exception while deleting process", ex);
1499      }
1500   }
1501
1502   public void mandatoryDelete (SharkTransaction t) throws TransactionException {
1503      try {
1504         SharkEngineManager
1505            .getInstance()
1506            .getInstancePersistenceManager()
1507            .deleteProcess(key,true,t);
1508
1509         SharkUtilities.removeProcessFromCache(t,this);
1510      } catch (Exception JavaDoc ex) {
1511         throw new TransactionException("Exception while deleting process", ex);
1512      }
1513   }
1514
1515   /*protected void deleteProcessContext () throws TransactionException {
1516    try {
1517    PersistentManagerInterface pm=SharkEngineManager.getInstance().getPersistentManager();
1518    Iterator it=getContext().keySet().iterator();
1519    while (it.hasNext()) {
1520    String defId=(String)it.next();
1521    ProcessVariablePersistenceInterface var=pm.createProcessVariable();
1522
1523    var.setProcessId(key);
1524    var.setDefinitionId(defId);
1525    pm.delete(var,SharkEngineManager.getTransaction());
1526    }
1527    } catch (Exception ex) {
1528    throw new TransactionException("Exception while deleting process context");
1529    }
1530    }*/

1531
1532   protected XMLCollectionElement getXPDLObject (SharkTransaction t) throws BaseException {
1533      return getProcessDefinition(t);
1534   }
1535
1536   public Map JavaDoc getContext (SharkTransaction t) throws BaseException {
1537      if (processContext==null) {
1538         setProcessVariables(t);
1539      }
1540      return processContext;
1541   }
1542
1543   public Evaluator evaluator (SharkTransaction t) throws RootException {
1544      if (evaluator==null) {
1545         evaluator= SharkEngineManager
1546            .getInstance()
1547            .getScriptingManager()
1548            .getEvaluator(t,SharkUtilities.getScriptType(pkgId,mgrVer));
1549      }
1550      return evaluator;
1551   }
1552
1553   private ProcessPersistenceInterface createAndFillPersistentObject () {
1554      ProcessPersistenceInterface po=
1555         SharkEngineManager.getInstance().getInstancePersistenceManager().createProcess();
1556      fillPersistentObject(po);
1557      return po;
1558   }
1559
1560   private void fillPersistentObject (ProcessPersistenceInterface po) {
1561      po.setId(this.key);
1562      po.setActivityRequesterId(this.actRequesterId);
1563      po.setActivityRequestersProcessId(this.actRequestersProcessId);
1564      po.setResourceRequesterId(this.resRequesterId);
1565      po.setExternalRequesterClassName(this.externalRequesterClassName);
1566      po.setState(this.state);
1567      po.setLastStateTime(this.lastStateTime);
1568      po.setCreatedTime(this.creationTime);
1569      po.setStartedTime(this.startTime);
1570      po.setProcessMgrName(managerName);
1571      po.setName(this.name);
1572      po.setDescription(this.description);
1573      po.setPriority(this.priority);
1574      po.setLimitTime(limitTime);
1575   }
1576
1577   private void restore (ProcessPersistenceInterface po) {
1578      this.key=po.getId();
1579      this.actRequesterId=po.getActivityRequesterId();
1580      this.actRequestersProcessId=po.getActivityRequestersProcessId();
1581      this.resRequesterId=po.getResourceRequesterId();
1582      this.externalRequesterClassName=po.getExternalRequesterClassName();
1583      this.state=po.getState();
1584      this.lastStateTime = po.getLastStateTime();
1585      this.creationTime = po.getCreatedTime();
1586      this.startTime = po.getStartedTime();
1587      this.managerName=po.getProcessMgrName();
1588      this.name=po.getName();
1589      this.description=po.getDescription();
1590      this.priority=po.getPriority();
1591      this.limitTime=po.getLimitTime();
1592      
1593      setXPDLAttribs();
1594   }
1595
1596   public final String JavaDoc package_id(SharkTransaction t) throws BaseException {
1597      return pkgId;
1598   }
1599
1600   public WfActivityInternal getActiveActivity (SharkTransaction t, String JavaDoc actId) throws BaseException {
1601      return (WfActivityInternal)getActiveActivitiesMap(t).get(actId);
1602   }
1603
1604   protected Map JavaDoc getActiveActivitiesMap (SharkTransaction t) throws BaseException {
1605      if (activeActivitiesMap==null) {
1606         clearTmpActiveActivityMap();
1607         try {
1608            SharkEngineManager sharkEngineManager=SharkEngineManager.getInstance();
1609            List JavaDoc l=sharkEngineManager.getInstancePersistenceManager().getAllActiveActivitiesForProcess(key, t);
1610            activeActivitiesMap=new HashMap JavaDoc();
1611            for (int i=0; i<l.size(); i++) {
1612               ActivityPersistenceInterface po=(ActivityPersistenceInterface)l.get(i);
1613               WfActivityInternal act=sharkEngineManager.
1614                  getObjectFactory().
1615                  createActivity(po,this);
1616               activeActivitiesMap.put(po.getId(),act);
1617            }
1618            //System.err.println("AllProcesses for mgr "+mgr.getProcessDefinitionId()+" are "+ret);
1619

1620         } catch (Exception JavaDoc ex) {
1621            throw new BaseException(ex);
1622         }
1623
1624      }
1625      return activeActivitiesMap;
1626   }
1627
1628   protected void clearTmpActiveActivityMap () {
1629      if (tmpActivitiesMap!=null) {
1630         tmpActivitiesMap.clear();
1631      }
1632   }
1633
1634   protected WfActivityInternal getTmpActivity (String JavaDoc actId) {
1635      if (tmpActivitiesMap==null) {
1636         tmpActivitiesMap=new HashMap JavaDoc();
1637      }
1638      return (WfActivityInternal)tmpActivitiesMap.get(actId);
1639   }
1640
1641   protected void addToTmpActivitiesMap (String JavaDoc actId,WfActivityInternal act) {
1642      if (tmpActivitiesMap==null) {
1643         tmpActivitiesMap=new HashMap JavaDoc();
1644      }
1645      tmpActivitiesMap.put(actId,act);
1646   }
1647
1648   public List JavaDoc getActiveActivities (SharkTransaction t) throws BaseException {
1649      return new ArrayList JavaDoc(getActiveActivitiesMap(t).values());
1650   }
1651
1652   public java.util.List JavaDoc getAllActivities (SharkTransaction t) throws BaseException {
1653      try {
1654         clearTmpActiveActivityMap();
1655         SharkEngineManager sharkEngineManager=SharkEngineManager.getInstance();
1656         List JavaDoc l=sharkEngineManager.getInstancePersistenceManager().getAllActivitiesForProcess(key, t);
1657         List JavaDoc ret=new ArrayList JavaDoc();
1658         Map JavaDoc tmpActActivitiesMap=new HashMap JavaDoc();
1659         for (int i=0; i<l.size(); i++) {
1660            ActivityPersistenceInterface po=(ActivityPersistenceInterface)l.get(i);
1661            WfActivityInternal act=null;
1662            if (activeActivitiesMap!=null) {
1663               act=getActiveActivity(t,po.getId());
1664            }
1665            if (act==null) {
1666               act=sharkEngineManager.getObjectFactory().createActivity(po,this);
1667            }
1668            if (activeActivitiesMap==null) {
1669               if (!po.getState().startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
1670                  tmpActActivitiesMap.put(po.getId(),act);
1671               }
1672            }
1673            ret.add(act);
1674         }
1675         if (activeActivitiesMap==null) {
1676            activeActivitiesMap=new HashMap JavaDoc(tmpActActivitiesMap);
1677         }
1678         //System.err.println("AllProcesses for mgr "+mgr.getProcessDefinitionId()+" are "+ret);
1679
return ret;
1680      } catch (Exception JavaDoc ex) {
1681         throw new BaseException(ex);
1682      }
1683   }
1684
1685   public WfActivityInternal getActivity (SharkTransaction t, String JavaDoc actId) throws BaseException {
1686      try {
1687         WfActivityInternal act=null;
1688         if (activeActivitiesMap!=null) {
1689            act=getActiveActivity(t,actId);
1690         } else {
1691            act=getTmpActivity(actId);
1692         }
1693
1694         if (act==null) {
1695            ActivityPersistenceInterface po=SharkEngineManager
1696               .getInstance()
1697               .getInstancePersistenceManager()
1698               .restoreActivity(actId,t);
1699            if (po!=null) {
1700               act=SharkEngineManager.getInstance().getObjectFactory().createActivity(po,this);
1701               addToTmpActivitiesMap(actId,act);
1702            }
1703         }
1704         return act;
1705      } catch (Exception JavaDoc ex) {
1706         throw new BaseException(ex);
1707      }
1708   }
1709
1710   public final long getCreationTime (SharkTransaction t) throws BaseException {
1711      return creationTime;
1712   }
1713
1714   public final long getStartTime (SharkTransaction t) throws BaseException {
1715      return startTime;
1716   }
1717
1718   private void setXPDLAttribs () {
1719      this.pkgId=SharkUtilities.getProcessMgrPkgId(this.managerName);
1720      this.pDefId=SharkUtilities.getProcessMgrProcDefId(this.managerName);
1721      this.mgrVer=SharkUtilities.getProcessMgrVersion(this.managerName);
1722   }
1723
1724   protected int restoreActivityToFollowedTransitionsMap (SharkTransaction t,Activity actDef,String JavaDoc asDefId) throws BaseException {
1725      Integer JavaDoc followed=(Integer JavaDoc)activityToFollowedTransitions.get(actDef);
1726      if (followed==null) {
1727         PersistentManagerInterface pmi=SharkEngineManager.getInstance().getInstancePersistenceManager();
1728         int noOfFollowed=0;
1729         try {
1730            noOfFollowed=pmi.howManyAndJoinEntries(key,
1731                                                   asDefId,
1732                                                   actDef.getId(),
1733                                                   t);
1734         } catch (Exception JavaDoc ex) {
1735            throw new BaseException (ex);
1736         }
1737         // get a list of followed transition to this activity
1738
followed=new Integer JavaDoc(noOfFollowed);
1739         activityToFollowedTransitions.put(actDef,followed);
1740      }
1741      return followed.intValue();
1742   }
1743
1744   protected void persistActivityToFollowedTransitions (SharkTransaction t) throws TransactionException {
1745      PersistentManagerInterface pmi=SharkEngineManager.getInstance().getInstancePersistenceManager();
1746      Iterator JavaDoc it=newActivityToFollowedTransitions.entrySet().iterator();
1747      while (it.hasNext()) {
1748         Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
1749         Activity actDef=(Activity)me.getKey();
1750         String JavaDoc asDefId=null;
1751         Object JavaDoc asOrWp=actDef.getParent().getParent();
1752         if (asOrWp instanceof ActivitySet) {
1753            asDefId=((ActivitySet)asOrWp).getId();
1754         }
1755         Set JavaDoc actInstances=(Set JavaDoc)me.getValue();
1756         if (actInstances==null || actInstances.size()==0) {
1757            try {
1758               pmi.deleteAndJoinEntries(key,asDefId,actDef.getId(),t);
1759            } catch (Exception JavaDoc ex) {
1760               throw new TransactionException(ex);
1761            }
1762         } else {
1763            Iterator JavaDoc aInst=actInstances.iterator();
1764            while (aInst.hasNext()) {
1765               String JavaDoc actId=(String JavaDoc)aInst.next();
1766               AndJoinEntryInterface aji=pmi.createAndJoinEntry();
1767               aji.setProcessId(key);
1768               aji.setActivitySetDefinitionId(asDefId);
1769               aji.setActivityDefinitionId(actDef.getId());
1770               aji.setActivityId(actId);
1771               try {
1772                  pmi.persist(aji,t);
1773               } catch (Exception JavaDoc ex) {
1774                  throw new TransactionException (ex);
1775               }
1776
1777            }
1778         }
1779      }
1780      newActivityToFollowedTransitions.clear();
1781   }
1782
1783   // Runs a BLOCK activity
1784
protected void runBlock(SharkTransaction t,Activity bActivity,WfActivityInternal blockActivity) throws BaseException, ToolAgentGeneralException {
1785      BlockActivity ba=bActivity.getActivityTypes().getBlockActivity();
1786      if (ba!=null) {
1787         String JavaDoc asId=ba.getBlockId();
1788         ActivitySet as=XMLUtil.getWorkflowProcess(bActivity).getActivitySet(asId);
1789         if (as!=null) {
1790            List JavaDoc starts=as.getStartingActivities();
1791            for (Iterator JavaDoc it=starts.iterator(); it.hasNext();) {
1792               Activity act=(Activity)it.next();
1793               startActivity(t,asId,act,blockActivity);
1794            }
1795         }
1796      }
1797   }
1798
1799   protected void addToActiveActivities (SharkTransaction t,Activity aDef,WfActivityInternal act) throws BaseException{
1800      getActiveActivitiesMap(t).put(act.key(t),act);
1801   }
1802
1803   public void checkDeadlines (SharkTransaction t) throws BaseException {
1804      // check only open.running processes
1805
if (!state(t).equals(SharkConstants.STATE_OPEN_RUNNING)) return;
1806
1807      List JavaDoc activeActs=getActiveActivities(t);
1808      long timeLimitBoundary=System.currentTimeMillis();
1809      Map JavaDoc actToExcNames=new HashMap JavaDoc();
1810      for (int i=0; i<activeActs.size(); i++) {
1811         WfActivityInternal act=(WfActivityInternal)activeActs.get(i);
1812         if (act.block_activity_id(t)==null) {
1813
1814            Map JavaDoc ataens=new HashMap JavaDoc();
1815            boolean syncDeadlineHappened=act.checkDeadlines(t,timeLimitBoundary,ataens);
1816
1817            if (syncDeadlineHappened) {
1818               continue;
1819            }
1820
1821            if (ataens!=null || ataens.size()>0) {
1822               actToExcNames.putAll(ataens);
1823            }
1824         }
1825      }
1826      if (actToExcNames.size()>0) {
1827         handleBrokenAsyncDeadlines(t,actToExcNames);
1828      }
1829   }
1830
1831   public void checkDeadline (SharkTransaction t,String JavaDoc actId) throws BaseException {
1832      // check only open.running processes
1833
if (!state(t).equals(SharkConstants.STATE_OPEN_RUNNING)) return;
1834
1835      WfActivityInternal act=getActiveActivity(t,actId);
1836      if (act==null) throw new BaseException("There is no active activity with Id="+actId+" within the process with Id="+key);
1837      Map JavaDoc actToExcNames=new HashMap JavaDoc();
1838      boolean syncDeadlineHappened=act.checkDeadlines(t,System.currentTimeMillis(),actToExcNames);
1839      if (syncDeadlineHappened) {
1840         //addToPersistenceList(act);
1841
}
1842      if (actToExcNames!=null && actToExcNames.size()>0) {
1843         handleBrokenAsyncDeadlines(t,actToExcNames);
1844      }
1845   }
1846
1847   private void handleBrokenAsyncDeadlines(SharkTransaction t,Map JavaDoc actToExcNames) throws BaseException {
1848      WorkflowProcess wp=getProcessDefinition(t);
1849      Iterator JavaDoc excs=actToExcNames.entrySet().iterator();
1850      while (excs.hasNext()) {
1851         Map.Entry JavaDoc me=(Map.Entry JavaDoc)excs.next();
1852         WfActivityInternal act=(WfActivityInternal)me.getKey();
1853         List JavaDoc excNames=(List JavaDoc)me.getValue();
1854         WfActivityInternal blockActivity=act.block_activity(t);
1855         Activity aDef=SharkUtilities.getActivityDefinition(t,act,wp,blockActivity);
1856         List JavaDoc resultingTransitions=new ArrayList JavaDoc();
1857         for (Iterator JavaDoc it=excNames.iterator(); it.hasNext();) {
1858            List JavaDoc ets=getExceptionTransFrom(t,act,aDef,(String JavaDoc)it.next());
1859            Iterator JavaDoc itets=ets.iterator();
1860            while (itets.hasNext()) {
1861               Object JavaDoc trans=itets.next();
1862               if (!resultingTransitions.contains(trans)) {
1863                  resultingTransitions.add(trans);
1864               }
1865            }
1866         }
1867         for (Iterator JavaDoc it=resultingTransitions.iterator(); it.hasNext();) {
1868            Transition trans=(Transition)it.next();
1869            try {
1870               Activity actToDef=trans.getToActivity();
1871               String JavaDoc asDefId=null;
1872               Object JavaDoc owner=actToDef.getParent().getParent();
1873               if (owner instanceof ActivitySet) {
1874                  asDefId=((ActivitySet)owner).getId();
1875               }
1876               startActivity(t,asDefId,actToDef,blockActivity);
1877            } catch (ToolAgentGeneralException tage) {
1878               throw new BaseException(tage);
1879            }
1880         }
1881      }
1882   }
1883
1884   public List JavaDoc getAllActiveActivitiesForBlockActivity (SharkTransaction t,String JavaDoc blockActivityId) throws BaseException {
1885      List JavaDoc allActiveActivities=getActiveActivities(t);
1886      Iterator JavaDoc it=allActiveActivities.iterator();
1887      List JavaDoc ret=new ArrayList JavaDoc();
1888      while (it.hasNext()) {
1889         WfActivityInternal act=(WfActivityInternal)it.next();
1890         if (blockActivityId.equals(act.block_activity_id(t))) {
1891            ret.add(act);
1892         }
1893      }
1894      return ret;
1895   }
1896
1897   protected void notifyStart (SharkTransaction t,Map JavaDoc context,long runtime) throws BaseException {
1898      LimitAgentManager mgr = SharkEngineManager.getInstance().getLimitAgentManager();
1899      try {
1900         mgr.notifyStart(key,null,context,runtime);
1901      } catch (LimitAgentException e) {
1902         throw new BaseException("Unable to register time limit for process "+this+" with limit agent",e);
1903      }
1904   }
1905
1906}
1907
1908
1909
1910
Popular Tags