KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.enhydra.shark;
2
3 import java.util.ArrayList JavaDoc;
4 import java.util.HashMap JavaDoc;
5 import java.util.Iterator JavaDoc;
6 import java.util.Map JavaDoc;
7 import java.util.Properties JavaDoc;
8
9 import org.enhydra.shark.api.ApplicationMappingTransaction;
10 import org.enhydra.shark.api.RootException;
11 import org.enhydra.shark.api.SharkTransaction;
12 import org.enhydra.shark.api.client.wfbase.BaseException;
13 import org.enhydra.shark.api.internal.appmappersistence.ApplicationMap;
14 import org.enhydra.shark.api.internal.appmappersistence.ApplicationMappingManager;
15 import org.enhydra.shark.api.internal.toolagent.AppParameter;
16 import org.enhydra.shark.api.internal.toolagent.ConnectFailed;
17 import org.enhydra.shark.api.internal.toolagent.SessionHandle;
18 import org.enhydra.shark.api.internal.toolagent.ToolAgent;
19 import org.enhydra.shark.api.internal.toolagent.ToolAgentGeneralException;
20 import org.enhydra.shark.api.internal.working.CallbackUtilities;
21 import org.enhydra.shark.api.internal.working.ToolAgentManager;
22 import org.enhydra.shark.api.internal.working.WfActivityInternal;
23 import org.enhydra.shark.api.internal.working.WfProcessInternal;
24 import org.enhydra.shark.xpdl.XMLComplexChoice;
25 import org.enhydra.shark.xpdl.XMLComplexElement;
26 import org.enhydra.shark.xpdl.XPDLConstants;
27 import org.enhydra.shark.xpdl.XMLUtil;
28 import org.enhydra.shark.xpdl.elements.Activity;
29 import org.enhydra.shark.xpdl.elements.ActualParameter;
30 import org.enhydra.shark.xpdl.elements.ActualParameters;
31 import org.enhydra.shark.xpdl.elements.Application;
32 import org.enhydra.shark.xpdl.elements.FormalParameter;
33 import org.enhydra.shark.xpdl.elements.FormalParameters;
34 import org.enhydra.shark.xpdl.elements.Tool;
35 import org.enhydra.shark.xpdl.elements.WorkflowProcess;
36
37 /**
38  * Executes tool agents for Tool activities.
39  *
40  * @author Sasa Bojanic
41  */

42 public class ToolAgentManagerImpl implements ToolAgentManager {
43
44    private final static long APP_STATUS_INVALID=-1;
45
46    private final static String JavaDoc DEFAULT_TOOL_AGENT="DefaultToolAgent";
47
48    private String JavaDoc defaultToolAgentClassName;
49
50    private CallbackUtilities cus;
51
52    protected ToolAgentManagerImpl () {
53       this.cus=SharkEngineManager.getInstance().getCallbackUtilities();
54       Properties JavaDoc props= cus.getProperties();
55       // setting default tool agent
56
try {
57          defaultToolAgentClassName=(String JavaDoc)props.get(DEFAULT_TOOL_AGENT);
58       } catch (Throwable JavaDoc ex) {
59          cus.error("ToolAgentManagerImpl -> Can't read default tool agent name - can't work without mappings !!!");
60       }
61    }
62
63    public void executeActivity (SharkTransaction t,WfActivityInternal act) throws BaseException, ToolAgentGeneralException {
64       ToolRunner tr=new ToolRunner(t,act);
65       //actToToolRunner.put(act,tr);
66
//new Thread(tr).start();
67
tr.run();
68    }
69
70    protected class ToolRunner {//implements Runnable {
71
protected WfActivityInternal activity;
72       protected Activity actDef;
73       protected SharkTransaction transaction;
74
75       protected ToolRunner (SharkTransaction t,WfActivityInternal wai) throws BaseException {
76          this.transaction=t;
77          this.activity=wai;
78          WfProcessInternal pr=wai.container(t);
79          WorkflowProcess wp=SharkUtilities.
80             getWorkflowProcess(pr.package_id(t),
81                                pr.manager_version(t),
82                                pr.process_definition_id(t));
83          this.actDef=SharkUtilities.getActivityDefinition(t,wai,wp,wai.block_activity(t));
84       }
85
86       public void run () throws BaseException, ToolAgentGeneralException {
87          Iterator JavaDoc tools = null;
88          tools=actDef.getActivityTypes().getImplementation().getImplementationTypes().getTools().toElements().iterator();
89          while(tools.hasNext()) {
90             Tool tool = (Tool)tools.next();
91             cus.info("Activity"+activity.toString()+" - Executing tool [id="+tool.getId()+"]");
92             // implement me
93
/*if (tool.get("Type").toValue().toString().equals("APPLICATION")){
94              } else {*/

95             try {
96                invokeApplication(tool);
97                // if some application is not executed, throw an exception
98
} catch (Throwable JavaDoc ex) {
99                cus.error("Activity"+activity.toString()+" - failed to execute tool [id="+tool.getId()+"]");
100                //ex.printStackTrace();
101
if (ex instanceof ToolAgentGeneralException) {
102                   throw (ToolAgentGeneralException)ex;
103                } else {
104                   throw new BaseException(ex);
105                }
106             }
107             //}
108
}
109       }
110
111       protected Map JavaDoc createContextMap (ActualParameters aps,FormalParameters fps) throws Exception JavaDoc {
112          return SharkUtilities.createContextMap(transaction,activity,aps,fps);
113       }
114
115       protected String JavaDoc getAssignmentId (String JavaDoc procId,String JavaDoc actId) throws Exception JavaDoc {
116          String JavaDoc actRes=activity.getResourceRequesterUsername(transaction);
117          String JavaDoc assId=SharkUtilities.createAssignmentKey(actId,actRes);
118          return assId;
119       }
120
121       // IT IS ASSUMED THAT APPLICATION IS DEFINED WITH IT's FORMAL PARAMETERS
122
// DEFINED - NOT AS EXTERNAL REFERENCE. IF IT IS NOT THE CASE, AN
123
// EXCEPTION WILL BE THROWN
124
protected void invokeApplication(Tool tool) throws Throwable JavaDoc {
125          String JavaDoc applicationId = tool.getId();
126          Application app=SharkUtilities.getApplication(tool, applicationId);
127
128          //SharkServer.getLogger().info("Tool defines " + ((ActualParameters)tool.get("ActualParameters")).size() +" actual parameters");
129

130          // build up the parameters
131
ArrayList JavaDoc parameters = new ArrayList JavaDoc();
132
133          // the extended attributes are always the first parameter passed to tool agent
134
String JavaDoc appPStr=app.getExtendedAttributes().getExtendedAttributesString();
135          //System.err.println("EXTATTRS="+appPStr);
136
AppParameter param=new AppParameter("ExtendedAttributes","ExtendedAttributes",XPDLConstants.FORMAL_PARAMETER_MODE_IN,appPStr,String JavaDoc.class);
137          parameters.add(param);
138
139          ActualParameters aps=tool.getActualParameters();
140          FormalParameters fps=app.getApplicationTypes().getFormalParameters();
141          Map JavaDoc m=createContextMap(aps,fps);
142          //System.err.println("Created param map "+m);
143
Iterator JavaDoc itFps=fps.toElements().iterator();
144          Iterator JavaDoc itAps=aps.toElements().iterator();
145          while (itFps.hasNext() && itAps.hasNext()) {
146             FormalParameter fp=(FormalParameter)itFps.next();
147             ActualParameter ap=(ActualParameter)itAps.next();
148             String JavaDoc fpMode=fp.getMode();
149             String JavaDoc fpId=fp.getId();
150             Object JavaDoc paramVal=m.get(fpId);
151
152             // JAWE's CLASSES DataField and FormalParameter RETURNS ITs
153
// Id ATTRIBUTE WHEN METHOD toString() is CALLED (when calling
154
// ap.toValue().toString(), it can be called toString() method of
155
// these two classes)
156
param=new AppParameter(ap.toValue(),fpId,fpMode,paramVal,SharkUtilities.getJavaClass(fp));
157             parameters.add(param);
158          }
159
160          // find mapped procedure - but we can also live without mapping
161
// manager (but we can't without ToolAgentFactory
162
ApplicationMappingManager mm=SharkEngineManager.getInstance().getApplicationMapPersistenceManager();
163          ApplicationMap tad=null;
164          if (mm!=null) {
165             XMLComplexElement cOwn=(XMLComplexElement)app.getParent().getParent();
166             boolean isProcessApp=(cOwn instanceof WorkflowProcess);
167             ApplicationMappingTransaction t=null;
168             try {
169                t = SharkUtilities.createApplicationMappingTransaction();
170                tad=
171                   SharkEngineManager.
172                   getInstance().getApplicationMapPersistenceManager().
173                   getApplicationMap(
174                                     t,
175                                     XMLUtil.getPackage(app).getId(),
176                                        ((isProcessApp)? cOwn.get("Id").toValue() : null),
177                                     applicationId
178                                    );
179                //SharkUtilities.commitMappingTransaction(t);
180
} catch (RootException e) {
181                //SharkUtilities.rollbackMappingTransaction(t);
182
throw e;
183             } finally {
184                SharkUtilities.releaseMappingTransaction(t);
185             }
186          }
187          SessionHandle shandle=null;
188          String JavaDoc tacn=(tad!=null) ? tad.getToolAgentClassName() : defaultToolAgentClassName;
189          String JavaDoc uname=(tad!=null) ? tad.getUsername() : "";
190          String JavaDoc pwd=(tad!=null) ? tad.getPassword() : "";
191          String JavaDoc appN=(tad!=null) ? tad.getApplicationName() : "";
192          Integer JavaDoc appM=(tad!=null) ? tad.getApplicationMode() : null;
193          ToolAgent ta=SharkEngineManager.getInstance().
194             getToolAgentFactory().
195             createToolAgent(transaction,tacn);
196          // try to connect to the tool agent
197
try {
198             shandle=ta.connect(transaction,uname,pwd,cus.getProperty("enginename","imaobihostrezube"),"");
199          } catch (ConnectFailed cf) {
200             cus.error("Activity"+activity.toString()+" - connection to Tool agent "+tacn+" failed !");
201             throw cf;
202          }
203
204          String JavaDoc procId=activity.container(transaction).key(transaction);
205          String JavaDoc actKey=activity.key(transaction);
206          String JavaDoc assId=getAssignmentId(procId,actKey);
207
208          // invoke the procedure with the specified parameters
209
AppParameter[] aprs=(AppParameter[])parameters.toArray(
210                                                                 new AppParameter[parameters.size()]);
211          ta.invokeApplication(transaction,
212                               shandle.getHandle(),
213                               appN,
214                               procId,
215                               assId,
216                               aprs,
217                               appM);
218          long appStatus;
219
220
221          appStatus=ta.requestAppStatus(transaction,
222                                        shandle.getHandle(),
223                                        procId,
224                                        assId,
225                                        aprs);
226          //System.err.println("TAM get status "+appStatus+" for underlying TA");
227
if (appStatus==APP_STATUS_INVALID) {
228             //System.err.println("TAM catched invalid APPS and throwing exc");
229
ta.disconnect(transaction,shandle);
230             throw new Exception JavaDoc("Tool agent status is invalid!");
231          }
232          ta.disconnect(transaction,shandle);
233
234          AppParameter[] returnValues=aprs;
235
236          // copy the return values into the workflow data
237
Map JavaDoc newData=new HashMap JavaDoc();
238          for(int i = 0; i < returnValues.length; i++){
239             if (returnValues[i].the_mode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_OUT) ||
240                    returnValues[i].the_mode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_INOUT)) {
241                String JavaDoc name = returnValues[i].the_actual_name;
242                Object JavaDoc value = returnValues[i].the_value;
243                newData.put(name,value);
244             }
245          }
246
247          activity.set_result(transaction,newData);
248
249       }
250
251    }
252
253 }
254
255
256
Popular Tags