KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.enhydra.shark;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.Collections JavaDoc;
5 import java.util.Comparator JavaDoc;
6 import java.util.HashMap JavaDoc;
7 import java.util.HashSet JavaDoc;
8 import java.util.Iterator JavaDoc;
9 import java.util.List JavaDoc;
10 import java.util.Map JavaDoc;
11 import java.util.Set JavaDoc;
12
13 import org.enhydra.shark.api.ParticipantMappingTransaction;
14 import org.enhydra.shark.api.RootException;
15 import org.enhydra.shark.api.SharkTransaction;
16 import org.enhydra.shark.api.TransactionException;
17 import org.enhydra.shark.api.UserTransaction;
18 import org.enhydra.shark.api.client.wfbase.BaseException;
19 import org.enhydra.shark.api.client.wfmodel.AlreadyRunning;
20 import org.enhydra.shark.api.client.wfmodel.AlreadySuspended;
21 import org.enhydra.shark.api.client.wfmodel.CannotAcceptSuspended;
22 import org.enhydra.shark.api.client.wfmodel.CannotComplete;
23 import org.enhydra.shark.api.client.wfmodel.CannotResume;
24 import org.enhydra.shark.api.client.wfmodel.CannotStart;
25 import org.enhydra.shark.api.client.wfmodel.CannotStop;
26 import org.enhydra.shark.api.client.wfmodel.CannotSuspend;
27 import org.enhydra.shark.api.client.wfmodel.InvalidData;
28 import org.enhydra.shark.api.client.wfmodel.InvalidPerformer;
29 import org.enhydra.shark.api.client.wfmodel.InvalidState;
30 import org.enhydra.shark.api.client.wfmodel.NotRunning;
31 import org.enhydra.shark.api.client.wfmodel.NotSuspended;
32 import org.enhydra.shark.api.client.wfmodel.ResultNotAvailable;
33 import org.enhydra.shark.api.client.wfmodel.TransitionNotAllowed;
34 import org.enhydra.shark.api.client.wfmodel.UpdateNotAllowed;
35 import org.enhydra.shark.api.client.wfmodel.WfDataEventAudit;
36 import org.enhydra.shark.api.client.wfmodel.WfEventAudit;
37 import org.enhydra.shark.api.client.wfmodel.WfRequester;
38 import org.enhydra.shark.api.common.DeadlineInfo;
39 import org.enhydra.shark.api.common.SharkConstants;
40 import org.enhydra.shark.api.internal.assignment.PerformerData;
41 import org.enhydra.shark.api.internal.instancepersistence.ActivityPersistenceInterface;
42 import org.enhydra.shark.api.internal.instancepersistence.ActivityVariablePersistenceInterface;
43 import org.enhydra.shark.api.internal.instancepersistence.AssignmentPersistenceInterface;
44 import org.enhydra.shark.api.internal.instancepersistence.DeadlinePersistenceInterface;
45 import org.enhydra.shark.api.internal.instancepersistence.PersistenceException;
46 import org.enhydra.shark.api.internal.instancepersistence.PersistentManagerInterface;
47 import org.enhydra.shark.api.internal.limitagent.LimitAgentException;
48 import org.enhydra.shark.api.internal.limitagent.LimitAgentManager;
49 import org.enhydra.shark.api.internal.partmappersistence.ParticipantMap;
50 import org.enhydra.shark.api.internal.partmappersistence.ParticipantMappingManager;
51 import org.enhydra.shark.api.internal.scripting.Evaluator;
52 import org.enhydra.shark.api.internal.toolagent.ToolAgentGeneralException;
53 import org.enhydra.shark.api.internal.usergroup.UserGroupManager;
54 import org.enhydra.shark.api.internal.working.ToolAgentManager;
55 import org.enhydra.shark.api.internal.working.WfActivityInternal;
56 import org.enhydra.shark.api.internal.working.WfAssignmentInternal;
57 import org.enhydra.shark.api.internal.working.WfProcessInternal;
58 import org.enhydra.shark.api.internal.working.WfProcessMgrInternal;
59 import org.enhydra.shark.api.internal.working.WfResourceInternal;
60 import org.enhydra.shark.utilities.MiscUtilities;
61 import org.enhydra.shark.xpdl.XMLCollectionElement;
62 import org.enhydra.shark.xpdl.XMLComplexElement;
63 import org.enhydra.shark.xpdl.XMLUtil;
64 import org.enhydra.shark.xpdl.XPDLConstants;
65 import org.enhydra.shark.xpdl.elements.Activity;
66 import org.enhydra.shark.xpdl.elements.ActualParameter;
67 import org.enhydra.shark.xpdl.elements.ActualParameters;
68 import org.enhydra.shark.xpdl.elements.Deadline;
69 import org.enhydra.shark.xpdl.elements.FormalParameter;
70 import org.enhydra.shark.xpdl.elements.FormalParameters;
71 import org.enhydra.shark.xpdl.elements.Participant;
72 import org.enhydra.shark.xpdl.elements.Responsible;
73 import org.enhydra.shark.xpdl.elements.SubFlow;
74 import org.enhydra.shark.xpdl.elements.WorkflowProcess;
75
76 /**
77  * WfActivityImpl - Workflow Activity Object implementation
78  * @author Sasa Bojanic
79  * @author Vladimir Puskas
80  */

81 public class WfActivityImpl extends WfExecutionObjectImpl implements WfActivityInternal {
82
83    private String JavaDoc mgrName;
84    private String JavaDoc processId;
85
86    private Activity activityDefinition;
87    private WorkflowProcess processDefinition;
88    private String JavaDoc activitySetDefinitionId;
89    private String JavaDoc activityDefinitionId;
90
91    private String JavaDoc blockActivityId;
92
93    private boolean accepted=false;
94    private String JavaDoc resourceUsername;
95
96    private Map JavaDoc activitiesProcessContext;
97
98    // for implementation of requester interface
99
private String JavaDoc performerId;
100    private boolean isSubflowSynchronous=true;
101
102    // holds Ids of variables that make activity results - only those variables will be
103
// returned to the process context when activity finishes
104
private Set JavaDoc resultVariableIds;
105
106    private Evaluator evaluator;
107
108    private WfProcessInternal process;
109
110    private long acceptedTime=Long.MAX_VALUE/2;
111
112    private long activatedTime=Long.MAX_VALUE/2;
113
114    protected List JavaDoc assignmentResourceIds;
115
116    protected Set JavaDoc variableIdsToPersist=new HashSet JavaDoc();
117
118    //private ToolRunner myToolRunner;
119

120    protected Thread JavaDoc startSubflowThread=null;
121
122    //protected boolean deleteAssignments=false;
123

124    protected WfActivityInternal blockActivity=null;
125
126    protected ToolAgentGeneralException toolAgentException=null;
127    protected String JavaDoc exceptionName=null;
128    protected List JavaDoc deadlinesInfo;
129
130    private boolean justCreated=false;
131    private boolean justCreatedVariables=false;
132    private boolean justCreatedDeadlines=false;
133
134    /**
135     * Create a new WfActivityImpl
136     */

137    protected WfActivityImpl(SharkTransaction t,
138                             WfProcessInternal process,
139                             String JavaDoc key,
140                             String JavaDoc activitySetDefId,
141                             String JavaDoc activityDefId,
142                             WfActivityInternal blockActivity) throws BaseException {
143       this.mgrName=process.manager_name(t);
144       this.processId=process.key(t);
145       this.key=key;
146       this.process=process;
147       this.activityDefinitionId=activityDefId;
148       this.blockActivity=blockActivity;
149       this.justCreated=true;
150       this.justCreatedVariables=true;
151       this.justCreatedDeadlines=true;
152       // initialize process definition
153
WorkflowProcess wp=getProcessDefinition(t);
154       if (this.blockActivity!=null) {
155          this.blockActivityId=this.blockActivity.key(t);
156          this.activitySetDefinitionId=activitySetDefId;
157       }
158       // initializing activity definition
159
getActivityDefinition(t);
160       name=activityDefinition.getName();
161       if (name.equals("")) {
162          name=getActivityDefinition(t).getId();
163       }
164       description=activityDefinition.getDescription();
165       if (description!=null && description.length()>254) {
166          description=description.substring(0,253);
167       }
168       try {
169          priority=Integer.valueOf(activityDefinition.getPriority()).shortValue();
170       } catch (Exception JavaDoc ex) {
171          priority=3;
172       }
173       lastStateTime = System.currentTimeMillis();
174
175       lastStateEventAudit=SharkEngineManager.
176          getInstance().
177          getObjectFactory().
178          createStateEventAuditWrapper(t,
179                                       this,
180                                       SharkConstants.EVENT_ACTIVITY_STATE_CHANGED,
181                                       null,
182                                       state);
183
184       activitiesProcessContext=getActivityContext(t);
185       resultVariableIds=new HashSet JavaDoc();
186       if (activitiesProcessContext.size()>0) {
187          variableIdsToPersist.addAll(getContext(t).keySet());
188          if (SharkEngineManager.getInstance().getEventAuditManager()!=null) {
189             SharkEngineManager.
190                getInstance().
191                getObjectFactory().
192                createDataEventAuditWrapper(t,
193                                            this,
194                                            SharkConstants.EVENT_ACTIVITY_CONTEXT_CHANGED,
195                                            null,
196                                            new HashMap JavaDoc(activitiesProcessContext));
197          }
198       }
199
200       assignmentResourceIds=new ArrayList JavaDoc();
201
202    }
203
204    /**
205     * Used to create object when restoring it from database.
206     */

207    protected WfActivityImpl (ActivityPersistenceInterface po,WfProcessInternal proc) {
208       this.process=proc;
209       restore(po);
210    }
211
212    public List JavaDoc getAssignmentResourceIds (SharkTransaction t) throws BaseException {
213       if (assignmentResourceIds==null) {
214          try {
215             assignmentResourceIds=new ArrayList JavaDoc();
216             boolean createAssignments=Boolean.valueOf(
217                   SharkEngineManager.
218                   getInstance().
219                   getCallbackUtilities().
220                   getProperty("SharkKernel.createAssignments","true")).booleanValue();
221             if (createAssignments) {
222                List JavaDoc l=SharkEngineManager
223                   .getInstance()
224                   .getInstancePersistenceManager().getAllAssignmentsForActivity(key,t);
225                for (int i=0; i<l.size(); i++) {
226                   AssignmentPersistenceInterface po=(AssignmentPersistenceInterface)l.get(i);
227                   assignmentResourceIds.add(po.getResourceUsername());
228                }
229             }
230          } catch (Exception JavaDoc ex) {
231             throw new BaseException(ex);
232          }
233       }
234       return assignmentResourceIds;
235    }
236
237    /**
238     * Getter for the process of this activity.
239     */

240    public WfProcessInternal container (SharkTransaction t) throws BaseException {
241       return process;
242    }
243
244    /**
245     * Retrieve the Result map of this activity.
246     * @return Map of results from this activity
247     */

248    public Map JavaDoc result (SharkTransaction t) throws BaseException, ResultNotAvailable {
249       Map JavaDoc resultMap=new HashMap JavaDoc();
250       //System.out.println("Updating process with the variables "+getChangedContextVariableIds(t));
251
Iterator JavaDoc it=resultMap(t).entrySet().iterator();
252       while (it.hasNext()) {
253          Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
254          try {
255             resultMap.put(me.getKey(),MiscUtilities.cloneWRD(me.getValue()));
256          } catch (Throwable JavaDoc thr) {
257             throw new BaseException(thr);
258          }
259       }
260       return resultMap;
261    }
262
263    private Map JavaDoc resultMap (SharkTransaction t) throws BaseException {
264       Map JavaDoc resultMap=new HashMap JavaDoc();
265       //System.out.println("Updating process with the variables "+getChangedContextVariableIds(t));
266
Iterator JavaDoc it=getResultVariableIds(t).iterator();
267       while (it.hasNext()) {
268          java.lang.Object JavaDoc vId=it.next();
269          resultMap.put(vId,getContext(t).get(vId));
270       }
271       return resultMap;
272    }
273
274    /**
275     * Assign Result for this activity.
276     */

277    public void set_result (SharkTransaction t,Map JavaDoc results) throws BaseException, InvalidData {
278       try {
279          setProcessContext(t,results,SharkConstants.EVENT_ACTIVITY_RESULT_CHANGED);
280       } catch (InvalidData id) {
281          SharkEngineManager.getInstance().getCallbackUtilities().error("Activity"+toString()+" - failed to set the activity result");
282          throw id;
283       } catch (BaseException be) {
284          SharkEngineManager.getInstance().getCallbackUtilities().error("Activity"+toString()+" - failed to set the activity result");
285          throw be;
286       } catch (Exception JavaDoc ex) {
287          throw new BaseException(ex);
288       }
289    }
290
291    public void complete (SharkTransaction t) throws BaseException, CannotComplete {
292       // get the type of this activity
293
int type=getActivityDefinition(t).getActivityType();
294       switch (type) {
295          case XPDLConstants.ACTIVITY_TYPE_ROUTE: // Route
296
throw new BaseException("Subflow activity can be finished only automatically");
297             //this.finish(t); // ROUTE goes directly to complete status
298
case XPDLConstants.ACTIVITY_TYPE_NO: // NoImplementation
299
// NOTE: when using JaWE's code for XPDL handling, we never
300
// have this activity type. NO type is representet by
301
// TOOL type with zero tools
302
this.finish(t); // NO impl goes directly to complete status
303
break;
304          case XPDLConstants.ACTIVITY_TYPE_TOOL: // Tools
305
int hmt=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getTools().size();
306             // if there is no tool -> the same as No implementation
307
if (hmt>0) {
308                if (getActivityDefinition(t).getActivityStartMode()==XPDLConstants.ACTIVITY_MODE_MANUAL) {
309                   boolean shouldFinishImmediatelly=getActivityDefinition(t).getActivityFinishMode()==XPDLConstants.ACTIVITY_MODE_AUTOMATIC;
310                   try {
311                      if (shouldFinishImmediatelly || getAssignmentResourceIds(t).size()>0) {
312                         this.runTool(t);
313                      }
314                   } catch (Exception JavaDoc ex) {
315                      if (ex instanceof ToolAgentGeneralException) {
316                         toolAgentException=(ToolAgentGeneralException)ex;
317                         finishImproperlyAndNotifyProcess(t,
318                                                          SharkUtilities.extractExceptionName(toolAgentException));
319
320                         return;
321                      } else {
322                         throw new BaseException(ex);
323                      }
324                   }
325                   if (shouldFinishImmediatelly || getAssignmentResourceIds(t).size()==0) {
326                      finish(t);
327                   } else {
328                      // delete assignments
329
removeAssignments(t, true, true);
330                   }
331                   return;
332                   // the case when start mode is AUTOMATIC, but finish mode is MANUAL
333
} else {
334                   finish(t);
335                }
336                //throw new BaseException("When the start mode is automatic, Tool activity can be finished automatically");
337
/*if (getStartMode()==WfActivityImpl.AUTOMATIC_MODE &&
338                 getFinishMode()==WfActivityImpl.MANUAL_MODE) {
339                 return;
340                 }*/

341                // check the finish mode
342
//this.finish(t); // this should never happen->tool agents should directly call finish()
343

344                //}
345
} else {
346                this.finish(t); // NO impl goes directly to complete status
347
}
348             break;
349          case XPDLConstants.ACTIVITY_TYPE_SUBFLOW: // SubFlow
350
throw new BaseException("Subflow activity can be finished only automatically");
351             //this.finish(t); // Subflow act. goes directly to complete status
352
//break;
353
case XPDLConstants.ACTIVITY_TYPE_BLOCK: // BlockActivity
354
throw new BaseException("Block activity can be finished only automatically");
355             //this.finish(t); // Block act. goes directly to complete status
356
//break;
357
}
358    }
359
360    /**
361     * Complete this activity.
362     */

363    public void finish (SharkTransaction t) throws BaseException, CannotComplete {
364       try {
365
366          // remove assignments first, because method for getting assignments
367
// from database depends on activity's state
368
removeAssignments(t, true, true);
369
370          change_state(t,SharkConstants.STATE_CLOSED_COMPLETED);
371          process.set_process_context(t,resultMap(t));
372
373          process.activity_complete(t,this);
374
375       } catch (InvalidState is) {
376          throw new CannotComplete(is);
377       } catch (TransitionNotAllowed tna) {
378          throw new CannotComplete(tna);
379       } catch (InvalidData e) {
380          throw new CannotComplete("Invalid result data was passed");
381       } catch (ResultNotAvailable rne) {
382          throw new CannotComplete("Result of activity is not available");
383       } catch (UpdateNotAllowed una) {
384          throw new CannotComplete("Process context update is not allowed");
385       } catch (Exception JavaDoc ex) {
386          if (ex instanceof BaseException) {
387             throw (BaseException)ex;
388          } else {
389             throw new BaseException(ex);
390          }
391       }
392    }
393
394    protected void change_state (SharkTransaction t,String JavaDoc new_state) throws BaseException, InvalidState, TransitionNotAllowed {
395       //System.out.println("Act "+this+" Curr st is "+state(t)+", new state is "+new_state+", valid states are "+SharkUtilities.valid_activity_states(state(t)));
396
if (!SharkUtilities.valid_activity_states(state(t)).contains(new_state)) {
397          throw new TransitionNotAllowed("Current state is "+state+", can't change to state "+new_state+"!");
398       }
399
400       // persist changes to activity state
401
String JavaDoc oldState=state;
402       state=new_state;
403
404       lastStateTime = System.currentTimeMillis();
405       try {
406          persist(t);
407       } catch (TransactionException te) {
408          throw new BaseException(te);
409       }
410       lastStateEventAudit=SharkEngineManager.
411          getInstance().
412          getObjectFactory().
413          createStateEventAuditWrapper(t,
414                                       this,
415                                       SharkConstants.EVENT_ACTIVITY_STATE_CHANGED,
416                                       oldState,
417                                       new_state);
418       // cancel the limit agent when we enter closed state
419
if (state.startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
420          LimitAgentManager mgr = SharkEngineManager.getInstance().getLimitAgentManager();
421          if (mgr != null) {
422             try {
423                mgr.notifyStop(processId,key);
424             } catch (LimitAgentException e) {
425                throw new BaseException(e);
426             }
427          }
428       }
429
430    }
431
432    public void set_process_context (SharkTransaction t,Map JavaDoc new_value) throws BaseException, InvalidData, UpdateNotAllowed {
433       try {
434          setProcessContext(t,new_value,SharkConstants.EVENT_ACTIVITY_CONTEXT_CHANGED);
435       } catch (InvalidData id) {
436          throw id;
437       } catch (UpdateNotAllowed una) {
438          throw una;
439       } catch (BaseException be) {
440          throw be;
441       } catch (Exception JavaDoc ex) {
442          throw new BaseException(ex);
443       }
444    }
445
446    private void setProcessContext (SharkTransaction t,Map JavaDoc newValue,String JavaDoc eventType)
447       throws BaseException, InvalidData, UpdateNotAllowed, Exception JavaDoc {
448       if (newValue==null) {
449          throw new BaseException("new value is null");
450       }
451       Map JavaDoc oldValues=new HashMap JavaDoc();
452       Map JavaDoc newChanged=new HashMap JavaDoc();
453       Iterator JavaDoc it=newValue.entrySet().iterator();
454       while (it.hasNext()) {
455          Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
456          String JavaDoc id=(String JavaDoc)me.getKey();
457          Object JavaDoc val= me.getValue();
458
459          //if (val==null) continue;
460
if (getContext(t).containsKey(id)) {
461             Object JavaDoc oldVal=getContext(t).get(id);
462             //type checking
463
if (SharkUtilities.checkDataType(t,getProcessDefinition(t),id,oldVal,val)) {
464                //System.out.println("var "+id+"["+oldVal+","+val+"]");
465
if ((oldVal!=null && !oldVal.equals(val)) || (oldVal==null && val!=null)) {
466                   oldValues.put(id,oldVal);
467                   newChanged.put(id,val);
468                }
469             } else {
470                throw new InvalidData("Invalid data type for activity variable "+id);
471             }
472          } else {
473             //System.err.println("The variable "+id+" is not in the context");
474
throw new UpdateNotAllowed("Context attribute "+id+" does not exist in the activity context - adding new attributes to activity context is not allowed");
475          }
476       }
477       if (newChanged.size()>0 || eventType.equals(SharkConstants.EVENT_ACTIVITY_RESULT_CHANGED)) {
478          getContext(t).putAll(newChanged);
479          Map JavaDoc toPersist=new HashMap JavaDoc(newChanged);
480          Map JavaDoc newSRVars=null;
481          if (eventType.equals(SharkConstants.EVENT_ACTIVITY_RESULT_CHANGED)) {
482             newSRVars=new HashMap JavaDoc();
483             Set JavaDoc oldRVIds=new HashSet JavaDoc(getResultVariableIds(t));
484             getResultVariableIds(t).addAll(newValue.keySet());
485             Set JavaDoc newRVIds=new HashSet JavaDoc(getResultVariableIds(t));
486             newRVIds.removeAll(oldRVIds);
487             Iterator JavaDoc itRV=newRVIds.iterator();
488             while (itRV.hasNext()) {
489                String JavaDoc id=(String JavaDoc)itRV.next();
490                Object JavaDoc val=getContext(t).get(id);
491                toPersist.put(id,val);
492                newSRVars.put(id,val);
493             }
494          }
495
496          variableIdsToPersist.addAll(toPersist.keySet());
497          persistActivityContext(t);
498          if (newChanged.size()>0) {
499             if (SharkEngineManager.getInstance().getEventAuditManager()!=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                SharkEngineManager.getInstance().getObjectFactory().
509                   createDataEventAuditWrapper(t,this,SharkConstants.EVENT_ACTIVITY_CONTEXT_CHANGED,oldValues,newChanged);
510             }
511          }
512          if (newSRVars!=null && newSRVars.size()>0) {
513             if (SharkEngineManager.getInstance().getEventAuditManager()!=null) {
514                boolean persistOldEventAuditData=new Boolean JavaDoc(
515                      SharkEngineManager
516                         .getInstance()
517                         .getCallbackUtilities()
518                         .getProperty("PERSIST_OLD_EVENT_AUDIT_DATA","true")).booleanValue();
519                if (!persistOldEventAuditData) {
520                   oldValues=null;
521                }
522                SharkEngineManager.getInstance().getObjectFactory().
523                   createDataEventAuditWrapper(t,this,eventType,null,newSRVars);
524             }
525          }
526       }
527    }
528
529    /**
530     * Resume this process or activity.
531     */

532    public void resume (SharkTransaction t) throws BaseException, CannotResume, NotSuspended {
533       int type=getActivityDefinition(t).getActivityType();
534
535       // try {
536
if (!state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
537          throw new NotSuspended("Can't resume activity that is not suspended");
538       }
539       if (process.state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
540          throw new CannotResume("Can't resume activity which process is suspended");
541       }
542       if (blockActivityId!=null && block_activity(t).state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
543          throw new CannotResume("Can't resume activity which block is suspended");
544       }
545
546       try {
547          if (accepted || type==XPDLConstants.ACTIVITY_TYPE_BLOCK || type==XPDLConstants.ACTIVITY_TYPE_SUBFLOW) {
548             change_state(t,SharkConstants.STATE_OPEN_RUNNING);
549          } else {
550             change_state(t,SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED);
551          }
552       } catch (Exception JavaDoc ex) {
553          throw new CannotResume(ex);
554       }
555
556       if (type==XPDLConstants.ACTIVITY_TYPE_SUBFLOW) {
557          // if this is a subflow activity, resume it's process
558
// if it is SYNCHRONOUS
559
if (isSubflowSynchronous) {
560             WfProcessInternal performer=getPerformer(t);
561             if (performer==null) {
562                SubFlow subflow=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
563                String JavaDoc refSbflw=subflow.getId();
564                WorkflowProcess wp=SharkUtilities.getWorkflowProcess(subflow,refSbflw);
565                if (wp!=null || performerId!=null) {
566                   throw new BaseException("Null performer of sync. subflow activity");
567                }
568
569                try {
570                   SharkEngineManager.getInstance().getWfEngineInteroperabilityMgr().resume(t,performerId,processId,SharkUtilities.createAssignmentKey(key,getResourceRequesterUsername(t)));
571                } catch (Exception JavaDoc ex) {
572                   throw new BaseException(ex);
573                }
574
575             } else {
576                if (performer.state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
577                   performer.resume(t);
578                }
579             }
580          }
581       } else if (type==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
582          List JavaDoc actActs=process.getAllActiveActivitiesForBlockActivity(t,key);
583          Iterator JavaDoc it=actActs.iterator();
584          while (it.hasNext()) {
585             WfActivityInternal act=(WfActivityInternal)it.next();
586             if (act.state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
587                act.resume(t);
588             }
589          }
590       }
591
592    }
593
594    /**
595     * Suspend this process or activity.
596     */

597    public void suspend(SharkTransaction t) throws BaseException, CannotSuspend, NotRunning, AlreadySuspended {
598       if (state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
599          throw new AlreadySuspended("The activity is already suspended - can't suspend it twice!");
600       }
601
602       try {
603          change_state(t,SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED);
604       } catch (Exception JavaDoc ex) {
605          throw new CannotSuspend(ex);
606       }
607
608
609       int type=getActivityDefinition(t).getActivityType();
610       if (type==XPDLConstants.ACTIVITY_TYPE_SUBFLOW) {
611          // if this is a subflow activity, suspend it's process
612
// if it is SYNCHRONOUS
613
if (isSubflowSynchronous) {
614             WfProcessInternal performer=getPerformer(t);
615             if (performer==null) {
616                SubFlow subflow=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
617                String JavaDoc refSbflw=subflow.getId();
618                WorkflowProcess wp=SharkUtilities.getWorkflowProcess(subflow,refSbflw);
619                if (wp!=null || performerId!=null) {
620                   throw new BaseException("Null performer of sync. subflow activity");
621                }
622
623                try {
624                   SharkEngineManager.getInstance().getWfEngineInteroperabilityMgr().suspend(t,performerId,processId,SharkUtilities.createAssignmentKey(key,getResourceRequesterUsername(t)));
625                } catch (Exception JavaDoc ex) {
626                   throw new BaseException(ex);
627                }
628
629
630             } else {
631                String JavaDoc perfState=performer.state(t);
632                if (perfState.startsWith(SharkConstants.STATEPREFIX_OPEN) &&
633                    !perfState.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
634                   performer.suspend(t);
635                }
636             }
637          }
638       } else if (type==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
639          List JavaDoc actActs=process.getAllActiveActivitiesForBlockActivity(t,key);
640          Iterator JavaDoc it=actActs.iterator();
641          while (it.hasNext()) {
642             WfActivityInternal act=(WfActivityInternal)it.next();
643             String JavaDoc actState=act.state(t);
644             if (actState.startsWith(SharkConstants.STATEPREFIX_OPEN) &&
645                 !actState.equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
646                act.suspend(t);
647             }
648          }
649       }
650
651    }
652
653    /**
654     * Terminate this process or activity.
655     */

656    public void terminateFromProcess (SharkTransaction t) throws BaseException, CannotStop, NotRunning {
657       terminateActivity(t,true);
658    }
659    /**
660     * Terminate this process or activity.
661     */

662    public void terminate(SharkTransaction t) throws BaseException, CannotStop, NotRunning {
663       terminateActivity(t,false);
664    }
665
666    protected void terminateActivity (SharkTransaction t,boolean fromProcess) throws BaseException, CannotStop, NotRunning {
667       String JavaDoc stateStr = SharkConstants.STATE_CLOSED_TERMINATED;
668       if (!state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
669          throw new CannotStop("The activity is already in the closed state - can't terminate it!");
670       }
671
672       // remove assignments first, because method for getting assignments
673
// from database depends on activity's state
674
removeAssignments(t, true, true);
675
676       try {
677          change_state(t,stateStr);
678       }catch (Exception JavaDoc ex) {
679          throw new CannotStop(ex);
680       }
681
682       int type=getActivityDefinition(t).getActivityType();
683       if (type==XPDLConstants.ACTIVITY_TYPE_SUBFLOW) {
684          // if this is a subflow activity, terminate it's process
685
// if it is SYNCHRONOUS
686
if (isSubflowSynchronous) {
687             WfProcessInternal performer=getPerformer(t);
688             if (performer==null) {
689                SubFlow subflow=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
690                String JavaDoc refSbflw=subflow.getId();
691                WorkflowProcess wp=SharkUtilities.getWorkflowProcess(subflow,refSbflw);
692                if (wp!=null || performerId!=null) {
693                   throw new BaseException("Null performer of sync. subflow activity");
694                }
695
696                try {
697                   SharkEngineManager.getInstance().getWfEngineInteroperabilityMgr().terminate(t,performerId,processId,SharkUtilities.createAssignmentKey(key,getResourceRequesterUsername(t)));
698                } catch (Exception JavaDoc ex) {
699                   throw new BaseException(ex);
700                }
701
702             } else {
703                if (performer.state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
704                   performer.terminateFromActivity(t);
705                }
706             }
707          }
708       } else if (type==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
709          List JavaDoc actActs=process.getAllActiveActivitiesForBlockActivity(t,key);
710          Iterator JavaDoc it=actActs.iterator();
711          while (it.hasNext()) {
712             WfActivityInternal act=(WfActivityInternal)it.next();
713             if (act.state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
714                act.terminateFromProcess(t);
715             }
716          }
717       }
718
719       if (!fromProcess) {
720          try {
721             process.activity_terminate(t,this);
722          } catch (Exception JavaDoc ex) {
723             throw new BaseException(ex);
724          }
725       }
726    }
727
728    public void abortFromProcess (SharkTransaction t) throws BaseException, CannotStop, NotRunning {
729       abortActivity(t,true);
730    }
731
732    /**
733     * Abort the execution of this process or activity.
734     */

735    public void abort(SharkTransaction t) throws BaseException, CannotStop, NotRunning {
736       abortActivity(t,false);
737    }
738
739    protected void abortActivity (SharkTransaction t,boolean fromProcess) throws BaseException, CannotStop, NotRunning {
740       String JavaDoc stateStr = SharkConstants.STATE_CLOSED_ABORTED;
741       if (!state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
742          throw new CannotStop("The activity is already in the closed state - can't abort it!");
743       }
744
745       // remove assignments first, because method for getting assignments
746
// from database depends on activity's state
747
removeAssignments(t, true, true);
748
749       try {
750          change_state(t,stateStr);
751       } catch (Exception JavaDoc ex) {
752          throw new CannotStop(ex);
753       }
754
755       int type=getActivityDefinition(t).getActivityType();
756       if (type==XPDLConstants.ACTIVITY_TYPE_SUBFLOW) {
757          // if this is a subflow activity, abort it's process
758
// if it is SYNCHRONOUS
759
if (isSubflowSynchronous) {
760             WfProcessInternal performer=getPerformer(t);
761             if (performer==null) {
762                SubFlow subflow=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
763                String JavaDoc refSbflw=subflow.getId();
764                WorkflowProcess wp=SharkUtilities.getWorkflowProcess(subflow,refSbflw);
765                if (wp!=null || performerId!=null) {
766                   throw new BaseException("Null performer of sync. subflow activity");
767                }
768
769                try {
770                   SharkEngineManager.getInstance().getWfEngineInteroperabilityMgr().abort(t,performerId,processId,SharkUtilities.createAssignmentKey(key,getResourceRequesterUsername(t)));
771                } catch (Exception JavaDoc ex) {
772                   throw new BaseException(ex);
773                }
774
775             } else {
776                if (performer.state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
777                   performer.abortFromActivity(t);
778                }
779             }
780          }
781       } else if (type==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
782          List JavaDoc actActs=process.getAllActiveActivitiesForBlockActivity(t,key);
783          Iterator JavaDoc it=actActs.iterator();
784          while (it.hasNext()) {
785             WfActivityInternal act=(WfActivityInternal)it.next();
786             if (act.state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
787                act.abortFromProcess(t);
788             }
789          }
790       }
791
792       if (!fromProcess) {
793          try {
794             process.activity_abort(t,this);
795          } catch (Exception JavaDoc ex) {
796             throw new BaseException(ex);
797          }
798       }
799    }
800
801    /**
802     * Receives notice of event status changes. This is called when some
803     * subflow process has finished its execution.
804     */

805    public void receive_event (SharkTransaction t,WfEventAudit event,WfProcessInternal performer) throws BaseException,InvalidPerformer {
806       //System.out.println("Act "+this+" receives event from process "+performer+", ms="+state);
807
Activity aDef=getActivityDefinition(t);
808       SubFlow subflow=aDef.getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
809
810       if (!isSubflowSynchronous) return;
811
812       try {
813          if (performer!=null) {
814             if (performer.state(t).equals(SharkConstants.STATE_CLOSED_COMPLETED) &&
815                 !state(t).startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
816                //if (event.event_type().equals(SharkConstants.EVENT_PROCESS_STATE_CHANGED) &&
817
// The Ids of variables of result from the subflow process must be
818
// corrected to correspond to the actual param variables
819
// In the following map are only OUT and INOUT formal params of
820
// subflow process
821
Map JavaDoc rm=performer.result(t);
822                // This is a subflow activity, so it's context consists
823
// of actual parameters to be passed to the referenced
824
// process in exact order. The Ids of the passed values
825
// are not the same as the Ids used internally by the subprocess
826
// formal parameters, so we get appropriate ids by getting the
827
// process context param at the appropriate place which must be
828
// determined from matching activities actual parameter order
829
// with the subflow process formal parameter order
830

831                // Get actual parameters definition of the subflow activity
832

833                Iterator JavaDoc actualParameters = subflow.getActualParameters().toElements().iterator();
834                // make a list of actual parameter Ids
835
List JavaDoc originalIds=new ArrayList JavaDoc();
836                while(actualParameters.hasNext()){
837                   ActualParameter ap=(ActualParameter)actualParameters.next();
838                   String JavaDoc apId=ap.toValue();
839                   originalIds.add(apId);
840                }
841
842                Map JavaDoc updatedContext=new HashMap JavaDoc();
843                WorkflowProcess wp=SharkUtilities
844                   .getWorkflowProcess(performer.package_id(t),
845                                       performer.manager_version(t),
846                                       performer.process_definition_id(t));
847                Iterator JavaDoc it=rm.entrySet().iterator();
848                while (it.hasNext()) {
849                   Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
850                   String JavaDoc fpId=(String JavaDoc)me.getKey();
851                   int index=0;
852                   int foundIndex=-1;
853                   // find the index of formal parameter by searching for it's Id
854
Iterator JavaDoc fps=wp.getFormalParameters().toElements().iterator();
855                   while (fps.hasNext()) {
856                      FormalParameter fp=(FormalParameter)fps.next();
857                      if (fpId.equals(fp.getId())) {
858                         foundIndex=index;
859                         break;
860                      }
861                      index++;
862                   }
863                   // if formal parameter is found, put the appropriate actual param
864
// name and formal param value into new context
865
if (foundIndex!=-1) {
866                      java.lang.Object JavaDoc apId=originalIds.get(foundIndex);
867                      updatedContext.put(apId,me.getValue());
868                   }
869                }
870                set_result(t,updatedContext);
871                finish(t);
872             }
873          } else {
874             if (performerId==null) {
875                throw new BaseException("This is not remote subflow activity!");
876             }
877             if (event instanceof WfDataEventAudit) {
878                WfDataEventAudit dea=(WfDataEventAudit)event;
879                Map JavaDoc res=dea.new_data();
880                // TODO: in the future, we'll need another call to wfxml API, to get
881
// info about variables to update
882
res = SharkEngineManager.getInstance()
883                   .getWfEngineInteroperabilityMgr()
884                   .parseOutParams(t,
885                                   processId,
886                                   SharkUtilities.createAssignmentKey(key,
887                                                                      getResourceRequesterUsername(t)),
888                                   res,
889                                   container(t).manager(t)
890                                      .context_signature(t));
891                set_result(t,res);
892             }
893             finish(t);
894          }
895       } catch (Exception JavaDoc ex) {
896          SharkEngineManager.getInstance().getCallbackUtilities().error("Activity"+toString()+" - problems when receiving finishing event of subprocess");
897          //System.err.println(ex.getMessage());
898
//ex.printStackTrace();
899
if (ex instanceof BaseException) {
900             throw (BaseException)ex;
901          } else {
902             throw new BaseException(ex);
903          }
904       }
905    }
906
907    public final String JavaDoc activity_set_definition_id(SharkTransaction t) throws BaseException {
908       return activitySetDefinitionId;
909    }
910
911    public final String JavaDoc activity_definition_id(SharkTransaction t) throws BaseException {
912       return activityDefinitionId;
913    }
914
915    public final String JavaDoc block_activity_id (SharkTransaction t) throws BaseException {
916       return blockActivityId;
917    }
918
919    public WfActivityInternal block_activity(SharkTransaction t) throws BaseException {
920       if (blockActivity==null && blockActivityId!=null) {
921          blockActivity=process.getActiveActivity(t,blockActivityId);
922          if (blockActivity==null) {
923             blockActivity=process.getActivity(t,blockActivityId);
924          }
925       }
926       return blockActivity;
927    }
928
929    public final String JavaDoc manager_name (SharkTransaction t) throws BaseException {
930       return mgrName;
931    }
932
933    public final String JavaDoc process_id (SharkTransaction t) throws BaseException {
934       return processId;
935    }
936
937
938    /**
939     * Returns the context of the given activity. Currently, it returns the whole
940     * process context for the activities which type is not Route or Block.
941     */

942    private Map JavaDoc getActivityContext (SharkTransaction t) throws BaseException {
943       // must be linked map to preserve the exact order of parameters,
944
// which is important for subflow, and tool activities
945
int type=getActivityDefinition(t).getActivityType();
946       // set the needed process context to activity context
947
if (type!=XPDLConstants.ACTIVITY_TYPE_ROUTE && type!=XPDLConstants.ACTIVITY_TYPE_BLOCK) {
948          return process.process_context(t);
949       } else {
950          return new HashMap JavaDoc();
951       }
952    }
953
954    // TODO: what to do with assignments that are already accepted???
955
public void reevaluateAssignments (SharkTransaction t) throws BaseException {
956       if (accepted) return;
957       int ls=getAssignmentResourceIds(t).size();
958       removeAssignments(t, true, true);
959       /*
960       Iterator it=l.iterator();
961       while (it.hasNext()) {
962          String username=(String)it.next();
963          WfAssignmentInternal ass=SharkUtilities.getAssignment(t,processId,key,username);
964          try {
965             ass.delete(t);
966          } catch (Exception ex) {
967             throw new BaseException(ex);
968          }
969       }*/

970
971       if (ls==0) return; // the case when activity start and finish mode is MANUAL
972
// but activity has tool to execute (it is waiting for
973
// some client to finish her
974

975       assignmentResourceIds.clear();
976       createAssignments(t);
977    }
978
979    protected void createAssignments(SharkTransaction t) throws BaseException {
980       boolean createAssignments=Boolean.valueOf(
981             SharkEngineManager.
982             getInstance().
983             getCallbackUtilities().
984             getProperty("SharkKernel.createAssignments","true")).booleanValue();
985       if (!createAssignments) return;
986
987       int type=getActivityDefinition(t).getActivityType();
988       if (!(type==XPDLConstants.ACTIVITY_TYPE_NO || type==XPDLConstants.ACTIVITY_TYPE_TOOL)) {
989          return;
990       }
991
992       Participant p=findParticipant(t,getActivityDefinition(t).getPerformer());
993       PerformerData xpdlParticipant=null;
994       List JavaDoc xpdlResponsibleParticipants=null;
995
996       xpdlParticipant=checkParticipant(t,p,type);
997
998       if (xpdlParticipant==null) return;
999
1000      Set JavaDoc performers=findResources(t,p);
1001
1002      // collect all responsibles of the activity
1003
Set JavaDoc responsibles=new HashSet JavaDoc();
1004      List JavaDoc resps=XMLUtil.getResponsibles(getProcessDefinition(t));
1005      Iterator JavaDoc it=resps.iterator();
1006      while (it.hasNext()) {
1007         if (xpdlResponsibleParticipants==null) {
1008            xpdlResponsibleParticipants=new ArrayList JavaDoc();
1009         }
1010         Responsible resp=(Responsible)it.next();
1011         // if responsible is not unresolved expression, this will return Participant object
1012
p=findParticipant(t,resp.toValue());
1013
1014         PerformerData pd=checkParticipant(t,p,type);
1015         if (pd!=null) {
1016            xpdlResponsibleParticipants.add(pd);
1017            responsibles.addAll(findResources(t,p));
1018         }
1019      }
1020
1021      List JavaDoc secUsers=null;
1022
1023      try {
1024         List JavaDoc users=SharkUtilities.getAssignments(t,
1025                                                  SharkEngineManager.getInstance().getCallbackUtilities().getProperty("enginename",""),
1026                                                  processId,
1027                                                  key,
1028                                                  new ArrayList JavaDoc(performers),
1029                                                  new ArrayList JavaDoc(responsibles),
1030                                                  getResourceRequesterUsername(t),
1031                                                  xpdlParticipant,
1032                                                  xpdlResponsibleParticipants);
1033         if (users.size()==0) {
1034            users.add(getResourceRequesterUsername(t));
1035         }
1036
1037         secUsers=SharkUtilities.getSecureAssignments(t,
1038                                                      SharkEngineManager.getInstance().getCallbackUtilities().getProperty("enginename",""),
1039                                                      processId,
1040                                                      key,
1041                                                      users);
1042      } catch (RootException ex) {
1043         throw new BaseException(ex);
1044      }
1045
1046      Iterator JavaDoc resourcesIt=secUsers.iterator();
1047      while (resourcesIt.hasNext()) {
1048         String JavaDoc username=(String JavaDoc)resourcesIt.next();
1049         WfResourceInternal wr=SharkUtilities.getResource(t,username);
1050         if (wr==null) {
1051            try {
1052               wr=SharkEngineManager
1053                  .getInstance()
1054                  .getObjectFactory()
1055                  .createResource(t,username);
1056            } catch (Exception JavaDoc ex) {
1057               throw new BaseException(ex);
1058            }
1059         }
1060         WfAssignmentInternal ass=SharkEngineManager.getInstance().getObjectFactory().createAssignment(t,this,wr);
1061         wr.addAssignment(t,ass);
1062         assignmentResourceIds.add(username);
1063      }
1064
1065   }
1066
1067   protected PerformerData checkParticipant (SharkTransaction t,Participant p,int activityType) throws BaseException {
1068      if (p!=null) {
1069         // check if participant is SYSTEM, and if it is, do not create PerformerData,
1070
// which will indicate not to create any assignments
1071
String JavaDoc participantType=p.getParticipantType().getType();
1072         if (participantType.equals(XPDLConstants.PARTICIPANT_TYPE_SYSTEM)) {
1073            return null;
1074         }
1075         String JavaDoc pDefId=null;
1076         if (p.getParent().getParent() instanceof WorkflowProcess) {
1077            pDefId=((WorkflowProcess)p.getParent().getParent()).getId();
1078         }
1079         return new PerformerData(XMLUtil.getPackage(p).getId(),
1080                                  pDefId,
1081                                  p.getId(),
1082                                  false,
1083                                  participantType);
1084      } else {
1085         String JavaDoc performerExpr=getActivityDefinition(t).getPerformer();
1086         // check if this is a tool activity with an empty performer, and if it
1087
// is, do not create PerformerData, which will indicate not to create any assignments
1088
if (performerExpr.trim().length()==0 &&
1089             activityType==XPDLConstants.ACTIVITY_TYPE_TOOL &&
1090             getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getTools().size()>0) {
1091            return null;
1092         }
1093
1094         try {
1095            // if participant is an expression, calculate an expression
1096
performerExpr=evaluateParticipantExpression(t,performerExpr);
1097         } catch (Exception JavaDoc ex) {}
1098
1099         return new PerformerData(
1100            XMLUtil.getPackage(getActivityDefinition(t)).getId(),
1101            XMLUtil.getWorkflowProcess(getActivityDefinition(t)).getId(),
1102            performerExpr.trim(),
1103            true,null);
1104      }
1105   }
1106
1107   protected Participant findParticipant (SharkTransaction t,String JavaDoc performerExpr) throws BaseException {
1108      Participant p=SharkUtilities.getParticipant(getActivityDefinition(t), performerExpr);
1109      if (p==null) {
1110         try {
1111            // if participant is an expression, calculate an expression, and
1112
// try to retrieve the participant
1113
String JavaDoc participantId=evaluateParticipantExpression(t,performerExpr);
1114            return findParticipant(t,participantId);
1115         } catch (Exception JavaDoc ex) {}
1116      }
1117      return p;
1118   }
1119
1120   /**
1121    * Activates this activity.
1122    */

1123   public void activate(SharkTransaction t) throws BaseException, CannotStart, AlreadyRunning {
1124      // make sure we aren't already running
1125
if (state(t).equals(SharkConstants.STATE_OPEN_RUNNING)) {
1126         throw new AlreadyRunning("The activity is already running");
1127      }
1128
1129      activatedTime = System.currentTimeMillis();
1130
1131      // re-evaluate deadlines - the information will be stored into DB
1132
try {
1133         reevaluateDeadlines(t);
1134      } catch (Exception JavaDoc ex) {
1135         throw new BaseException(ex);
1136      }
1137
1138      // call the limit agent manager here - this is the only central point
1139
// for both automatic and manual activities; start time is set based
1140
// on the time when activity is activated. The limit does not have
1141
// any sense for automatic activities in shark's standard impl.
1142
if (SharkEngineManager.getInstance().getLimitAgentManager()!=null) {
1143         this.activateLimitAgent(t);
1144      }
1145
1146      try {
1147         persist(t);
1148         persistActivityContext(t);
1149         persistDeadlines(t);
1150      } catch (Exception JavaDoc ex) {
1151         throw new BaseException(ex);
1152      }
1153
1154      createAssignments(t);
1155
1156      try {
1157         startActivity(t);
1158      } catch (ToolAgentGeneralException tage) {
1159         toolAgentException=tage;
1160         finishImproperlyAndNotifyProcess(t,
1161                                          SharkUtilities.extractExceptionName(tage));
1162      }
1163      startSubflowThread=null;
1164   }
1165
1166   // Starts or activates this automatic activity
1167
protected void startActivity(SharkTransaction t) throws BaseException, CannotStart, ToolAgentGeneralException {
1168
1169      // get the type of this activity
1170
int type=getActivityDefinition(t).getActivityType();
1171      //log.info("Executing activity " + activity.getId());
1172

1173      if (type!=XPDLConstants.ACTIVITY_TYPE_NO && type!=XPDLConstants.ACTIVITY_TYPE_TOOL) {
1174         try {
1175            change_state(t,SharkConstants.STATE_OPEN_RUNNING);
1176         } catch (InvalidState is) {
1177            throw new CannotStart(is.getMessage());
1178         } catch (TransitionNotAllowed tna) {
1179            throw new CannotStart(tna.getMessage());
1180         } catch (BaseException be) {
1181            throw new CannotStart(be.getMessage());
1182         }
1183      }
1184
1185      // configure the limit agent - this is handled in change_state
1186
// this is not a point for all activities
1187

1188      // set the new previousActivity
1189

1190      // set the estimatedStartDate
1191

1192      switch (type) {
1193         case XPDLConstants.ACTIVITY_TYPE_ROUTE: // Route
1194
try {
1195               this.finish(t); // ROUTE goes directly to complete status
1196
} catch (CannotComplete cc) {
1197               //System.err.println(cc.getMessage());
1198
throw new CannotStart(cc);
1199            }
1200            break;
1201         case XPDLConstants.ACTIVITY_TYPE_NO: // NoImplementation
1202
// NOTE: when using JaWE's code for XPDL handling, we never
1203
// have this activity type. NO type is representet by
1204
// TOOL type with zero tools
1205
this.runNo();
1206            break;
1207         case XPDLConstants.ACTIVITY_TYPE_TOOL: // Tools
1208
int hmt=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getTools().size();
1209            if (hmt>0) {
1210               if (getActivityDefinition(t).getActivityStartMode()==XPDLConstants.ACTIVITY_MODE_AUTOMATIC) {
1211                  boolean shouldFinishImmediatelly=getActivityDefinition(t).getActivityFinishMode()==XPDLConstants.ACTIVITY_MODE_AUTOMATIC;
1212                  this.runTool(t);
1213                  try {
1214                     if (shouldFinishImmediatelly) {
1215                        finish(t);
1216                     } else {
1217                        removeAssignments(t, true, true);
1218                     }
1219                  } catch (CannotComplete cnc) {
1220                     throw new BaseException(cnc);
1221                  }
1222               }
1223            } else {
1224               Participant p=findParticipant(t,getActivityDefinition(t).getPerformer());
1225               if (p!=null) {
1226                  String JavaDoc participantType=p.getParticipantType().getType();
1227                  // THIS SHOULD NEVER HAPPEN - VALIDATOR DOES NOT ALLOW SUCH PROCESSES
1228
if (participantType.equals(XPDLConstants.PARTICIPANT_TYPE_SYSTEM)) {
1229                     try {
1230                        this.finish(t);
1231                        return;
1232                     } catch (CannotComplete cc) {
1233                        throw new CannotStart(cc);
1234                     }
1235                  }
1236               }
1237               this.runNo();
1238            }
1239            break;
1240         case XPDLConstants.ACTIVITY_TYPE_SUBFLOW: // SubFlow
1241
startSubflowThread=Thread.currentThread();
1242            this.runSubFlow(t); // Begin a sub workflow
1243
startSubflowThread=null;
1244            break;
1245         case XPDLConstants.ACTIVITY_TYPE_BLOCK: // BlockActivity
1246
this.runBlock(t); // Block activity
1247
break;
1248      }
1249   }
1250
1251   protected void runNo() throws BaseException, CannotStart {
1252   }
1253
1254   // Runs a TOOL activity - there can be 0..n
1255
protected void runTool(SharkTransaction t) throws BaseException, CannotStart, ToolAgentGeneralException {
1256
1257      if (!state(t).equals(SharkConstants.STATE_OPEN_RUNNING)) {
1258         try {
1259            change_state(t,SharkConstants.STATE_OPEN_RUNNING);
1260         } catch (InvalidState is) {
1261            throw new CannotStart(is.getMessage());
1262         } catch (TransitionNotAllowed tna) {
1263            throw new CannotStart(tna.getMessage());
1264         } catch (BaseException be) {
1265            throw new CannotStart(be.getMessage());
1266         }
1267      }
1268      ToolAgentManager tam=SharkEngineManager.getInstance().getToolAgentManager();
1269      tam.executeActivity(t,this);
1270   }
1271
1272   // Runs a SUBFLOW activity
1273
protected void runSubFlow(SharkTransaction t) throws BaseException, ToolAgentGeneralException {
1274      SubFlow subflow=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
1275      if (subflow == null) {
1276         return;
1277      }
1278
1279      // Get actual parameters definition of the subflow activity
1280
ActualParameters aps=subflow.getActualParameters();
1281      isSubflowSynchronous=getActivityDefinition(t).isSubflowSynchronous();
1282
1283      String JavaDoc refSbflw=subflow.getId();
1284      WorkflowProcess wp=SharkUtilities.getWorkflowProcess(subflow,refSbflw);
1285
1286      String JavaDoc packageId = process.package_id(t);
1287      String JavaDoc packageVersion = process.manager_version(t);
1288
1289      if (wp!=null) {
1290         // start the process
1291
WfProcessMgrInternal[] mgrs;
1292         WfProcessMgrInternal mgr;
1293         WfProcessInternal subProc;
1294         String JavaDoc sbflwPkgIdWithVersion;
1295         String JavaDoc sbflwPkgId;
1296         String JavaDoc sbflwPkgVersion;
1297         String JavaDoc sbflwProcId;
1298
1299         sbflwPkgId=XMLUtil.getPackage(wp).getId();
1300         sbflwPkgVersion=XMLUtil.getPackage(wp).getInternalVersion();
1301         sbflwProcId=refSbflw;
1302         String JavaDoc pmgrName=SharkUtilities.createProcessMgrKey(
1303            sbflwPkgId,
1304            sbflwPkgVersion,
1305            sbflwProcId);
1306         //System.out.println("SPIDWV="+sbflwPkgIdWithVersion+", PMGRN="+pmgrName);
1307
mgr=SharkUtilities.getProcessMgr(t,pmgrName);
1308         if (mgr==null) {
1309            throw new BaseException("Subflow process is not found");
1310         }
1311         try {
1312            subProc=mgr.create_process(t,this);
1313            if (new Boolean JavaDoc(SharkEngineManager.getInstance().getCallbackUtilities().getProperty("SharkKernel.lockSubProcesses","false")).booleanValue()) {
1314               SharkEngineManager.getInstance().getLockMaster().lock(t,subProc.key(t));
1315            }
1316            subProc.set_name(t,process.name(t)+"-"+this.name(t));
1317         } catch (Exception JavaDoc ex) {
1318            SharkEngineManager.getInstance().getCallbackUtilities().error("Activity"+toString()+" - Error instantiating sub-process");
1319            throw new BaseException(ex);
1320         }
1321
1322         FormalParameters fps=
1323            SharkUtilities
1324            .getWorkflowProcess(sbflwPkgId,
1325                                sbflwPkgVersion,
1326                                sbflwProcId).getFormalParameters();
1327
1328         Map JavaDoc m=null;
1329         try {
1330            m=SharkUtilities.createContextMap(t,
1331                                              this.getContext(t),
1332                                              aps,
1333                                              fps,
1334                                              packageId,
1335                                              packageVersion);
1336            subProc.set_process_context(t,m);
1337            performerId=subProc.key(t);
1338            persist(t);
1339            subProc.start(t);
1340         } catch (Exception JavaDoc ex) {
1341            if (ex instanceof ToolAgentGeneralException) {
1342               throw (ToolAgentGeneralException)ex;
1343            } else {
1344               throw new BaseException(ex);
1345            }
1346         }
1347         // this is a remote subflow
1348
} else {
1349         try {
1350            Map JavaDoc m=SharkUtilities.createContextMap(t,
1351                                                  this.getContext(t),
1352                                                  aps,
1353                                                  packageId,
1354                                                  packageVersion);
1355            String JavaDoc assId=SharkUtilities.createAssignmentKey(key,getResourceRequesterUsername(t));
1356            // check if some variable is used to define a reference to remote subflow
1357
if (this.getContext(t).containsKey(refSbflw)) {
1358               Object JavaDoc rsv=this.getContext(t).get(refSbflw);
1359               if (rsv instanceof String JavaDoc) {
1360                  refSbflw=(String JavaDoc)rsv;
1361               }
1362            }
1363            performerId=SharkEngineManager.getInstance().getWfEngineInteroperabilityMgr().start(t,refSbflw,processId,assId,isSubflowSynchronous,m);
1364
1365            persist(t);
1366         } catch (Exception JavaDoc ex) {
1367            throw new BaseException(ex);
1368         }
1369      }
1370
1371      // if this is asynchronous execution, complete activity, otherwise
1372
// wait until the process calls the receive_event() method
1373
if (!isSubflowSynchronous) {
1374         try {
1375            this.finish(t);
1376         } catch (Exception JavaDoc ex) {
1377            //System.err.println(ex.getMessage());
1378
throw new BaseException(ex);
1379         }
1380      }
1381   }
1382
1383   // Runs a BLOCK activity
1384
protected void runBlock(SharkTransaction t) throws BaseException, ToolAgentGeneralException {
1385   }
1386
1387   /**
1388    * Complete this activity.
1389    */

1390   protected void finishImproperlyAndNotifyProcess (SharkTransaction t,String JavaDoc excName) throws BaseException {
1391      try {
1392
1393         // remove assignments first, because method for getting assignments
1394
// from database depends on activity's state
1395
removeAssignments(t, true, true);
1396
1397         change_state(t,SharkConstants.STATE_CLOSED_TERMINATED);
1398
1399         this.exceptionName=excName;
1400
1401         if (toolAgentException==null && excName!=null) {
1402            int type=getActivityDefinition(t).getActivityType();
1403            if (type==XPDLConstants.ACTIVITY_TYPE_SUBFLOW) {
1404               // if this is a subflow activity, terminate it's process
1405
// if it is SYNCHRONOUS
1406
if (isSubflowSynchronous) {
1407                  WfProcessInternal performer=getPerformer(t);
1408                  if (performer==null) {
1409                     SubFlow subflow=getActivityDefinition(t).getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
1410                     String JavaDoc refSbflw=subflow.getId();
1411                     WorkflowProcess wp=SharkUtilities.getWorkflowProcess(subflow,refSbflw);
1412                     if (wp!=null || performerId!=null) {
1413                        throw new BaseException("Null performer of sync. subflow activity");
1414                     }
1415
1416                     SharkEngineManager.getInstance().getWfEngineInteroperabilityMgr().abort(t,performerId,processId,SharkUtilities.createAssignmentKey(key,getResourceRequesterUsername(t)));
1417
1418                  } else {
1419                     if (performer.state(t).startsWith(SharkConstants.STATEPREFIX_OPEN)) {
1420                        performer.terminateFromActivity(t);
1421                     }
1422                  }
1423               }
1424            } else if (type==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
1425               List JavaDoc actActs=process.getAllActiveActivitiesForBlockActivity(t,key);
1426               Iterator JavaDoc it=actActs.iterator();
1427               while (it.hasNext()) {
1428                  WfActivityInternal act=(WfActivityInternal)it.next();
1429                  act.terminateFromProcess(t);
1430               }
1431            }
1432         }
1433
1434         process.activity_terminate(t,this);
1435
1436
1437      } catch (Exception JavaDoc ex) {
1438         if (ex instanceof BaseException) {
1439            throw (BaseException)ex;
1440         } else {
1441            throw new BaseException(ex);
1442         }
1443      }
1444   }
1445
1446   public void set_accepted_status (SharkTransaction t,boolean accept,String JavaDoc resourceUname) throws BaseException, CannotAcceptSuspended {
1447      if (state(t).startsWith(SharkConstants.STATEPREFIX_CLOSED)) {
1448         throw new BaseException("Can't change accepted status - activity state is closed"); // activity is closed
1449
}
1450      if (state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
1451         throw new CannotAcceptSuspended("Can't accept or reject suspended activity"); // activity is suspended
1452
}
1453      if (this.accepted && accept) {
1454         throw new BaseException("Someone else already accepted assignment!"); // activity is already accepted
1455
}
1456
1457      if (SharkEngineManager.getInstance().getEventAuditManager()!=null) {
1458         WfResourceInternal res=SharkUtilities.getResource(t,resourceUname);
1459         SharkEngineManager.getInstance().getObjectFactory().
1460            createAssignmentEventAuditWrapper(t,this,res,res,accept);
1461      }
1462      // accept
1463
boolean deleteOtherAssignments=Boolean.valueOf(
1464            SharkEngineManager.
1465            getInstance().
1466            getCallbackUtilities().
1467            getProperty("SharkKernel.deleteOtherAssignments","true")).booleanValue();
1468            boolean createAssignments=Boolean.valueOf(
1469               SharkEngineManager.
1470               getInstance().
1471               getCallbackUtilities().
1472               getProperty("SharkKernel.createAssignments","true")).booleanValue();
1473      
1474      if (accept) {
1475         try {
1476            // the following three lines must come before change_state where peristing happens
1477
this.accepted=true;
1478            acceptedTime = System.currentTimeMillis();
1479            this.resourceUsername=resourceUname;
1480            if (createAssignments) {
1481               removeAssignments(t, false, deleteOtherAssignments);
1482               setAssignmentStatus(t, resourceUsername, true, true);
1483               WfResourceInternal res=SharkUtilities.getResourceFromCache(t,resourceUsername);
1484               if (res!=null) {
1485                  res.restoreAssignment(t, mgrName, processId, key, true);
1486               }
1487            }
1488            change_state(t,SharkConstants.STATE_OPEN_RUNNING);
1489         } catch (Exception JavaDoc ex) {
1490            throw new BaseException(ex); //
1491
}
1492         /*if (!deleteOtherAssignments) {
1493            try {
1494               String curResUsername=resourceUname;
1495               Iterator itAss = getAssignmentResourceIds(t).iterator();
1496               while (itAss.hasNext()) {
1497                  String resUsername=(String)itAss.next();
1498                  if (!resUsername.equals(curResUsername)) {
1499                     WfResourceInternal res=SharkUtilities.getResourceFromCache(t,resUsername);
1500                     if (res!=null) {
1501                        res.removeAssignment(t,processId,key);
1502                     }
1503                  }
1504               }
1505            } catch (Exception ex) {
1506               //ex.printStackTrace();
1507               throw new BaseException(ex);
1508            }
1509         }*/

1510         // reject
1511
} else {
1512         // if the previous state was accepted, create assignments again
1513
if (this.accepted) {
1514            // put activity into not_started status, or leave it
1515
// as it is if activities status is suspended
1516
//if (!state(t).equals(SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED)) {
1517
try {
1518                  change_state(t,SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED);
1519               } catch (InvalidState is) {
1520                  throw new BaseException(is); //
1521
} catch (TransitionNotAllowed tna) {
1522                  throw new BaseException(tna); //
1523
}
1524            //}
1525
this.accepted=false;
1526            this.acceptedTime = Long.MAX_VALUE/2;
1527            this.resourceUsername=null;
1528            try {
1529               if (createAssignments && !deleteOtherAssignments) {
1530                  String JavaDoc curResUsername=resourceUname;
1531                  Iterator JavaDoc it=getAssignmentResourceIds(t).iterator();
1532                  while (it.hasNext()) {
1533                     String JavaDoc resUsername=(String JavaDoc)it.next();
1534                     setAssignmentStatus(t, resUsername, true, false);
1535                     WfResourceInternal res=SharkUtilities.getResourceFromCache(t,resUsername);
1536                     if (res!=null) {
1537                        res.restoreAssignment(t,mgrName,processId,key,false);
1538                     }
1539                  }
1540               }
1541               persist(t);
1542            } catch (Exception JavaDoc ex) {
1543               throw new BaseException(ex);
1544            }
1545            if (createAssignments && deleteOtherAssignments) {
1546               reevaluateAssignments(t);
1547            }
1548         }
1549      }
1550   }
1551
1552   public final String JavaDoc getResourceUsername (SharkTransaction t) throws BaseException {
1553      return resourceUsername;
1554   }
1555
1556   protected Activity getActivityDefinition (SharkTransaction t) throws BaseException {
1557      if (activityDefinition==null) {
1558         activityDefinition=
1559            SharkUtilities.getActivityDefinition(t,this,getProcessDefinition(t),block_activity(t));
1560      }
1561      return activityDefinition;
1562   }
1563
1564   protected WorkflowProcess getProcessDefinition (SharkTransaction t) throws BaseException {
1565      if (processDefinition==null) {
1566         String JavaDoc packageId=process.package_id(t);
1567         String JavaDoc packageVer=process.manager_version(t);
1568         String JavaDoc pDefId=process.process_definition_id(t);
1569         processDefinition=SharkUtilities.getWorkflowProcess(packageId,packageVer,pDefId);
1570      }
1571      return processDefinition;
1572   }
1573
1574   public String JavaDoc toString () {
1575      return "[Id="+key+", ba="+blockActivityId+", ActDefId="+activityDefinitionId+"]";
1576   }
1577
1578   private void setActivityVariables (SharkTransaction t) throws BaseException {
1579      try {
1580         //System.out.println("SPVCVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV");
1581
// initialize context, just to keep the order of variables
1582
//initializeActivityContext(t);
1583
activitiesProcessContext=new HashMap JavaDoc();
1584         resultVariableIds=new HashSet JavaDoc();
1585   
1586         int type=getActivityDefinition(t).getActivityType();
1587         // ROUTE AND BLOCK Activities do not have a context
1588
if (type==XPDLConstants.ACTIVITY_TYPE_ROUTE || type==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
1589            return;
1590         }
1591         
1592         WorkflowProcess wp=getProcessDefinition(t);
1593         List JavaDoc l=new ArrayList JavaDoc(wp.getAllVariables().values());
1594
1595         if (l.size()==0) return;
1596         
1597         PersistentManagerInterface ipm = SharkEngineManager.getInstance()
1598         .getInstancePersistenceManager();
1599
1600         //System.err.println("INIT PC="+processContext);
1601
Iterator JavaDoc it=l.iterator();
1602         List JavaDoc variableIds=new ArrayList JavaDoc();
1603         while (it.hasNext()) {
1604            XMLCollectionElement dfOrFp=(XMLCollectionElement)it.next();
1605            String JavaDoc vdId=dfOrFp.getId();
1606            variableIds.add(vdId);
1607         }
1608         l=ipm.getActivityVariables(key, variableIds, t);
1609         it=l.iterator();
1610         while (it.hasNext()) {
1611            ActivityVariablePersistenceInterface var=(ActivityVariablePersistenceInterface)it.next();
1612            String JavaDoc vdId=var.getDefinitionId();
1613            Object JavaDoc val=var.getValue();
1614            //System.out.println("Restoring act var "+vdId+", val="+val);
1615
//if (anyVal!=null) {
1616
activitiesProcessContext.put(vdId,val);
1617            if (var.isResultVariable()) {
1618               resultVariableIds.add(vdId);
1619            }
1620            //
1621
}
1622         //System.err.println("REFILLED AC="+activitiesProcessContext);
1623
} catch (Exception JavaDoc ex) {
1624         throw new BaseException ("Restoring of process context failed!",ex);
1625      }
1626   }
1627      
1628   /**
1629    * It is assumed that there can't be two or more
1630    * activities having the same key.
1631    */

1632   public boolean equals (java.lang.Object JavaDoc obj) {
1633      if (!(obj instanceof WfActivityImpl)) return false;
1634      return ((WfActivityImpl)obj).key.equals(key);
1635   }
1636
1637   protected String JavaDoc evaluateParticipantExpression(SharkTransaction t,String JavaDoc expr) throws Exception JavaDoc {
1638      if (expr==null || expr.trim().length()==0) throw new Exception JavaDoc("Improper participant expression!");
1639      // use process_context - these are cloned variables
1640
return evaluator(t).evaluateExpression(t,expr.trim(),process_context(t),java.lang.String JavaDoc.class).toString();
1641   }
1642
1643   private Evaluator evaluator (SharkTransaction t) throws Exception JavaDoc {
1644      if (evaluator==null) {
1645         evaluator=SharkEngineManager
1646            .getInstance()
1647            .getScriptingManager()
1648            .getEvaluator(t,SharkUtilities.getScriptType(
1649                             process.package_id(t),
1650                             process.manager_version(t)));
1651      }
1652      return evaluator;
1653   }
1654
1655   private WfProcessInternal getPerformer (SharkTransaction t) throws BaseException {
1656      if (performerId!=null) {
1657         return SharkUtilities.getProcess(t,performerId);
1658      }
1659      return null;
1660   }
1661
1662   public String JavaDoc getResourceRequesterUsername(SharkTransaction t) throws BaseException {
1663      return process.requester(t).getResourceRequesterUsername(t);
1664   }
1665
1666   public WfRequester getExternalRequester (SharkTransaction t) throws BaseException {
1667      return null;
1668   }
1669
1670   public final boolean accepted_status (SharkTransaction t) throws BaseException {
1671      return accepted;
1672   }
1673
1674   public void persist (SharkTransaction t) throws TransactionException {
1675      try {
1676         //System.err.println("The act "+this+" is being persisted with thread "+Thread.currentThread());
1677
//System.err.println(" The act "+key+" is being persisted:");
1678
PersistentManagerInterface pmi=SharkEngineManager
1679            .getInstance()
1680            .getInstancePersistenceManager();
1681
1682         pmi.persist(createAndFillPersistentObject(), this.justCreated, t);
1683         //persistActivityContext(t);
1684
this.justCreated=false;
1685         // delete assignments if needed
1686
/*if (deleteAssignments) {
1687          Iterator aRes=getAssignmentResourceIds(t).iterator();
1688          while (aRes.hasNext()) {
1689          String resKey=(String)aRes.next();
1690          //System.err.println(" The act "+key+" is deleting its assignment for resource "+resKey);
1691          pmi.deleteAssignment(key,resKey,t.getSharkTransaction());
1692          }
1693          deleteAssignments=false;
1694          }*/

1695
1696         /*if (deadlinesInfo!=null && deadlinesInfo.size()>0) {
1697          persistDeadlines(t);
1698          }*/

1699      } catch (Exception JavaDoc pe) {
1700         throw new TransactionException(pe);
1701      }
1702   }
1703
1704   /**
1705    * Method persistActivityContext stores content of the workflow relevant
1706    * data of this activity, either all of them, or modified only.
1707    *
1708    * @param t a SharkTransaction
1709    * @exception BaseException
1710    */

1711   protected void persistActivityContext(SharkTransaction t) throws BaseException {
1712      try {
1713         if (variableIdsToPersist.size()==0) return;
1714         PersistentManagerInterface pmgr = SharkEngineManager
1715            .getInstance()
1716            .getInstancePersistenceManager();
1717         //System.out.println("Persisting act var map="+getContext(t));
1718
Iterator JavaDoc it=getContext(t).entrySet().iterator();
1719         while (it.hasNext()) {
1720            Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
1721            String JavaDoc defId=(String JavaDoc)me.getKey();
1722            //boolean modifiedOnly = (null != modified);
1723
//if (!modifiedOnly||(modifiedOnly && modified.contains(defId))) {
1724
if (variableIdsToPersist.contains(defId)) {
1725               Object JavaDoc val=me.getValue();
1726               ActivityVariablePersistenceInterface var = pmgr.createActivityVariable();
1727               var.setActivityId(key);
1728               var.setDefinitionId(defId);
1729               var.setValue(val);
1730               var.setResultVariable(getResultVariableIds(t).contains(defId));
1731               pmgr.persist(var, this.justCreatedVariables, t);
1732               //System.out.println("Persisting activity variable "+defId+", val="+val+" for activity "+key+" of process "+processId);
1733
}
1734         }
1735         variableIdsToPersist.clear();
1736         this.justCreatedVariables=false;
1737      } catch (PersistenceException pe) {
1738         throw new BaseException(pe);
1739      }
1740   }
1741
1742   protected void persistDeadlines (SharkTransaction t) throws BaseException {
1743      if (deadlinesInfo==null || deadlinesInfo.size()==0) return;
1744      try {
1745         PersistentManagerInterface pmgr = SharkEngineManager
1746            .getInstance()
1747            .getInstancePersistenceManager();
1748         Iterator JavaDoc it=deadlinesInfo.iterator();
1749         while (it.hasNext()) {
1750            DeadlineInfo dinfo=(DeadlineInfo)it.next();
1751            DeadlinePersistenceInterface dpi = pmgr.createDeadline();
1752            dpi.setProcessId(processId);
1753            dpi.setActivityId(key);
1754            dpi.setExceptionName(dinfo.exceptionName);
1755            dpi.setSynchronous(dinfo.isSynchronous);
1756            dpi.setTimeLimit(dinfo.timeLimit);
1757            pmgr.persist(dpi,justCreatedDeadlines, t);
1758         }
1759         deadlinesInfo.clear();
1760         this.justCreatedDeadlines=false;
1761      } catch (PersistenceException pe) {
1762         throw new BaseException(pe);
1763      }
1764   }
1765
1766   protected void persistExecutedDeadline (String JavaDoc uniqueId,SharkTransaction t) throws BaseException {
1767      try {
1768         PersistentManagerInterface pmgr = SharkEngineManager
1769            .getInstance()
1770            .getInstancePersistenceManager();
1771            DeadlinePersistenceInterface dpi = pmgr.createDeadline();
1772            dpi.setUniqueId(uniqueId);
1773            dpi.setExecuted(true);
1774            pmgr.persist(dpi,false, t);
1775      } catch (PersistenceException pe) {
1776         throw new BaseException(pe);
1777      }
1778   }
1779
1780   public void delete (SharkTransaction t) throws TransactionException {
1781      //try {System.err.println("Deleting activity "+key());}catch (Exception ex){};
1782
try {
1783         SharkEngineManager
1784            .getInstance()
1785            .getInstancePersistenceManager()
1786            .deleteActivity(key,t);
1787      } catch (Exception JavaDoc ex) {
1788         throw new TransactionException("Exception while deleting activity",ex);
1789      }
1790   }
1791
1792   protected XMLCollectionElement getXPDLObject (SharkTransaction t) throws BaseException {
1793      return getActivityDefinition(t);
1794   }
1795
1796   public Map JavaDoc getContext (SharkTransaction t) throws BaseException {
1797      if (activitiesProcessContext==null) {
1798         setActivityVariables(t);
1799      }
1800      return activitiesProcessContext;
1801   }
1802
1803   private Set JavaDoc getResultVariableIds (SharkTransaction t) throws BaseException {
1804      if (resultVariableIds==null) {
1805         setActivityVariables(t);
1806      }
1807      return resultVariableIds;
1808   }
1809
1810   private ActivityPersistenceInterface createAndFillPersistentObject () {
1811      ActivityPersistenceInterface po =
1812         SharkEngineManager
1813         .getInstance()
1814         .getInstancePersistenceManager()
1815         .createActivity();
1816      fillPersistentObject(po);
1817      return po;
1818   }
1819
1820   private void fillPersistentObject (ActivityPersistenceInterface po) {
1821      po.setId(this.key);
1822      po.setActivitySetDefinitionId(this.activitySetDefinitionId);
1823      po.setActivityDefinitionId(this.activityDefinitionId);
1824      po.setProcessMgrName(this.mgrName);
1825      po.setProcessId(this.processId);
1826      po.setResourceUsername(this.resourceUsername);
1827      po.setSubflowProcessId(this.performerId);
1828      po.setSubflowAsynchronous(!this.isSubflowSynchronous);
1829      po.setState(this.state);
1830      po.setBlockActivityId(this.blockActivityId);
1831      po.setName(this.name);
1832      po.setDescription(this.description);
1833      po.setPriority(this.priority);
1834      po.setAcceptedTime(this.acceptedTime);
1835      po.setActivatedTime(this.activatedTime);
1836      po.setLastStateTime(this.lastStateTime);
1837      po.setLimitTime(limitTime);
1838   }
1839
1840   private void restore (ActivityPersistenceInterface po) {
1841      this.key=po.getId();
1842      this.activitySetDefinitionId=po.getActivitySetDefinitionId();
1843      this.activityDefinitionId=po.getActivityDefinitionId();
1844      this.mgrName=po.getProcessMgrName();
1845      this.processId=po.getProcessId();
1846      this.resourceUsername=po.getResourceUsername();
1847      if (this.resourceUsername==null) {
1848         accepted=false;
1849      } else {
1850         accepted=true;
1851      }
1852      this.performerId=po.getSubflowProcessId();
1853      this.isSubflowSynchronous=!po.isSubflowAsynchronous();
1854      this.state=po.getState();
1855      this.blockActivityId=po.getBlockActivityId();
1856      this.name=po.getName();
1857      this.description=po.getDescription();
1858      this.priority=po.getPriority();
1859      this.acceptedTime = po.getAcceptedTime();
1860      this.activatedTime = po.getActivatedTime();
1861      this.lastStateTime = po.getLastStateTime();
1862      this.limitTime=po.getLimitTime();
1863   }
1864
1865   /**
1866    * Return a resource Ids for the specified participant.
1867    * @return A set of resource mapping for given participant.
1868    */

1869   protected Set JavaDoc findResources (SharkTransaction t,Participant p) throws BaseException {
1870      Set JavaDoc ress=new HashSet JavaDoc();
1871      if (p==null) return ress;
1872      String JavaDoc participantId=p.getId();
1873      XMLComplexElement cOwn=(XMLComplexElement)p.getParent().getParent();
1874      boolean isProcessParticipant=(cOwn instanceof WorkflowProcess);
1875      Set JavaDoc usernames=new HashSet JavaDoc();
1876
1877      // We can live without mapping manager
1878
List JavaDoc pMappings=new ArrayList JavaDoc();
1879      ParticipantMappingManager pms = SharkEngineManager.
1880         getInstance().
1881         getParticipantMapPersistenceManager();
1882      if (null != pms) {
1883         ParticipantMappingTransaction trans = null;
1884         try {
1885            trans = SharkUtilities.createParticipantMappingTransaction();
1886            String JavaDoc pkgId=XMLUtil.getPackage(p).getId();
1887            String JavaDoc pDefId=((isProcessParticipant)? cOwn.get("Id").toValue() : null);
1888            pMappings=pms.getParticipantMappings(trans,pkgId,pDefId,participantId);
1889            //SharkUtilities.commitMappingTransaction(trans);
1890
} catch (RootException ex){
1891            //SharkUtilities.rollbackMappingTransaction(trans);
1892
SharkEngineManager
1893               .getInstance()
1894               .getCallbackUtilities()
1895               .error("Error in WfActivityImpl.findResources()", ex);
1896            throw new BaseException(ex);
1897         } finally {
1898            SharkUtilities.releaseMappingTransaction(trans);
1899         }
1900      }
1901      // expanding user groups
1902
Iterator JavaDoc it=pMappings.iterator();
1903      UserGroupManager ugm=SharkEngineManager.
1904         getInstance().
1905         getUserGroupManager();
1906      // We can live without usergroup manager
1907
if (ugm!=null) {
1908         UserTransaction userTrans = null;
1909         try {
1910            userTrans = SharkUtilities.createUserTransaction();
1911
1912            while (it.hasNext()) {
1913               ParticipantMap pm=(ParticipantMap)it.next();
1914               String JavaDoc uname=pm.getUsername();
1915               if (pm.getIsGroupUser()) {
1916                  List JavaDoc unames=ugm.getAllUsers(userTrans,uname);
1917                  //System.out.println("Expanded uname "+uname+" is "+unames);
1918
usernames.addAll(unames);
1919               } else {
1920                  usernames.add(uname);
1921               }
1922            }
1923            //SharkUtilities.commitUserTransaction(userTrans);
1924
} catch (RootException ex){
1925            SharkEngineManager
1926               .getInstance()
1927               .getCallbackUtilities()
1928               .error("Error in WfActivityImpl.findResources() : ", ex);
1929            throw new BaseException(ex);
1930            //SharkUtilities.rollbackUserTransaction(userTrans);
1931
} finally {
1932            SharkUtilities.releaseUserTransaction(userTrans);
1933         }
1934      }
1935      return usernames;
1936   }
1937
1938   public final String JavaDoc getPerformerId (SharkTransaction t) {
1939      return performerId;
1940   }
1941
1942   public final boolean isPerformerSynchronous (SharkTransaction t) {
1943      return isSubflowSynchronous;
1944   }
1945
1946   public final long getCreationTime (SharkTransaction t) throws BaseException {
1947      return activatedTime;
1948   }
1949
1950   public final long getStartTime (SharkTransaction t) throws BaseException {
1951      return acceptedTime;
1952   }
1953
1954   public void updateAssignmentResourceIds (SharkTransaction t,String JavaDoc oldResUname,String JavaDoc newResUname) throws BaseException {
1955      if (assignmentResourceIds!=null) {
1956         assignmentResourceIds.remove(oldResUname);
1957         if (!assignmentResourceIds.contains(newResUname)) {
1958            assignmentResourceIds.add(newResUname);
1959         }
1960      }
1961      if (this.resourceUsername!=null && this.resourceUsername.equals(oldResUname)) {
1962         this.resourceUsername=newResUname;
1963         try {
1964            persist(t);
1965         } catch (Exception JavaDoc ex) {
1966            throw new BaseException(ex);
1967         }
1968      }
1969   }
1970
1971   protected void removeAssignments (SharkTransaction t,boolean removeActiveOne, boolean deleteOtherAssignments) throws BaseException {
1972      boolean createAssignments=Boolean.valueOf(
1973            SharkEngineManager.
1974            getInstance().
1975            getCallbackUtilities().
1976            getProperty("SharkKernel.createAssignments","true")).booleanValue();
1977      if (!createAssignments) return;
1978      PersistentManagerInterface pmi=SharkEngineManager
1979         .getInstance()
1980         .getInstancePersistenceManager();
1981      Iterator JavaDoc itAss = getAssignmentResourceIds(t).iterator();
1982      while (itAss.hasNext()) {
1983         String JavaDoc resUsername=(String JavaDoc)itAss.next();
1984         if (!removeActiveOne && resUsername.equals(resourceUsername)) continue;
1985         WfResourceInternal res=null;
1986         try {
1987            res=SharkUtilities.getResourceFromCache(t,resUsername);
1988            //System.err.println(" The act "+key+" is deleting its assignment for resource "+resKey);
1989
if (deleteOtherAssignments || removeActiveOne) {
1990               pmi.deleteAssignment(key,resUsername,t);
1991            } else {
1992               setAssignmentStatus(t, resUsername, false, false);
1993            }
1994         } catch (Exception JavaDoc ex) {
1995            throw new BaseException(ex);
1996         }
1997         if (res!=null) {
1998            res.removeAssignment(t,processId,key);
1999         }
2000      }
2001
2002      if (deleteOtherAssignments) {
2003         assignmentResourceIds.clear();
2004         if (!removeActiveOne) {
2005            assignmentResourceIds.add(resourceUsername);
2006         }
2007      }
2008      //deleteAssignments=true;
2009
}
2010
2011   protected void setAssignmentStatus (SharkTransaction t,String JavaDoc resUsername,boolean isValid,boolean isAccepted) throws BaseException {
2012      try {
2013         PersistentManagerInterface pmi=SharkEngineManager
2014            .getInstance()
2015            .getInstancePersistenceManager();
2016         AssignmentPersistenceInterface asspo=pmi.createAssignment();
2017         asspo.setProcessMgrName(mgrName);
2018         asspo.setProcessId(processId);
2019         asspo.setActivityId(key);
2020         asspo.setResourceUsername(resUsername);
2021         asspo.setValid(isValid);
2022         asspo.setAccepted(isAccepted);
2023         pmi.persist(asspo, false, t);
2024// System.out.println("PA "+asspo.getActivityId()+", "+asspo.getResourceUsername()+", a="+asspo.isAccepted()+", v="+asspo.isValid());
2025
} catch (Exception JavaDoc ex) {
2026         throw new BaseException(ex);
2027      }
2028   }
2029
2030   public List JavaDoc getDeadlineInfo (SharkTransaction t) throws BaseException {
2031      List JavaDoc ret = null;
2032      List JavaDoc pDeadlines = null;
2033      try {
2034         pDeadlines=SharkEngineManager
2035            .getInstance()
2036            .getInstancePersistenceManager()
2037            .getAllDeadlinesForActivity(this.processId,this.key,t);
2038         Collections.sort(pDeadlines,new DeadlineComparator());
2039      } catch (Exception JavaDoc ex) {
2040         throw new BaseException(ex);
2041      }
2042      
2043      if (pDeadlines==null || pDeadlines.size()==0) return new ArrayList JavaDoc();
2044               
2045      if (!performDeadlineReevaluation()){
2046         ret = new ArrayList JavaDoc();
2047         for (Iterator JavaDoc iter = pDeadlines.iterator(); iter.hasNext();) {
2048            DeadlinePersistenceInterface dpo = (DeadlinePersistenceInterface) iter.next();
2049            DeadlineInfo info = new DeadlineInfo(processId,key,dpo.isExecuted(),dpo.getTimeLimit(),dpo.getExceptionName(), dpo.isSynchronous());
2050            ret.add(info);
2051         }
2052      } else {
2053        try {
2054            ret=new ArrayList JavaDoc(reevaluateDeadlines(t));
2055        } catch (Exception JavaDoc e) {
2056            throw new BaseException(e);
2057        }
2058        for (int i=0; i<ret.size(); i++) {
2059           DeadlineInfo di=(DeadlineInfo)ret.get(i);
2060            DeadlinePersistenceInterface dpo=(DeadlinePersistenceInterface)pDeadlines.get(i);
2061            di.isExecuted=dpo.isExecuted();
2062         }
2063      }
2064      return ret;
2065   }
2066   
2067   public boolean checkDeadlines (SharkTransaction t,long timeLimitBoundary,Map JavaDoc actsToAsyncExcNames) throws BaseException {
2068      String JavaDoc syncDeadlineExcName=null;
2069      List JavaDoc brokenDeadlines=null;
2070      List JavaDoc excNames=new ArrayList JavaDoc();
2071      if (performDeadlineReevaluation()) {
2072         List JavaDoc pDeadlines = null;
2073         try {
2074            pDeadlines=SharkEngineManager
2075               .getInstance()
2076               .getInstancePersistenceManager()
2077               .getAllDeadlinesForActivity(this.processId,this.key,t);
2078            Collections.sort(pDeadlines,new DeadlineComparator());
2079            reevaluateDeadlines(t);
2080            brokenDeadlines=new ArrayList JavaDoc();
2081            for (int i=0; i<pDeadlines.size(); i++) {
2082               DeadlineInfo di=(DeadlineInfo)deadlinesInfo.get(i);
2083               DeadlinePersistenceInterface dpo=(DeadlinePersistenceInterface)pDeadlines.get(i);
2084               if (di.timeLimit<timeLimitBoundary) {
2085                  dpo.setTimeLimit(di.timeLimit);
2086                  brokenDeadlines.add(dpo);
2087               }
2088            }
2089         } catch (Exception JavaDoc ex) {
2090            throw new BaseException(ex);
2091         }
2092         deadlinesInfo.clear();
2093      } else {
2094         try {
2095            brokenDeadlines=SharkEngineManager
2096               .getInstance()
2097               .getInstancePersistenceManager()
2098               .getAllDeadlinesForActivity(this.processId,this.key,timeLimitBoundary,t);
2099         } catch (Exception JavaDoc ex) {
2100            throw new BaseException(ex);
2101         }
2102      }
2103
2104      if (brokenDeadlines!=null && brokenDeadlines.size()>0) {
2105         boolean raiseAsyncDeadlineOnce=new Boolean JavaDoc(SharkEngineManager
2106         .getInstance()
2107         .getCallbackUtilities()
2108         .getProperty("Deadlines.raiseAsyncDeadlineOnlyOnce","true")).booleanValue();
2109         
2110         for (int i=0; i<brokenDeadlines.size(); i++) {
2111            DeadlinePersistenceInterface dpi=(DeadlinePersistenceInterface)brokenDeadlines.get(i);
2112            if (dpi.isExecuted() && raiseAsyncDeadlineOnce) {
2113               continue;
2114            } else {
2115               persistExecutedDeadline(dpi.getUniqueId(), t);
2116            }
2117            String JavaDoc excName=dpi.getExceptionName();
2118            if (dpi.isSynchronous()) {
2119               syncDeadlineExcName=excName;
2120               break;
2121            } else {
2122               if (!excNames.contains(excName)) {
2123                  excNames.add(excName);
2124               }
2125            }
2126         }
2127      }
2128      
2129      if (syncDeadlineExcName!=null) {
2130         finishImproperlyAndNotifyProcess(t,syncDeadlineExcName);
2131      } else {
2132         if (excNames.size()>0) {
2133            actsToAsyncExcNames.put(this,excNames);
2134         }
2135         int type=getActivityDefinition(t).getActivityType();
2136         // if this is block activity, handle its content deadlines
2137
if (type==XPDLConstants.ACTIVITY_TYPE_BLOCK) {
2138            List JavaDoc actActs=process.getAllActiveActivitiesForBlockActivity(t,key);
2139            Iterator JavaDoc it=actActs.iterator();
2140            while (it.hasNext()) {
2141               Map JavaDoc ataens=new HashMap JavaDoc();
2142               WfActivityInternal act=(WfActivityInternal)it.next();
2143               boolean syncDeadlineHappened=act.checkDeadlines(t,timeLimitBoundary,ataens);
2144               if (syncDeadlineHappened) {
2145                  continue;
2146               }
2147               if (ataens.size()>0) {
2148                  actsToAsyncExcNames.putAll(ataens);
2149               }
2150            }
2151         }
2152      }
2153      return (syncDeadlineExcName!=null);
2154   }
2155
2156   protected List JavaDoc reevaluateDeadlines (SharkTransaction t) throws Exception JavaDoc {
2157      Iterator JavaDoc dls=getActivityDefinition(t).getDeadlines().toElements().iterator();
2158
2159      deadlinesInfo=new ArrayList JavaDoc();
2160      while (dls.hasNext()) {
2161         Deadline dl=(Deadline)dls.next();
2162         String JavaDoc dc=dl.getDeadlineCondition();
2163         String JavaDoc en=dl.getExceptionName();
2164         boolean isSynchronous=dl.getExecution().equals(XPDLConstants.EXECUTION_SYNCHR);
2165         Map JavaDoc context=null;
2166         String JavaDoc useProcessContextStr=SharkEngineManager
2167            .getInstance()
2168            .getCallbackUtilities()
2169            .getProperty("Deadlines.useProcessContext","false");
2170
2171         if (Boolean.valueOf(useProcessContextStr).booleanValue()) {
2172            context=this.process.process_context(t);
2173         } else {
2174            context=this.process_context(t);
2175         }
2176
2177         context.put(SharkConstants.PROCESS_STARTED_TIME,new java.util.Date JavaDoc(process.getStartTime(t)));
2178         context.put(SharkConstants.ACTIVITY_ACCEPTED_TIME,new java.util.Date JavaDoc(this.acceptedTime));
2179         context.put(SharkConstants.ACTIVITY_ACTIVATED_TIME,new java.util.Date JavaDoc(this.activatedTime));
2180         long timeLimit=((java.util.Date JavaDoc)evaluator(t).evaluateExpression(t,dc,context,java.util.Date JavaDoc.class)).getTime();
2181         DeadlineInfo dinfo=new DeadlineInfo(processId,key,false,timeLimit,en,isSynchronous);
2182         deadlinesInfo.add(dinfo);
2183         //System.out.println("Act "+this+" re-evaluated deadline "+dinfo);
2184
}
2185      return deadlinesInfo;
2186   }
2187
2188   public final ToolAgentGeneralException getToolAgentException (SharkTransaction t) {
2189      return toolAgentException;
2190   }
2191
2192   public final void setToolAgentException (SharkTransaction t,ToolAgentGeneralException tage) {
2193      this.toolAgentException=tage;
2194   }
2195
2196   public final String JavaDoc getExceptionName (SharkTransaction t) {
2197      return exceptionName;
2198   }
2199
2200   public final void setExceptionName (SharkTransaction t,String JavaDoc excName) {
2201      this.exceptionName=excName;
2202   }
2203
2204   protected boolean performDeadlineReevaluation () {
2205      String JavaDoc reevalStr=SharkEngineManager
2206         .getInstance()
2207         .getCallbackUtilities()
2208         .getProperty("Deadlines.reevaluateDeadlines","true");
2209      return Boolean.valueOf(reevalStr).booleanValue();
2210   }
2211
2212   protected void notifyStart (SharkTransaction t,Map JavaDoc context,long runtime) throws BaseException {
2213      LimitAgentManager mgr = SharkEngineManager.getInstance().getLimitAgentManager();
2214      try {
2215         mgr.notifyStart(processId,key,context,runtime);
2216      } catch (LimitAgentException e) {
2217         throw new BaseException("Unable to register time limit for activity "+this+" with limit agent",e);
2218      }
2219   }
2220
2221   class DeadlineComparator implements Comparator JavaDoc {
2222      public int compare(Object JavaDoc o1,Object JavaDoc o2) {
2223         DeadlinePersistenceInterface dd1=(DeadlinePersistenceInterface)o1;
2224         DeadlinePersistenceInterface dd2=(DeadlinePersistenceInterface)o2;
2225         String JavaDoc ui1=dd1.getUniqueId();
2226         String JavaDoc ui2=dd2.getUniqueId();
2227
2228         return ui1.compareTo(ui2);
2229      }
2230   }
2231   
2232}
2233
2234
Popular Tags