KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > shark > asap > AsapBindingUtilitiesImpl


1 /* AsapBindingUtiltiesImpl.java */
2
3 package org.enhydra.shark.asap;
4
5 import java.net.*;
6 import java.rmi.RemoteException JavaDoc;
7 import java.text.DateFormat JavaDoc;
8 import java.text.SimpleDateFormat JavaDoc;
9 import java.util.*;
10
11 import javax.xml.rpc.holders.StringHolder JavaDoc;
12
13 import org.apache.axis.MessageContext;
14 import org.apache.axis.message.MessageElement;
15 import org.apache.axis.types.URI;
16 import org.apache.axis.types.URI.MalformedURIException;
17 import org.enhydra.shark.api.RootException;
18 import org.enhydra.shark.api.SharkTransaction;
19 import org.enhydra.shark.api.client.timebase.UtcT;
20 import org.enhydra.shark.api.client.wfbase.BaseException;
21 import org.enhydra.shark.api.client.wfmodel.*;
22 import org.enhydra.shark.api.common.SharkConstants;
23 import org.enhydra.shark.asap.types.*;
24 import org.enhydra.shark.asap.types.holders.ResponseHolder;
25 import org.w3c.dom.*;
26
27 /**
28  * ASAP utility methods
29  *
30  * @author V.Puskas, S.Bojanic
31  * @version 0.1
32  */

33 public abstract class AsapBindingUtilitiesImpl {
34
35    public static String JavaDoc[] allowedJavaTypes = new String JavaDoc[] {
36          "java.lang.Long",
37          "java.lang.Boolean",
38          "java.lang.Double",
39          "java.util.Date",
40          "java.lang.String"
41    };
42
43    public static String JavaDoc[] allowedXMLTypes = new String JavaDoc[] {
44          "xsd:long",
45          "xsd:int",
46          "xsd:boolean",
47          "xsd:double",
48          "xsd:double",
49          "xsd:date",
50          "xsd:string"
51    };
52
53    public static Object JavaDoc xmlTypeToDefaultValue(String JavaDoc xmlType) {
54       Object JavaDoc val = null;
55
56       if (xmlType.equals("xsd:long") || xmlType.equals("xsd:int")) {
57          val = new Long JavaDoc(0);
58       } else if (xmlType.equals("xsd:boolean")) {
59          val = new Boolean JavaDoc(false);
60       } else if (xmlType.equals("xsd:double") || xmlType.equals("xsd:float")) {
61          val = new Double JavaDoc(0);
62       } else if (xmlType.equals("xsd:date")) {
63          val = new Date();
64       } else if (xmlType.equals("xsd:string")) {
65          val = new String JavaDoc();
66       }
67       return val;
68    }
69
70    public static String JavaDoc parseFactoryReceiverKey(URI rqReceiverKey) throws Exception JavaDoc {
71       String JavaDoc qString = rqReceiverKey.getQueryString();
72       String JavaDoc procMgr = SharkServiceImpl.DEFAULT_PROC_MGR;
73       if (null != qString) {
74          String JavaDoc procDef = null;
75          String JavaDoc packageId = null;
76          int n = qString.indexOf(SharkServiceImpl.QSPN_PROCESS_DEFINITION);
77          int i;
78          if (n >= 0) {
79             procDef = qString.substring(n
80                                         + SharkServiceImpl.QSPN_PROCESS_DEFINITION.length());
81             i = procDef.indexOf('&');
82             if (i > 0) {
83                procDef = procDef.substring(0, i);
84             }
85             n = qString.indexOf(SharkServiceImpl.QSPN_PACKAGE_ID);
86             if (n >= 0) {
87                packageId = qString.substring(n
88                                              + SharkServiceImpl.QSPN_PACKAGE_ID.length());
89                i = packageId.indexOf('&');
90                if (i > 0) {
91                   packageId.substring(0, i);
92                }
93             }
94             procMgr = SharkServiceImpl.getExecAdmin()
95                .getProcessMgr(packageId, procDef)
96                .name();
97          } else {
98             n = qString.indexOf(SharkServiceImpl.QSPN_PROCESS_MANAGER);
99             if (n >= 0) {
100                procMgr = qString.substring(n
101                                            + SharkServiceImpl.QSPN_PROCESS_MANAGER.length());
102                i = procMgr.indexOf('&');
103                if (i > 0) {
104                   procMgr = procMgr.substring(0, i);
105                }
106                procMgr = URLDecoder.decode(procMgr, "UTF-8");
107             }
108          }
109       }
110
111       return procMgr;
112    }
113
114    protected static void completeActivity(URI rqReceiverKey,
115                                           CompletedRqResultData rd) {
116       String JavaDoc qString = rqReceiverKey.getQueryString();
117       if (null != qString) {
118          String JavaDoc procId = null;
119          String JavaDoc actId = null;
120          String JavaDoc varId = null;
121          String JavaDoc procIdStr = "procId=";
122          String JavaDoc actIdStr = "actId=";
123          String JavaDoc varIdStr = "varId=";
124          int n = qString.indexOf(procIdStr);
125          int i;
126          if (n >= 0) {
127             procId = qString.substring(n + procIdStr.length());
128             i = procId.indexOf('&');
129             if (i > 0) {
130                procId = procId.substring(0, i);
131             }
132             n = qString.indexOf(actIdStr);
133             if (n >= 0) {
134                actId = qString.substring(n + actIdStr.length());
135                i = actId.indexOf('&');
136                if (i > 0) {
137                   actId = actId.substring(0, i);
138                }
139             }
140             n = qString.indexOf(varIdStr);
141             if (n >= 0) {
142                varId = qString.substring(n + varIdStr.length());
143                i = varId.indexOf('&');
144                if (i > 0) {
145                   varId = varId.substring(0, i);
146                }
147             }
148             try {
149                System.out.println("Searching for activity ["
150                                   + procId + "," + actId + "]");
151                WfActivity act = SharkServiceImpl.getExecAdmin()
152                   .getActivity(procId, actId);
153                Map r;
154                if (null != varId) {
155                   HashMap res = retrieveContextVariables(rd.get_any());
156                   r = new HashMap();
157                   System.out.println("Putting results "
158                                      + res + "in variable " + varId);
159                   r.put(varId, res);
160                } else {
161                   System.out.println("Putting results into activity context "
162                                      + actId);
163                   r = parseContext(rd.get_any(), act.container()
164                      .manager()
165                      .context_signature());
166                }
167                act.set_result(r);
168                act.complete();
169             } catch (Exception JavaDoc ex) {
170                ex.printStackTrace();
171             }
172
173          }
174       }
175
176    }
177
178    protected static Map parseContext(CreateInstanceRqContextData rqContextData,
179                                      WfProcess p) throws Exception JavaDoc {
180       if (null != rqContextData && null != rqContextData.get_any()) { return parseContext(rqContextData.get_any(),
181                                                                                           p.manager()
182                                                                                              .context_signature()); }
183       return new HashMap();
184    }
185
186    protected static Map parseContext(Object JavaDoc rqContextData, WfProcess p) throws Exception JavaDoc {
187       if (null != rqContextData) { return parseContext((MessageElement[]) rqContextData,
188                                                        p.manager()
189                                                           .context_signature()); }
190       return new HashMap();
191    }
192
193    protected static Map parseContext(MessageElement[] a, Map csig) throws Exception JavaDoc {
194       Map ret = new HashMap();
195       for (int i = 0; i < a.length; i++) {
196          String JavaDoc n = a[i].getName();
197          if (!csig.containsKey(n)) {
198             System.err.println("WARNING:Variable "
199                                + n + " doesn't match context signiture!");
200             continue;
201             //throw new Exception("Variable " + n + " doesn't match
202
// context signiture!");
203
}
204          String JavaDoc value = a[i].getValue();
205          String JavaDoc t = (String JavaDoc) csig.get(n);
206          try {
207             if (t.equals("java.lang.String")) {
208                if (value != null) {
209                   ret.put(n, value);
210                } else {
211                   ret.put(n, "");
212                }
213             } else {
214                if (value == null) {
215                   value = "0";
216                }
217                if (t.equals("java.lang.Long")) {
218                   ret.put(n, new Long JavaDoc(value));
219                } else if (t.equals("java.lang.Boolean")) {
220                   ret.put(n, new Boolean JavaDoc(value));
221                } else if (t.equals("java.lang.Double")) {
222                   ret.put(n, new Double JavaDoc(value));
223                } else if (t.equals("java.util.Date")) {
224                   java.util.Date JavaDoc dd;
225                   try {
226                      dd = DateFormat.getDateInstance().parse(value);
227                   } catch (Exception JavaDoc _) {
228                      dd = new Date(0L);
229                   }
230                   ret.put(n, dd);
231                }
232             }
233          } catch (Exception JavaDoc ex) {
234             ret.put(n, null);
235             System.out.println("Value "
236                                + a[i].getValue()
237                                + " can't be converted to type " + t
238                                + " - setting null value");
239          }
240       }
241       return ret;
242    }
243
244    public static SchemaType getContextDataSchema(Map contextSigniture) {
245       SchemaType cdt = new SchemaType();
246       MessageElement[] mes = new MessageElement[] {
247          getSchemaElement("ContextDataType", contextSigniture)
248       };
249       cdt.set_any(mes);
250       return cdt;
251    }
252
253    protected static SchemaType getResultDataSchema(Map resultSigniture) {
254       SchemaType rdt = new SchemaType();
255       MessageElement[] mes = new MessageElement[] {
256          getSchemaElement("ResultDataType", resultSigniture)
257       };
258       rdt.set_any(mes);
259       return rdt;
260    }
261
262    public static Map getContextSigniture(SchemaType cdt) {
263       return getSigniture(cdt.get_any());
264    }
265
266    public static Map getResultSigniture(SchemaType rdt) {
267       return getSigniture(rdt.get_any());
268    }
269
270    private static Map getSigniture(MessageElement[] mes) {
271       Map m = new HashMap();
272
273       try {
274          System.out.println("mes-length=" + mes.length);
275          MessageElement main = mes[0];
276          //System.out.println("mes[0]="+main);
277
Node sequence = main.getFirstChild().getFirstChild();
278          NodeList cnodes = sequence.getChildNodes();
279          List allowedXMLT = Arrays.asList(allowedXMLTypes);
280          for (int i = 0; i < cnodes.getLength(); i++) {
281             Node n = cnodes.item(i);
282             //System.out.println("CN="+n);
283
NamedNodeMap nnm = n.getAttributes();
284             String JavaDoc name = getAttributeValue(nnm, "name");
285             String JavaDoc type = getAttributeValue(nnm, "type");
286             m.put(name, xmlTypeToDefaultValue(type));
287          }
288       } catch (Exception JavaDoc ex) {
289          ex.printStackTrace();
290       }
291       return m;
292    }
293
294    private static MessageElement getSchemaElement(String JavaDoc ctName, Map signiture) {
295       MessageElement main = new MessageElement("schema",
296                                                "xsd",
297                                                "http://www.w3.org/2001/XMLSchema");
298       main.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
299       main.setAttribute("targetNamespace", "http://shark.objectweb.org/");
300       MessageElement main2 = new MessageElement("complexType",
301                                                 "xsd",
302                                                 "http://www.w3.org/2001/XMLSchema");
303       main2.setAttribute("name", ctName);
304       //main.setName("schema");
305
//main.setNamespaceURI("http://www.w3.org/2001/XMLSchema");
306
MessageElement sequence = new MessageElement("sequence",
307                                                    "xsd",
308                                                    "http://www.w3.org/2001/XMLSchema");
309       //sequence.setName("sequence");
310
try {
311          main.addChild(main2);
312          main2.addChild(sequence);
313          Iterator it = signiture.entrySet().iterator();
314          while (it.hasNext()) {
315             Map.Entry me = (Map.Entry) it.next();
316             String JavaDoc javaClass = me.getValue().toString();
317             String JavaDoc xsdType = null;
318             if (javaClass.equals("java.lang.Boolean")) {
319                xsdType = "xsd:boolean";
320             } else if (javaClass.equals("java.lang.String")) {
321                xsdType = "xsd:string";
322             } else if (javaClass.equals("java.lang.Long")) {
323                xsdType = "xsd:long";
324             } else if (javaClass.equals("java.lang.Double")) {
325                xsdType = "xsd:double";
326             } else if (javaClass.equals("java.util.Date")) {
327                xsdType = "xsd:date";
328             }
329             if (xsdType != null) {
330                MessageElement el = new MessageElement("element",
331                                                       "xsd",
332                                                       "http://www.w3.org/2001/XMLSchema");
333                //el.setName("element");
334
el.setAttribute("name", me.getKey().toString());
335                el.setAttribute("type", xsdType);
336                el.setAttribute("minOccurs", "0");
337                sequence.addChild(el);
338             }
339          }
340       } catch (Exception JavaDoc ex) {}
341       return main;
342    }
343
344    public static CreateInstanceRqContextData getContextData(Map m, String JavaDoc schemaLocation) {
345       CreateInstanceRqContextData cd = new CreateInstanceRqContextData();
346       cd.set_any(prepareContextVariables(m, schemaLocation));
347       return cd;
348    }
349
350    protected static MessageElement[] prepareContextVariables(Map m, String JavaDoc schemaLocation) {
351       //MessageElement main = new MessageElement("ContextData", "asap",
352
// "http://www.oasis-open.org/asap/0.9/asap.xsd");
353

354       //main.setAttribute("xmlns:asap",
355
// "http://www.oasis-open.org/asap/0.9/asap.xsd");
356
List main = new ArrayList();
357       try {
358          Iterator it = m.entrySet().iterator();
359          while (it.hasNext()) {
360             Map.Entry me = (Map.Entry) it.next();
361             String JavaDoc element = me.getKey().toString();
362
363             Object JavaDoc value = me.getValue();
364             String JavaDoc valueStr = String.valueOf(me.getValue());
365             if (value instanceof java.util.Date JavaDoc) {
366                valueStr = new SimpleDateFormat JavaDoc("yyyy-MM-dd").format(value);
367 // Calendar c = Calendar.getInstance();
368
// c.setTime((java.util.Date) value);
369
// String year = String.valueOf(c.get(Calendar.YEAR));
370
// String month = String.valueOf(c.get(Calendar.MONTH) + 1);
371
// String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
372
// valueStr = year + "-" + month + "-" + day;
373
}
374             String JavaDoc _prefix = "";
375             if (schemaLocation.length() > 0) {
376                _prefix = "pd";
377             }
378             MessageElement el = new MessageElement(element, _prefix, schemaLocation);
379             el.setValue(valueStr);
380             //main.addChild(el);
381
main.add(el);
382          }
383       } catch (Exception JavaDoc ex) {
384          ex.printStackTrace();
385       }
386       System.out.println("main=" + main);
387       //
388
MessageElement[] els = new MessageElement[main.size()];
389       main.toArray(els);
390       return els;
391       //return new MessageElement[] {main};
392
}
393
394    private static HashMap retrieveContextVariables(MessageElement[] mes) {
395       HashMap m = new HashMap();
396
397       try {
398          System.out.println("mes-length=" + mes.length);
399          for (int i = 0; i < mes.length; i++) {
400             MessageElement me = mes[i];
401             System.out.println("mes=" + me);
402             String JavaDoc name = me.getName();
403             String JavaDoc value = me.getValue();
404             m.put(name, value);
405          }
406       } catch (Exception JavaDoc ex) {
407          ex.printStackTrace();
408       }
409       return m;
410    }
411
412    protected static String JavaDoc parseState(StateType rqState) throws Exception JavaDoc {
413       if (StateType.value1.equals(rqState)) {
414          return SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED;
415       } else if (StateType.value2.equals(rqState)) {
416          return SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED;
417       } else if (StateType.value3.equals(rqState)) {
418          return SharkConstants.STATE_OPEN_RUNNING;
419       } else if (StateType.value4.equals(rqState)) {
420          return SharkConstants.STATE_CLOSED_COMPLETED;
421       } else if (StateType.value5.equals(rqState)) {
422          return SharkConstants.STATE_CLOSED_TERMINATED;
423       } else if (StateType.value6.equals(rqState)) {
424          return SharkConstants.STATE_CLOSED_TERMINATED;
425       } else if (StateType.value7.equals(rqState)) {
426          return SharkConstants.STATE_CLOSED_ABORTED;
427       } else {
428          throw new Exception JavaDoc("Argh!");
429       }
430    }
431
432    public static StateType parseState(String JavaDoc rqState) throws Exception JavaDoc {
433       if (SharkConstants.STATE_OPEN_NOT_RUNNING_NOT_STARTED.equals(rqState)) {
434          return StateType.value1;
435       } else if (SharkConstants.STATE_OPEN_NOT_RUNNING_SUSPENDED.equals(rqState)) {
436          return StateType.value2;
437       } else if (SharkConstants.STATE_OPEN_RUNNING.equals(rqState)) {
438          return StateType.value3;
439       } else if (SharkConstants.STATE_CLOSED_COMPLETED.equals(rqState)) {
440          return StateType.value4;
441       } else if (SharkConstants.STATE_CLOSED_TERMINATED.equals(rqState)) {
442          return StateType.value5;
443       } else if (SharkConstants.STATE_CLOSED_TERMINATED.equals(rqState)) {
444          return StateType.value6;
445       } else if (SharkConstants.STATE_CLOSED_ABORTED.equals(rqState)) {
446          return StateType.value7;
447       } else {
448          throw new Exception JavaDoc("Argh!");
449       }
450    }
451
452    protected static URI instanceId2URI(String JavaDoc string) throws Exception JavaDoc {
453       URI instanceURI = new URI(new SharkWebServiceLocator().getasapInstanceBindingAddress());
454       //instanceURI.setHost(myAddress);
455
imprintURI(instanceURI);
456       instanceURI.setQueryString(SharkServiceImpl.QSPN_PROCESS_INSTANCE
457                                  + string);
458       return instanceURI;
459    }
460
461    /**
462     * @param factoryURI
463     * @throws MalformedURIException
464     */

465    public static void imprintURI(URI factoryURI) throws MalformedURIException {
466       String JavaDoc[] a = MessageContext.getCurrentContext()
467          .getRequestMessage()
468          .getMimeHeaders()
469          .getHeader("X-Forwarded-Host");
470       if (null != a && a.length > 0 && null != a[a.length - 1]) {
471          URI tmp = new URI("http://" + a[a.length - 1]);
472          factoryURI.setHost(tmp.getHost());
473          factoryURI.setPort(tmp.getPort());
474       }
475    }
476
477    protected static String JavaDoc instanceURI2Id(URI instanceURI) throws Exception JavaDoc {
478       String JavaDoc string = instanceURI.getQueryString();
479       return string.substring(SharkServiceImpl.QSPN_PROCESS_INSTANCE.length());
480    }
481
482    protected static Event[] extractEvents(WfProcess p) throws Exception JavaDoc {
483       //if (true) return new Event[0];
484
WfEventAudit[] q = p.get_sequence_history(0);
485       List list = new ArrayList();
486       for (int n = 0; n < q.length; ++n) {
487          if (q[n] instanceof WfStateEventAudit
488                && null != ((WfStateEventAudit) q[n]).old_state()) {
489             Event e = new Event();
490             e.setDetails(null);
491             e.setEventType(parseEvent(q[n].event_type()));
492             WfStateEventAudit sea = (WfStateEventAudit) q[n];
493             e.setNewState(parseState(sea.new_state()));
494             e.setOldState(parseState(sea.old_state()));
495             e.setSourceKey(null);
496             Calendar c = Calendar.getInstance();
497             c.setTimeInMillis(q[n].time_stamp().getTime());
498             e.setTime(c);
499             list.add(e);
500          }
501       }
502       Event[] ret = new Event[list.size()];
503       list.toArray(ret);
504       return ret;
505    }
506
507    protected static EventEventType parseEvent(String JavaDoc string) {
508       if (string.equals(SharkConstants.EVENT_PROCESS_CREATED)) {
509          return EventEventType.InstanceCreated;
510       } else if (string.equals(SharkConstants.EVENT_ACTIVITY_CONTEXT_CHANGED)) {
511          return EventEventType.PropertiesSet;
512       } else if (string.equals(SharkConstants.EVENT_PROCESS_CONTEXT_CHANGED)) {
513          return EventEventType.PropertiesSet;
514       } else if (string.equals(SharkConstants.EVENT_ACTIVITY_RESULT_CHANGED)) {
515          return EventEventType.PropertiesSet;
516       } else if (string.equals(SharkConstants.EVENT_ACTIVITY_STATE_CHANGED)) {
517          return EventEventType.StateChanged;
518       } else if (string.equals(SharkConstants.EVENT_PROCESS_STATE_CHANGED)) {
519          return EventEventType.StateChanged;
520       } else {
521          new Throwable JavaDoc("Event not found " + string).printStackTrace();
522          return EventEventType.Error;
523       }
524    }
525
526    protected static URI createFactoryKey(String JavaDoc string) throws Exception JavaDoc {
527       URI factoryURI = new URI(SharkServiceImpl.factoryBindingAddress);
528       //factoryURI.setHost(SharkServiceImpl.getMyAddress());
529
imprintURI(factoryURI);
530       factoryURI.setQueryString(SharkServiceImpl.QSPN_PROCESS_MANAGER
531                                 + URLEncoder.encode(string, "UTF-8"));
532       return factoryURI;
533    }
534
535    protected static MessageElement[] extractData(Map context, String JavaDoc prefix) throws RootException {
536       List mels = new ArrayList();
537       try {
538          List allowedJTs = Arrays.asList(allowedJavaTypes);
539          Iterator it = context.entrySet().iterator();
540          System.out.println("Extracting data for context " + context);
541          while (it.hasNext()) {
542             //main[n].setNamespaceURI("http://www.w3.org/2001/XMLSchema");
543
Map.Entry me = (Map.Entry) it.next();
544             String JavaDoc varId = me.getKey().toString();
545             Object JavaDoc varVal = me.getValue();
546             if (allowedJTs.contains(varVal.getClass().getName())) {
547                MessageElement mel = new MessageElement("http://shark.objectweb.org/",varId,varVal);
548                //mel.setNamespaceURI("http://vidi/");
549
// mel.setName(varId);
550
// mel.setPrefix("p" + prefix);
551
// mel.setObjectValue(varVal);
552
//mel.setObjectValue("pohovani pilici");
553
mels.add(mel);
554             }
555          }
556
557       } catch (Exception JavaDoc ex) {
558          ex.printStackTrace();
559       }
560       MessageElement[] main = new MessageElement[mels.size()];
561       mels.toArray(main);
562       System.out.println("Extracting data result is " + mels);
563       return main;
564    }
565
566    public static URI turnHeads(Request rqHead, ResponseHolder rsHead) throws RemoteException JavaDoc {
567       URI rqReceiverKey = rqHead.getReceiverKey();
568       if (null == rqReceiverKey || 0 == rqReceiverKey.toString().length()) { throw new RemoteException JavaDoc("Invalid receiver key!!!"); }
569       String JavaDoc rqRequestID = rqHead.getRequestID();
570       YesNoIfError rqResponseRequired = rqHead.getResponseRequired();
571       // TODO: rqResponseRequired isn't being used here
572
// what should we do about it ?
573
URI rqSenderKey = rqHead.getSenderKey();
574
575       rsHead.value = new Response(rqReceiverKey, rqSenderKey, rqRequestID);
576       return rqReceiverKey;
577    }
578
579    protected static void notifyObservers(final String JavaDoc procId,
580                                          final String JavaDoc myURI,
581                                          final Map result,
582                                          final String JavaDoc new_state,
583                                          final String JavaDoc old_state,
584                                          final Set observers) throws Exception JavaDoc {
585       Thread JavaDoc notifier = new Thread JavaDoc() {
586          public void run() {
587             // wait until transaction that calls receive_event method
588
// finishes,
589
// cause the process results can be invalid otherwise
590
try {
591                Thread.sleep(100);
592             } catch (Exception JavaDoc ex) {
593                ex.printStackTrace();
594             }
595
596             StateType n, o;
597             CompletedRqResultData crrd;
598             URI instanceURI;
599
600             try {
601                instanceURI = new URI(myURI);//AsapBindingUtilitiesImpl.instanceId2URI(procId);
602
n = AsapBindingUtilitiesImpl.parseState(new_state);
603                o = AsapBindingUtilitiesImpl.parseState(old_state);
604                crrd = (new_state.startsWith("closed")) ? new CompletedRqResultData(AsapBindingUtilitiesImpl.extractData(result,
605                                                                                                                         procId))
606                                                       : null;
607             } catch (Exception JavaDoc e1) {
608                e1.printStackTrace();
609                return;
610             }
611             Request rqh = new Request();
612             StateChangedRq srqb = new StateChangedRq();
613             CompletedRq crqb = new CompletedRq();
614             ResponseHolder rsh = new ResponseHolder();
615             rqh.setSenderKey(instanceURI);
616             srqb.setState(n);
617             srqb.setPreviousState(o);
618             crqb.setInstanceKey(instanceURI);
619             crqb.setResultData(crrd);
620             StringHolder JavaDoc rsb = new StringHolder JavaDoc();
621             boolean notified = false;
622             boolean finished = null != crrd;
623             System.err.println("finished:"
624                                + finished + " notified:" + notified);
625             System.out.println("Notifying observers "
626                                + observers + " about event");
627
628             int maxCnt = 5;
629             do {
630                List obCopy = new ArrayList(observers);
631                int cnt = 0;
632                while (0 < obCopy.size()) {
633                   for (Iterator iter = obCopy.iterator(); iter.hasNext();) {
634                      boolean exc = false;
635                      try {
636                         String JavaDoc element = iter.next().toString();
637                         AsapObserverBindingStub binding;
638                         binding = (AsapObserverBindingStub) new SharkWebServiceLocator().getasapObserverBinding(new URL(element));
639                         binding.setTimeout(60000);
640
641                         rqh.setReceiverKey(new URI(element));
642                         if (!notified) {
643                            binding.stateChanged(rqh, srqb, rsh, rsb);
644                            System.out.println("Observer "
645                                               + element
646                                               + " notified about state change.");
647
648                         } else if (finished) {
649                            binding.completed(rqh, crqb, rsh, rsb);
650                            System.out.println("Observer "
651                                               + element
652                                               + " notified about process complete event.");
653                         }
654                      } catch (Throwable JavaDoc e) {
655                         exc = true;
656                         e.printStackTrace();
657                      } finally {
658                         if (!exc || cnt >= maxCnt) {
659                            iter.remove();
660                         }
661                      }
662                   }
663                   cnt++;
664                }
665                notified = !notified;
666             } while (finished && notified);
667          }
668       };
669       notifier.start();
670    }
671
672    public static Observers createObservers(Set observerKeys) throws Exception JavaDoc {
673       URI[] ret = new URI[observerKeys.size()];
674       Iterator it = observerKeys.iterator();
675       int i = 0;
676       while (it.hasNext()) {
677          Object JavaDoc __o = it.next();
678          ret[i] = new URI(__o.toString());
679          i++;
680       }
681       Observers os = new Observers(ret);
682
683       return os;
684    }
685
686    private static String JavaDoc getAttributeValue(NamedNodeMap nnm, String JavaDoc attrName) {
687       try {
688          Node attrib = nnm.getNamedItem(attrName);
689          if (attrib.hasChildNodes()) {
690             return attrib.getChildNodes().item(0).getNodeValue();
691          } else {
692             return attrib.getNodeValue();
693          }
694       } catch (Exception JavaDoc ex) {
695          return "";
696       }
697    }
698
699    /**
700     * @param rqReceiverKey
701     * @param rqInstanceUri
702     * @param rqResultData
703     * @param oldState
704     * @param newState
705     * @return @throws Exception
706     */

707    public static boolean sendEventToActivity(URI rqReceiverKey,
708                                              final String JavaDoc rqInstanceUri,
709                                              CompletedRqResultData rqResultData,
710                                              final String JavaDoc oldState,
711                                              final String JavaDoc newState) {
712       try {
713          WfRequester act = findActivityFromURI(rqReceiverKey);
714          final UtcT now = new UtcT(System.currentTimeMillis(),
715                                    0,
716                                    (short) 0,
717                                    (short) 0);
718          if (null != rqResultData) {
719             final Map data = retrieveContextVariables(rqResultData.get_any());
720             WfEventAudit a = new WfDataEventAudit() {
721
722                public Map old_data() throws BaseException {
723                   return null;
724                }
725
726                public Map new_data() throws BaseException {
727                   return data;
728                }
729
730                public WfExecutionObject source() throws BaseException,
731                                                 SourceNotAvailable {
732                   // TODO Auto-generated method stub
733
return null;
734                }
735
736                public WfExecutionObject source(SharkTransaction t) throws BaseException,
737                                                                   SourceNotAvailable {
738                   // TODO Auto-generated method stub
739
return null;
740                }
741
742                public UtcT time_stamp() throws BaseException {
743                   return now;
744                }
745
746                public String JavaDoc event_type() throws BaseException {
747                   // TODO Auto-generated method stub
748
return null;
749                }
750
751                public String JavaDoc activity_key() throws BaseException {
752                   return "";
753                }
754
755                public String JavaDoc activity_name() throws BaseException {
756                   // TODO Auto-generated method stub
757
return "";
758                }
759
760                public String JavaDoc process_key() throws BaseException {
761                   // TODO Auto-generated method stub
762
return "";
763                }
764
765                public String JavaDoc process_name() throws BaseException {
766                   // TODO Auto-generated method stub
767
return rqInstanceUri;
768                }
769
770                public String JavaDoc process_mgr_name() throws BaseException {
771                   return "";
772                }
773
774                public String JavaDoc process_mgr_version() throws BaseException {
775                   return "";
776                }
777             };
778             act.receive_event(a);
779          }
780          if (null != newState) {
781             WfEventAudit b = new WfStateEventAudit() {
782                public String JavaDoc old_state() throws BaseException {
783                   return oldState;
784                }
785                
786                public String JavaDoc new_state() throws BaseException {
787                   return newState;
788                }
789                
790                public WfExecutionObject source() throws BaseException,
791                SourceNotAvailable {
792                   return null;
793                }
794                
795                public WfExecutionObject source(SharkTransaction t) throws BaseException,
796                SourceNotAvailable {
797                   return null;
798                }
799                
800                public UtcT time_stamp() throws BaseException {
801                   return now;
802                }
803                
804                public String JavaDoc event_type() throws BaseException {
805                   return null;
806                }
807                
808                public String JavaDoc activity_key() throws BaseException {
809                   return "";
810                }
811                
812                public String JavaDoc activity_name() throws BaseException {
813                   return "";
814                }
815                
816                public String JavaDoc process_key() throws BaseException {
817                   return "";
818                }
819                
820                public String JavaDoc process_name() throws BaseException {
821                   return rqInstanceUri;
822                }
823                
824                public String JavaDoc process_mgr_name() throws BaseException {
825                   return "";
826                }
827                
828                public String JavaDoc process_mgr_version() throws BaseException {
829                   return "";
830                }
831             };
832             act.receive_event(b);
833          }
834       } catch (Throwable JavaDoc _) {
835          //_.printStackTrace();
836
return false;
837       }
838       return true;
839    }
840
841    protected static WfActivity findActivityFromURI(URI anUri) throws Exception JavaDoc {
842       String JavaDoc qString = anUri.getQueryString();
843       String JavaDoc procId = "";
844       String JavaDoc actId = "";
845       if (null != qString) {
846          String JavaDoc procIdStr = "procId=";
847          String JavaDoc actIdStr = "actId=";
848          int n = qString.indexOf(procIdStr);
849          int i;
850          if (n >= 0) {
851             procId = qString.substring(n + procIdStr.length());
852             i = procId.indexOf('&');
853             if (i > 0) {
854                procId = procId.substring(0, i);
855             }
856             n = qString.indexOf(actIdStr);
857             if (n >= 0) {
858                actId = qString.substring(n + actIdStr.length());
859                i = actId.indexOf('&');
860                if (i > 0) {
861                   actId = actId.substring(0, i);
862                }
863             }
864          }
865       }
866       return SharkServiceImpl.getExecAdmin().getActivity(procId, actId);
867    }
868
869 }
870
871
Popular Tags