KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > shark > xpdl > XMLUtil


1 package org.enhydra.shark.xpdl;
2
3 import java.io.ByteArrayInputStream JavaDoc;
4 import java.io.ByteArrayOutputStream JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.FileOutputStream JavaDoc;
8 import java.io.ObjectInputStream JavaDoc;
9 import java.io.ObjectOutputStream JavaDoc;
10 import java.io.OutputStream JavaDoc;
11 import java.io.StringReader JavaDoc;
12 import java.net.URL JavaDoc;
13 import java.util.ArrayList JavaDoc;
14 import java.util.Calendar JavaDoc;
15 import java.util.Collection JavaDoc;
16 import java.util.GregorianCalendar JavaDoc;
17 import java.util.HashMap JavaDoc;
18 import java.util.HashSet JavaDoc;
19 import java.util.Iterator JavaDoc;
20 import java.util.List JavaDoc;
21 import java.util.Map JavaDoc;
22 import java.util.MissingResourceException JavaDoc;
23 import java.util.Properties JavaDoc;
24 import java.util.ResourceBundle JavaDoc;
25 import java.util.Set JavaDoc;
26
27 import javax.xml.parsers.DocumentBuilder JavaDoc;
28 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
29 import javax.xml.transform.Transformer JavaDoc;
30 import javax.xml.transform.TransformerFactory JavaDoc;
31 import javax.xml.transform.dom.DOMSource JavaDoc;
32 import javax.xml.transform.stream.StreamResult JavaDoc;
33
34 import org.apache.xerces.util.XMLChar;
35 import org.enhydra.shark.xpdl.elements.Activities;
36 import org.enhydra.shark.xpdl.elements.Activity;
37 import org.enhydra.shark.xpdl.elements.ActivitySet;
38 import org.enhydra.shark.xpdl.elements.ActivitySets;
39 import org.enhydra.shark.xpdl.elements.ActualParameter;
40 import org.enhydra.shark.xpdl.elements.ActualParameters;
41 import org.enhydra.shark.xpdl.elements.BasicType;
42 import org.enhydra.shark.xpdl.elements.BlockActivity;
43 import org.enhydra.shark.xpdl.elements.Condition;
44 import org.enhydra.shark.xpdl.elements.DataType;
45 import org.enhydra.shark.xpdl.elements.DataTypes;
46 import org.enhydra.shark.xpdl.elements.Deadlines;
47 import org.enhydra.shark.xpdl.elements.DeclaredType;
48 import org.enhydra.shark.xpdl.elements.EnumerationType;
49 import org.enhydra.shark.xpdl.elements.EnumerationValue;
50 import org.enhydra.shark.xpdl.elements.ExtendedAttribute;
51 import org.enhydra.shark.xpdl.elements.ExtendedAttributes;
52 import org.enhydra.shark.xpdl.elements.FinishMode;
53 import org.enhydra.shark.xpdl.elements.FormalParameter;
54 import org.enhydra.shark.xpdl.elements.FormalParameters;
55 import org.enhydra.shark.xpdl.elements.Join;
56 import org.enhydra.shark.xpdl.elements.Manual;
57 import org.enhydra.shark.xpdl.elements.Namespace;
58 import org.enhydra.shark.xpdl.elements.Namespaces;
59 import org.enhydra.shark.xpdl.elements.Package;
60 import org.enhydra.shark.xpdl.elements.RedefinableHeader;
61 import org.enhydra.shark.xpdl.elements.Responsible;
62 import org.enhydra.shark.xpdl.elements.Responsibles;
63 import org.enhydra.shark.xpdl.elements.SchemaType;
64 import org.enhydra.shark.xpdl.elements.Split;
65 import org.enhydra.shark.xpdl.elements.StartMode;
66 import org.enhydra.shark.xpdl.elements.SubFlow;
67 import org.enhydra.shark.xpdl.elements.Tools;
68 import org.enhydra.shark.xpdl.elements.Transition;
69 import org.enhydra.shark.xpdl.elements.TransitionRef;
70 import org.enhydra.shark.xpdl.elements.TransitionRefs;
71 import org.enhydra.shark.xpdl.elements.TransitionRestriction;
72 import org.enhydra.shark.xpdl.elements.TransitionRestrictions;
73 import org.enhydra.shark.xpdl.elements.Transitions;
74 import org.enhydra.shark.xpdl.elements.WorkflowProcess;
75 import org.w3c.dom.Attr JavaDoc;
76 import org.w3c.dom.Document JavaDoc;
77 import org.w3c.dom.Element JavaDoc;
78 import org.w3c.dom.NamedNodeMap JavaDoc;
79 import org.w3c.dom.Node JavaDoc;
80 import org.w3c.dom.NodeList JavaDoc;
81 import org.xml.sax.InputSource JavaDoc;
82
83 /**
84  * Class with utilities to read/write XPDLs from/to XML.
85  *
86  * @author Sasa Bojanic
87  */

88 public class XMLUtil {
89
90    public final static String JavaDoc XMLNS = "http://www.wfmc.org/2002/XPDL1.0";
91    public final static String JavaDoc XMLNS_XPDL = "http://www.wfmc.org/2002/XPDL1.0";
92    public final static String JavaDoc XMLNS_XSI = "http://www.w3.org/2001/XMLSchema-instance";
93    public final static String JavaDoc XSI_SCHEMA_LOCATION = "http://www.wfmc.org/2002/XPDL1.0 http://wfmc.org/standards/docs/TC-1025_schema_10_xpdl.xsd";
94
95    private static ResourceBundle JavaDoc defaultResources;
96    private static ResourceBundle JavaDoc choosenResources;
97    private static Properties JavaDoc properties;
98
99    public static void setDefaultResources (ResourceBundle JavaDoc defaultR) {
100       defaultResources=defaultR;
101    }
102
103    public static void setChoosenResources (ResourceBundle JavaDoc choosenR) {
104       choosenResources=choosenR;
105    }
106
107    public static void setProperties (Properties JavaDoc props) {
108       properties=props;
109    }
110
111    /**
112     * Gets a resource string from the resource bundle.<p> Resource bundle
113     * represents the <i>property file</i>. For example, if property file
114     * contains something like this:<BR><CENTER>menubar=file edit help</CENTER>
115     * method call getLanguageDependentString("menubar") will give the string
116     * <i>file edit help</i> as a result. <BR> This method reads information
117     * from property file. If can't find desired resource, returns <b>null</b>.
118     * @param nm name of the resource to fetch.
119     * @return String value of named resource.
120     */

121    public static String JavaDoc getLanguageDependentString(String JavaDoc nm) {
122       String JavaDoc str;
123       try {
124          str=choosenResources.getString(nm);
125       } catch (MissingResourceException JavaDoc mre) {
126          try {
127             str=defaultResources.getString(nm);
128          } catch (MissingResourceException JavaDoc mre1) {
129             str = null;
130          } catch (NullPointerException JavaDoc npe) {
131             str=null;
132          }
133       } catch (NullPointerException JavaDoc npe) {
134          /*ResourceBundle orig=ResourceBundle.
135           getBundle("org.enhydra.shark.xpdl.resources.SharkXPDL",new Locale(""));*/

136          ResourceBundle JavaDoc orig=ResourceBundle.
137             getBundle("org.enhydra.shark.xpdl.resources.SharkXPDL");
138          try {
139             str=orig.getString(nm);
140          } catch (Exception JavaDoc ex) {
141             str=null;
142          }
143       }
144       return str;
145    }
146
147    /**
148     * Gets the url from a resource string.
149     * @param key the string key to the url in the properties.
150     * @return the resource location.
151     * @see java.lang.Class#getResource
152     */

153    public static URL JavaDoc getResource(String JavaDoc key) {
154       try {
155          String JavaDoc name=properties.getProperty(key);
156          if (name != null) {
157             URL JavaDoc url = XMLUtil.class.getClassLoader().getResource(name);
158             return url;
159          }
160       } catch (Exception JavaDoc ex) {}
161       return null;
162    }
163
164    /**
165     * Determines the number of string toFind within string toSearch.
166     */

167    public static int howManyStringsWithinString (String JavaDoc toSearch,String JavaDoc toFind) {
168       try {
169          int startAt=0;
170          int howMany=0;
171
172          int fnd;
173          while ((fnd=toSearch.indexOf(toFind,startAt))!=-1) {
174             howMany++;
175             startAt=(fnd+toFind.length());
176          }
177          return howMany;
178       } catch (Exception JavaDoc ex) {
179          return -1;
180       }
181    }
182
183    public static String JavaDoc getCanonicalPath (String JavaDoc relpath,String JavaDoc basedir,boolean canBeDirectory) {
184       File JavaDoc f=new File JavaDoc(relpath);
185       if (!f.isAbsolute()) {
186          f=f.getAbsoluteFile();
187          if (!f.exists()) {
188             f=new File JavaDoc(XMLUtil.createPath(basedir,relpath));
189          }
190       }
191       if (!f.exists() || (f.isDirectory() && !canBeDirectory)) {
192          System.err.println("The file "+f.getAbsolutePath()+" does not exist");
193          return null;
194       } else {
195          return getCanonicalPath(f);
196       }
197    }
198
199    public static String JavaDoc getCanonicalPath (String JavaDoc path, boolean canBeDirectory) {
200       File JavaDoc f=new File JavaDoc(path);
201       if (!f.isAbsolute()) {
202          f=new File JavaDoc(System.getProperty("user.dir")+File.separator+path);
203       }
204       if (!f.exists() || (f.isDirectory() && !canBeDirectory)) {
205          System.err.println("The file "+f.getAbsolutePath()+" does not exist");
206          return null;
207       } else {
208          return getCanonicalPath(f);
209       }
210    }
211
212    private static String JavaDoc getCanonicalPath (File JavaDoc f) {
213       try {
214          return f.getCanonicalPath();
215       } catch (Exception JavaDoc ex) {
216          return f.getAbsolutePath();
217       }
218    }
219
220    private static boolean logging=false;
221
222    public static void fromXML (Element JavaDoc node,Package JavaDoc pkg) {
223 // long t1,t2;
224
// t1=System.currentTimeMillis();
225
NamedNodeMap JavaDoc attribs=node.getAttributes();
226       Namespaces nss=pkg.getNamespaces();
227       for (int i=0; i<attribs.getLength(); i++) {
228          Node JavaDoc n=attribs.item(i);
229          String JavaDoc nn=n.getNodeName();
230          if (nn.startsWith("xmlns:") && !nn.equals("xmlns:xsi")) {
231             Namespace ns=(Namespace)nss.generateNewElement();
232             ns.setName(nn.substring(6,nn.length()));
233             fromXML(n,(XMLAttribute)ns.get("location"));
234             nss.add(ns);
235          }
236       }
237       fromXML(node,(XMLComplexElement)pkg);
238 // t2=System.currentTimeMillis();
239
// System.out.println("MFXML="+(t2-t1));
240
}
241
242    public static void fromXML (Node JavaDoc node,XMLCollection cel) {
243       if ( node == null || !node.hasChildNodes()) return;
244       String JavaDoc nameSpacePrefix=getNameSpacePrefix(node);
245
246       XMLElement newOne=cel.generateNewElement();
247       String JavaDoc elName=newOne.toName();
248
249       NodeList JavaDoc children = node.getChildNodes();
250       int lng=children.getLength();
251 if (logging) System.out.println("FROMXML for "+cel.toName()+", c="+cel.getClass().getName());
252       for (int i = 0; i<lng; i++) {
253          Node JavaDoc child=children.item(i);
254          if (child.getNodeName().equals(nameSpacePrefix+elName)) {
255             //System.out.println("I="+i);
256
newOne = cel.generateNewElement();
257             //System.out.println("Now the collection element of collection "+node.getNodeName()+" will be processed");
258
if (newOne instanceof XMLComplexElement) {
259                fromXML(children.item(i),(XMLComplexElement)newOne);
260             } else {
261                fromXML(children.item(i),(XMLSimpleElement)newOne);
262             }
263             cel.add(newOne);
264          } else {
265             //System.err.println("Something's wrong with collection "+elName+" parsing - c="+cel.getClass().getName()+" !");
266
}
267       }
268       //System.out.println("The length of collection "+name+" after importing is"+size());
269
}
270
271    public static void fromXML (Node JavaDoc node,XMLComplexElement cel) {
272       if ( node == null || (!node.hasChildNodes() && !node.hasAttributes())) return;
273
274       String JavaDoc nameSpacePrefix=node.getPrefix();
275       if (nameSpacePrefix!=null) {
276          nameSpacePrefix+=":";
277       } else {
278          nameSpacePrefix="";
279       }
280 if (logging) System.out.println("FROMXML for "+cel.toName()+", c="+cel.getClass().getName());
281
282       if ( node.hasAttributes() ) {
283          NamedNodeMap JavaDoc attribs = node.getAttributes();
284          for ( int i = 0; i < attribs.getLength(); ++i ) {
285             Node JavaDoc attrib = ( Node JavaDoc ) attribs.item( i );
286             try {
287 //System.out.println("Getting attrib "+attrib.getNodeName());
288
fromXML(attrib,(XMLAttribute)cel.get( attrib.getNodeName() ));
289             } catch ( NullPointerException JavaDoc npe ) {
290                /*System.err.println("Processing attributes for "+ cel.toName()
291                                +" element having problems with "
292                                + attrib.getNodeName()+" attribute\n"
293                                + attrib.getNodeValue().trim());*/

294             }
295          }
296       }
297       // getting elements
298
if (node.hasChildNodes()) {
299          // Specific code for handling Condition element - we don't support Xpression element
300
if (cel instanceof Condition) {
301             String JavaDoc newVal=node.getChildNodes().item(0).getNodeValue();
302             if (newVal!=null) {
303                cel.setValue(newVal);
304             }
305          }
306          // Specific code for handling SchemaType element
307
if (cel instanceof SchemaType) {
308             NodeList JavaDoc nl=node.getChildNodes();
309             for (int j=0; j<nl.getLength(); j++) {
310                Node JavaDoc sn=nl.item(j);
311                if (sn instanceof Element JavaDoc) {
312                   cel.setValue(XMLUtil.getContent(sn,true));
313                   break;
314                }
315             }
316          }
317          // Specific code for handling ExtendedAttribute element
318
if (cel instanceof ExtendedAttribute) {
319             cel.setValue(XMLUtil.getChildNodesContent(node));
320          }
321          Iterator JavaDoc it=cel.getXMLElements().iterator();
322          while (it.hasNext()) {
323             XMLElement el=(XMLElement)it.next();
324             String JavaDoc elName=el.toName();
325             if (el instanceof XMLComplexElement) {
326                Node JavaDoc child = getChildByName(node,nameSpacePrefix+elName);
327                fromXML(child, (XMLComplexElement)el);
328             // Specific case if element is Deadlines
329
} else if (el instanceof Deadlines) {
330                fromXML(node, (XMLCollection)el);
331             } else if (el instanceof XMLCollection) {
332                Node JavaDoc child = getChildByName(node,nameSpacePrefix+elName);
333                fromXML(child, (XMLCollection)el);
334             } else if (el instanceof XMLComplexChoice) {
335                fromXML(node, (XMLComplexChoice)el);
336             } else if (el instanceof XMLSimpleElement) {
337                Node JavaDoc child = getChildByName(node,nameSpacePrefix+elName);
338                fromXML(child,(XMLSimpleElement)el);
339             }
340          }
341       }
342    }
343
344    public static void fromXML (Node JavaDoc node,XMLComplexChoice el) {
345       String JavaDoc nameSpacePrefix=getNameSpacePrefix(node);
346       List JavaDoc ch=el.getChoices();
347 if (logging) System.out.println("FROMXML for "+el.toName()+", c="+el.getClass().getName());
348       for (int i=0; i<ch.size(); i++) {
349          XMLElement chc=(XMLElement)ch.get(i);
350          String JavaDoc chname=chc.toName();
351          // Specific code for handling Tools
352
if (chname.equals("Tools")) {
353             chname="Tool";
354          }
355          Node JavaDoc child = getChildByName(node,nameSpacePrefix+chname);
356          if (child!=null) {
357             if (chc instanceof XMLComplexElement) {
358                fromXML(child,(XMLComplexElement)chc);
359             } else { // it is XMLCollection
360
// Specific code for handling Tools
361
if (chc instanceof Tools) {
362                   fromXML(node, (XMLCollection)chc);
363                } else {
364                   fromXML(child, (XMLCollection)chc);
365                }
366             }
367             el.setChoosen(chc);
368             break;
369          }
370       }
371    }
372
373    public static void fromXML (Node JavaDoc node,XMLSimpleElement el) {
374       fromXMLBasic(node, el);
375    }
376
377    public static void fromXML (Node JavaDoc node,XMLAttribute el) {
378       fromXMLBasic(node,el);
379    }
380
381    public static void fromXMLBasic (Node JavaDoc node,XMLElement el) {
382       if (node!=null) {
383 if (logging) System.out.println("FROMXML for "+el.toName()+", c="+el.getClass().getName());
384          String JavaDoc newVal;
385          if (node.hasChildNodes()) {
386             newVal=node.getChildNodes().item(0).getNodeValue();
387 if (logging) System.out.println("11111");
388             // should never happen
389
} else {
390 if (logging) System.out.println("22222");
391             newVal=node.getNodeValue();
392          }
393 if (logging) System.out.println("NV="+newVal);
394
395          if (newVal!=null) {
396             el.setValue(newVal);
397          }
398       }
399    }
400
401
402    public static void toXML (Document JavaDoc parent,Package JavaDoc pkg) {
403       Node JavaDoc node = ((Document JavaDoc) parent).createElement(pkg.toName());
404       ((Element JavaDoc) node).setAttribute("xmlns", XMLNS);
405       //((Element) node).setAttribute("xmlns:xpdl", XMLNS_XPDL);
406
// save additional namespaces
407
Iterator JavaDoc itNs=pkg.getNamespaces().toElements().iterator();
408       while (itNs.hasNext()) {
409          Namespace ns=(Namespace)itNs.next();
410          ((Element JavaDoc) node).setAttribute("xmlns:"+ns.getName(),
411                                        ns.getLocation());
412       }
413       ((Element JavaDoc) node).setAttribute("xmlns:xsi", XMLNS_XSI);
414       ((Element JavaDoc) node).setAttribute("xsi:schemaLocation", XSI_SCHEMA_LOCATION);
415
416       toXML(node,(XMLComplexElement)pkg);
417       parent.appendChild( node );
418    }
419
420    public static void toXML (Node JavaDoc parent,XMLCollection cel) {
421       if (!cel.isEmpty() || cel.isRequired()) {
422          if (parent!=null) {
423             String JavaDoc elName=cel.toName();
424             Node JavaDoc node = parent;
425             // Specific code for handling Deadlines and Tools
426
if (!(elName.equals("Deadlines") || elName.equals("Tools"))) {
427                node=(parent.getOwnerDocument()).createElement(elName);
428             }
429             for (Iterator JavaDoc it = cel.toElements().iterator(); it.hasNext();) {
430                XMLElement el=(XMLElement)it.next();
431                if (el instanceof XMLSimpleElement) {
432                   toXML(node,(XMLSimpleElement)el);
433                } else {
434                   toXML(node,(XMLComplexElement)el);
435                }
436             }
437             // If Deadlines or Tools are handled, node==parent
438
if (node!=parent) {
439                parent.appendChild(node);
440             }
441          }
442       }
443    }
444
445    public static void toXML (Node JavaDoc parent,XMLComplexElement cel) {
446       if ( cel.isEmpty() && !cel.isRequired() )
447          return;
448       if ( parent != null ) {
449 if (logging) System.out.println("TOXML for "+cel.toName()+", c="+cel.getClass().getName());
450          Node JavaDoc node=parent;
451          // Specific code for handling Package
452
if (!(cel instanceof Package JavaDoc)) {
453             node = ( parent.getOwnerDocument() ).createElement( cel.toName() );
454          }
455          if (cel.toValue()!=null && cel.toValue().length()>0) {
456             // Specific code for handling Condition
457
if (cel instanceof Condition) {
458                if (!cel.toValue().equals("")) {
459                   Node JavaDoc textNode=node.getOwnerDocument().createTextNode(cel.toValue());
460                   node.appendChild(textNode);
461                }
462             }
463             // Specific code for handling SchemaType
464
if (cel instanceof SchemaType) {
465                Node JavaDoc schema=XMLUtil.parseSchemaNode(cel.toValue(), false);
466                if (schema!=null) {
467                   node.appendChild(node.getOwnerDocument().importNode(schema,true));
468                }
469             }
470             // Specific code for handling ExtendedAttribute
471
if (cel instanceof ExtendedAttribute) {
472                try {
473                   Node JavaDoc n=XMLUtil.parseExtendedAttributeContent(cel.toValue());
474                   NodeList JavaDoc nl=n.getChildNodes();
475                   for (int i=0; i<nl.getLength(); i++) {
476                      node.appendChild(parent.getOwnerDocument().importNode(nl.item(i),true));
477                   }
478                } catch (Exception JavaDoc ex) {}
479             }
480          }
481          for ( Iterator JavaDoc it = cel.toElements().iterator(); it.hasNext(); ) {
482             XMLElement el = ( XMLElement ) it.next();
483             if (el instanceof XMLComplexElement) {
484                toXML(node, (XMLComplexElement)el);
485             } else if (el instanceof XMLCollection) {
486                toXML(node, (XMLCollection)el);
487             } else if (el instanceof XMLComplexChoice) {
488                toXML(node, (XMLComplexChoice)el);
489             } else if (el instanceof XMLSimpleElement) {
490                toXML(node,(XMLSimpleElement)el);
491             } else { // it's XMLAttribute
492
toXML(node,(XMLAttribute)el);
493             }
494          }
495          // If Package is handled, parent==node
496
if (node!=parent) {
497             parent.appendChild( node );
498          }
499       }
500    }
501
502    public static void toXML (Node JavaDoc parent,XMLComplexChoice el) {
503       XMLElement choosen=el.getChoosen();
504       if (choosen!=null) {
505          if (choosen instanceof XMLComplexElement) {
506             toXML(parent,(XMLComplexElement)choosen);
507          } else {
508             toXML(parent,(XMLCollection)choosen);
509          }
510       }
511    }
512
513    public static void toXML (Node JavaDoc parent,XMLSimpleElement el) {
514       if (!el.isEmpty() || el.isRequired()) {
515          if (parent!=null) {
516             Node JavaDoc node = (parent.getOwnerDocument()).createElement(el.toName());
517             node.appendChild(parent.getOwnerDocument().createTextNode(el.toValue().trim()));
518             parent.appendChild(node);
519          }
520       }
521    }
522
523    public static void toXML (Node JavaDoc parent,XMLAttribute el) {
524       if (!el.isEmpty() || el.isRequired()) {
525          if (parent!=null) {
526             Attr JavaDoc node = (parent.getOwnerDocument()).createAttribute(el.toName());
527             node.setValue(el.toValue().trim());
528             ((Element JavaDoc) parent).setAttributeNode(node);
529          }
530       }
531    }
532
533    public static String JavaDoc getNameSpacePrefix (Node JavaDoc node) {
534       String JavaDoc nameSpacePrefix=node.getPrefix();
535       if (nameSpacePrefix!=null) {
536          nameSpacePrefix+=":";
537       } else {
538          nameSpacePrefix="";
539       }
540       return nameSpacePrefix;
541    }
542
543    public static Node JavaDoc getChildByName(Node JavaDoc parent,String JavaDoc childName) {
544       NodeList JavaDoc children = parent.getChildNodes();
545       for (int i = 0; i < children.getLength(); ++i) {
546          Node JavaDoc child = (Node JavaDoc) children.item(i);
547          if (child.getNodeName().equals(childName)) {
548             return child;
549          }
550       }
551       return null;
552    }
553
554    public static String JavaDoc getId (Node JavaDoc node) {
555       try {
556          NamedNodeMap JavaDoc nnm=node.getAttributes();
557          Node JavaDoc attrib=nnm.getNamedItem("Id");
558          Object JavaDoc ID;
559          if (attrib.hasChildNodes()) {
560             ID=attrib.getChildNodes().item(0).getNodeValue();
561          } else {
562             ID=attrib.getNodeValue();
563          }
564          return ID.toString();
565       } catch (Exception JavaDoc ex) {
566          return "";
567       }
568    }
569
570    public static String JavaDoc getContent (Node JavaDoc node,boolean omitXMLDeclaration) {
571       try {
572          ByteArrayOutputStream JavaDoc baos=new ByteArrayOutputStream JavaDoc();
573
574          // Use a Transformer for output
575
TransformerFactory JavaDoc tFactory =
576             TransformerFactory.newInstance();
577          Transformer JavaDoc transformer = tFactory.newTransformer();
578          transformer.setOutputProperty("indent","yes");
579          transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
580          transformer.setOutputProperty("encoding","UTF-8");
581          if (omitXMLDeclaration) {
582             transformer.setOutputProperty("omit-xml-declaration","yes");
583          }
584
585          DOMSource JavaDoc source = new DOMSource JavaDoc(node);
586          StreamResult JavaDoc result = new StreamResult JavaDoc(baos);
587          transformer.transform(source,result);
588
589          String JavaDoc cont=baos.toString("UTF8");
590
591          baos.close();
592          return cont;
593       } catch (Exception JavaDoc ex) {
594          return "";
595       }
596    }
597
598    public static String JavaDoc getChildNodesContent (Node JavaDoc node) {
599       String JavaDoc txt="";
600       if (node!=null) {
601          if (node.hasChildNodes()) {
602             txt=XMLUtil.getContent(node,true);
603             try {
604                Node JavaDoc fc=node.getFirstChild();
605                String JavaDoc fcnc=XMLUtil.getContent(fc,true);
606                String JavaDoc closedTag="</"+node.getNodeName()+">";
607                if (fcnc.trim().length()>0) {
608                   fcnc=fcnc.trim();
609                }
610
611                int i1,i2;
612                i1=txt.indexOf(fcnc);
613                i2=txt.lastIndexOf(closedTag);
614                txt=txt.substring(i1,i2).trim();
615             } catch (Exception JavaDoc ex) {
616                NodeList JavaDoc nl=node.getChildNodes();
617                txt="";
618                try {
619                   for (int i=0; i<nl.getLength(); i++) {
620                      Node JavaDoc sn=nl.item(i);
621                      if (sn instanceof Element JavaDoc) {
622                         txt+=XMLUtil.getContent(sn,true);
623                      } else {
624                         String JavaDoc nv=sn.getNodeValue();
625                         // trim only the begining of the string
626
if (i>0) {
627                            txt+=nv.substring(1);
628                         } else if (i==0 && nv.trim().length()==0) {
629                            continue;
630                         } else {
631                            txt+=nv;
632                         }
633                      }
634                   }
635                } catch (Exception JavaDoc ex2){}
636             }
637          }
638       }
639       return txt;
640    }
641
642    public static String JavaDoc getShortClassName (String JavaDoc fullClassName) {
643       int lastDot=fullClassName.lastIndexOf(".");
644       if (lastDot>=0) {
645          return fullClassName.substring(lastDot+1,fullClassName.length());
646       }
647       return fullClassName;
648    }
649
650    public static String JavaDoc getExternalPackageId (String JavaDoc extPkgHref) {
651 // System.out.println("EPID1="+extPkgHref);
652
int indBSL=extPkgHref.lastIndexOf("\\");
653       int indSL=extPkgHref.lastIndexOf("/");
654       int indDotXPDL=extPkgHref.lastIndexOf(".xpdl");
655       if (indSL!=-1 || indBSL!=-1) {
656          int ind=indSL;
657          if (indBSL>indSL) {
658             ind=indBSL;
659          }
660          extPkgHref=extPkgHref.substring(indSL+1);
661       }
662       if (indDotXPDL!=-1) {
663          extPkgHref=extPkgHref.substring(0,extPkgHref.length()-5);
664       }
665 // System.out.println("EPID2="+extPkgHref);
666
return extPkgHref;
667    }
668
669    public static Node JavaDoc parseSchemaNode (String JavaDoc toParse,boolean isFile) {
670       Document JavaDoc document=null;
671
672       DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
673       factory.setValidating(false);
674
675       // Parse the Document and traverse the DOM
676
try {
677          ParsingErrors pErrors=new ParsingErrors();
678
679          DocumentBuilder JavaDoc parser = factory.newDocumentBuilder();
680          parser.setErrorHandler(pErrors);
681          //document=parser.parse(refToFile);
682
if (isFile) {
683             File JavaDoc f=new File JavaDoc(toParse);
684             if (!f.exists()) {
685                throw new Exception JavaDoc();
686             //f=new File(f.getCanonicalPath());
687
} else {
688                document=parser.parse(new InputSource JavaDoc(new FileInputStream JavaDoc(f))); // Fixed by Harald Meister
689
}
690          } else {
691             document=parser.parse(new InputSource JavaDoc(new StringReader JavaDoc(toParse)));
692          }
693
694
695          Set JavaDoc errorMessages = pErrors.getErrorMessages();
696          if (errorMessages.size()>0) {
697             System.err.println("Errors in schema type");
698          }
699       } catch (Exception JavaDoc ex) {
700          System.err.println("Fatal error while parsing xml schema document");
701          return null;
702       }
703       if (document!=null) {
704          return document.getDocumentElement();
705       } else {
706          return null;
707       }
708    }
709
710    public static String JavaDoc stringifyExtendedAttributes(ExtendedAttributes extAttribs) throws Exception JavaDoc {
711       try {
712          ExtendedAttributes easclone=(ExtendedAttributes)extAttribs.clone();
713          easclone.setParent(null);
714          Iterator JavaDoc it=easclone.toElements().iterator();
715          while (it.hasNext()) {
716             ExtendedAttribute ea=(ExtendedAttribute)it.next();
717             ea.setParent(null);
718             ea.get("Name").setParent(null);
719             ea.get("Value").setParent(null);
720          }
721          
722          return XMLUtil.getExtendedAttributesString(easclone);
723 // byte[] eas=XMLUtil.serialize(easclone);
724
// return Base64.encode(eas);
725
} catch (Throwable JavaDoc thr) {
726          throw new Exception JavaDoc("Can't stringify extended attributes, error="+thr.getMessage()+" !");
727       }
728    }
729
730    public static ExtendedAttributes destringyfyExtendedAttributes(String JavaDoc extAttribs) throws Exception JavaDoc {
731       ExtendedAttributes extAttr=null;
732       if (extAttribs != null && !extAttribs.trim().equals("")) {
733          try {
734             DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
735             factory.setNamespaceAware(true);
736
737             DocumentBuilder JavaDoc parser = factory.newDocumentBuilder();
738
739             Document JavaDoc document=null;
740             document=parser.parse(new InputSource JavaDoc(new StringReader JavaDoc(extAttribs)));
741
742             extAttr=new ExtendedAttributes(null);
743             if (document!=null) {
744                fromXML(document.getDocumentElement(),extAttr);
745             }
746             
747 // byte[] eas=Base64.decode(extAttribs);
748
// extAttr=(ExtendedAttributes)XMLUtil.deserialize(eas);
749
return extAttr;
750          } catch (Throwable JavaDoc thr) {
751             thr.printStackTrace();
752             throw new Exception JavaDoc("Failed to destringify extended attributes, error="+thr.getMessage()+" !");
753          }
754       }
755
756       return extAttr;
757    }
758
759    public static Node JavaDoc parseExtendedAttributeContent (String JavaDoc toParse) {
760       Document JavaDoc document=null;
761
762       DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
763       factory.setValidating(false);
764
765       try {
766          ParsingErrors pErrors=new ParsingErrors();
767
768          DocumentBuilder JavaDoc parser = factory.newDocumentBuilder();
769          parser.setErrorHandler(pErrors);
770          // adding helper tag, so after parsing, all its children
771
// will be taken into account
772
toParse="<ExtAttribsAddition>"+toParse+"</ExtAttribsAddition>";
773          document=parser.parse(new InputSource JavaDoc(new StringReader JavaDoc(toParse)));
774          Set JavaDoc errorMessages = pErrors.getErrorMessages();
775          if (errorMessages.size()>0) {
776             System.err.println("Errors in ext attribs complex content");
777          }
778       } catch (Exception JavaDoc ex) {
779          System.err.println("Fatal error while parsing ext. attributes complex content "+toParse);
780          return null;
781       }
782       if (document!=null) {
783          return document.getDocumentElement();
784       } else {
785          return null;
786       }
787
788    }
789
790    public static String JavaDoc getExtendedAttributeValue(String JavaDoc[][] extendedAttributes, String JavaDoc extAttrName) {
791       if (extendedAttributes != null) {
792          for (int i = 0; i < extendedAttributes.length; i++) {
793             if (extendedAttributes[i][0].equals(extAttrName)) {
794                return extendedAttributes[i][1];
795             }
796          }
797       }
798       return null;
799    }
800    
801    public static Package JavaDoc getPackage(XMLElement el) {
802       while (!(el instanceof Package JavaDoc)) {
803          el = el.getParent();
804          if (el == null)
805             break;
806       }
807       return (Package JavaDoc) el;
808    }
809
810    public static WorkflowProcess getWorkflowProcess(XMLElement el) {
811       while (!(el instanceof WorkflowProcess)) {
812          el = el.getParent();
813          if (el == null)
814             break;
815       }
816       return (WorkflowProcess) el;
817    }
818
819    public static Activity getActivity(XMLElement el) {
820       while (!(el instanceof Activity)) {
821          el = el.getParent();
822          if (el == null)
823             break;
824       }
825       return (Activity) el;
826    }
827
828    public static Join getJoin (Activity act) {
829       Join j=null;
830       TransitionRestrictions trs=act.getTransitionRestrictions();
831       if (trs.size()>0) {
832          j=((TransitionRestriction)trs.get(0)).getJoin();
833       }
834       return j;
835    }
836
837    public static Split getSplit (Activity act) {
838       Split s=null;
839       TransitionRestrictions trs=act.getTransitionRestrictions();
840       if (trs.size()>0) {
841          s=((TransitionRestriction)trs.get(0)).getSplit();
842       }
843       return s;
844    }
845
846    public static Set JavaDoc getOutgoingTransitions (Activity act) {
847       Set JavaDoc s=new HashSet JavaDoc();
848       Iterator JavaDoc it=((Transitions)((XMLCollectionElement)act.getParent().getParent()).get("Transitions")).toElements().iterator();
849       while (it.hasNext()) {
850          Transition t=(Transition)it.next();
851          if (t.getFrom().equals(act.getId())) {
852             s.add(t);
853          }
854       }
855       return s;
856    }
857
858    public static Set JavaDoc getExceptionalOutgoingTransitions (Activity act) {
859       Set JavaDoc s=new HashSet JavaDoc();
860       Iterator JavaDoc it=((Transitions)((XMLCollectionElement)act.getParent().getParent()).get("Transitions")).toElements().iterator();
861       while (it.hasNext()) {
862          Transition t=(Transition)it.next();
863          if (t.getFrom().equals(act.getId())) {
864             String JavaDoc ct=t.getCondition().getType();
865             if (ct.equals(XPDLConstants.CONDITION_TYPE_EXCEPTION) ||
866                   ct.equals(XPDLConstants.CONDITION_TYPE_DEFAULTEXCEPTION)) {
867                s.add(t);
868             }
869          }
870       }
871       return s;
872    }
873
874    public static Set JavaDoc getNonExceptionalOutgoingTransitions (Activity act) {
875       Set JavaDoc s=new HashSet JavaDoc();
876       Iterator JavaDoc it=((Transitions)((XMLCollectionElement)act.getParent().getParent()).get("Transitions")).toElements().iterator();
877       while (it.hasNext()) {
878          Transition t=(Transition)it.next();
879          if (t.getFrom().equals(act.getId())) {
880             String JavaDoc ct=t.getCondition().getType();
881             if (!(ct.equals(XPDLConstants.CONDITION_TYPE_EXCEPTION) ||
882                   ct.equals(XPDLConstants.CONDITION_TYPE_DEFAULTEXCEPTION))) {
883                s.add(t);
884             }
885          }
886       }
887       return s;
888    }
889
890    public static Set JavaDoc getIncomingTransitions (Activity act) {
891       Set JavaDoc s=new HashSet JavaDoc();
892       Iterator JavaDoc it=((Transitions)((XMLCollectionElement)act.getParent().getParent()).get("Transitions")).toElements().iterator();
893       while (it.hasNext()) {
894          Transition t=(Transition)it.next();
895          if (t.getTo().equals(act.getId())) {
896             s.add(t);
897          }
898       }
899       return s;
900    }
901
902    public static Activity getFromActivity (Transition t) {
903       return ((Activities)((XMLCollectionElement)t.getParent().getParent()).get("Activities")).getActivity(t.getFrom());
904    }
905
906    public static Activity getToActivity (Transition t) {
907       return ((Activities)((XMLCollectionElement)t.getParent().getParent()).get("Activities")).getActivity(t.getTo());
908    }
909
910    /**
911     * Checks if Id is valid NMTOKEN string.
912     */

913    public static boolean isIdValid (String JavaDoc id) {
914       return XMLChar.isValidNmtoken(id);
915    }
916    
917    
918    public static WorkflowProcess getSubflowProcess (XMLInterface xmlInterface,Activity sbflwAct) {
919       if (sbflwAct.getActivityType()!=XPDLConstants.ACTIVITY_TYPE_SUBFLOW) return null;
920       Package JavaDoc pkg=XMLUtil.getPackage(sbflwAct);
921       SubFlow s=sbflwAct.getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
922       String JavaDoc subflowID=s.getId();
923
924       WorkflowProcess wp=pkg.getWorkflowProcess(subflowID);
925       if (wp==null) {
926          List JavaDoc l=XMLUtil.getAllExternalPackageIds(xmlInterface, pkg);
927          Iterator JavaDoc it=l.iterator();
928          while (it.hasNext()) {
929             Package JavaDoc p=xmlInterface.getPackageById((String JavaDoc)it.next());
930             if (p!=null) {
931                wp=p.getWorkflowProcess(subflowID);
932                if (wp!=null) {
933                   break;
934                }
935             }
936          }
937       }
938       //System.out.println("Found Subprocess is "+((wp!=null) ? wp.getId() : "null"));
939
return wp;
940    }
941
942    public static List JavaDoc getAllExternalPackageIds (XMLInterface xmli,Package JavaDoc pkg) {
943       List JavaDoc l=new ArrayList JavaDoc();
944       List JavaDoc workingList=new ArrayList JavaDoc(pkg.getExternalPackageIds());
945       Iterator JavaDoc it=workingList.iterator();
946       while (it.hasNext()) {
947          Package JavaDoc p=xmli.getPackageById((String JavaDoc)it.next());
948          if (p!=null) {
949             l.add(p.getId());
950             l.addAll(getAllExternalPackageIds(xmli, p));
951          }
952       }
953       return l;
954    }
955
956    /**
957     * Returns the set of (XML) activities that have split or join.
958     * @param acts The activities graph objects that are checked if their
959     * XML object have split or join, depending on the second parameter.
960     * @param sOrJ if 0, activity is checked for split, otherwise it is
961     * checked for join
962     */

963    public static Set JavaDoc getSplitOrJoinActivities (Collection JavaDoc acts,int sOrJ) {
964       Set JavaDoc sOrJactivities=new HashSet JavaDoc();
965       if (acts==null) return sOrJactivities;
966       Iterator JavaDoc it=acts.iterator();
967       while (it.hasNext()) {
968          Activity act=(Activity)it.next();
969          Iterator JavaDoc iter;
970          if (sOrJ==0) {
971             iter=getOutgoingTransitions(act).iterator();
972          } else {
973             iter=getIncomingTransitions(act).iterator();
974          }
975          int noOfTrans=0;
976          while (iter.hasNext()) {
977             Transition t = (Transition)iter.next();
978             noOfTrans++;
979          }
980          if (noOfTrans>1) {
981             sOrJactivities.add(act);
982          }
983       }
984
985       return sOrJactivities;
986    }
987
988    /**
989     * Returns the set of BlockActivity objects contained within given
990     * process or block activity. If the BlockActivity objects contains
991     * other BlockActivity objects, and the second parameter is set to true,
992     * these are also returned, and so on - which means that
993     * implementation is recursive.
994     */

995    public static Set JavaDoc getBlockActivities(XMLComplexElement wpOrAs,boolean recursivly) {
996       Collection JavaDoc allActs=((Activities)wpOrAs.get("Activities")).toElements();
997       Set JavaDoc bas=new HashSet JavaDoc();
998       Iterator JavaDoc it=allActs.iterator();
999       Activity act;
1000      while (it.hasNext()) {
1001         act=(Activity)it.next();
1002         BlockActivity ba=act.getActivityTypes().getBlockActivity();
1003         if (ba!=null) {
1004            bas.add(act);
1005            if (!recursivly) continue;
1006            ActivitySets ass=getWorkflowProcess(act).getActivitySets();
1007            String JavaDoc asId=ba.getBlockId();
1008            ActivitySet as=ass.getActivitySet(asId);
1009            if (as!=null) {
1010               bas.addAll(getBlockActivities(as,true));
1011            }
1012         }
1013      }
1014      return bas;
1015   }
1016
1017
1018   /**
1019    * Returns predefined conformanceClass number.
1020    * @param conformanceClass The conformance class we are looking for number
1021    * @return 0 if conformance class is NON_BLOCKED, 1 if conformance class is
1022    * LOOP_BLOCKED, 2 if conformance class is FULL_BLOCKED, and -1 otherwise
1023    */

1024   public static int getConformanceClassNo (String JavaDoc conformanceClass) {
1025      if (conformanceClass.equals(XPDLConstants.GRAPH_CONFORMANCE_NON_BLOCKED)) {
1026         return 0;
1027      } else if (conformanceClass.equals(XPDLConstants.GRAPH_CONFORMANCE_LOOP_BLOCKED)) {
1028         return 1;
1029      } else if (conformanceClass.equals(XPDLConstants.GRAPH_CONFORMANCE_FULL_BLOCKED)) {
1030         return 2;
1031      } else {
1032         return -1;
1033      }
1034   }
1035
1036   /**
1037    * Converts a file specified by the path, to the String.
1038    */

1039   public static String JavaDoc fileToString (String JavaDoc fileName) {
1040      if (fileName != null) {
1041         //String sLine;
1042
byte[] utf8Bytes;
1043         String JavaDoc sFile = new String JavaDoc();
1044         // Reading input by lines:
1045
try {
1046            FileInputStream JavaDoc fis=new FileInputStream JavaDoc(fileName);
1047            int noOfBytes=fis.available();
1048            if (noOfBytes>0) {
1049               utf8Bytes=new byte[noOfBytes];
1050               fis.read(utf8Bytes);
1051               sFile=new String JavaDoc(utf8Bytes,"UTF8");
1052            }
1053         }
1054         catch (Exception JavaDoc ex) {
1055            return null;
1056         }
1057         return sFile;
1058      }
1059      return null;
1060   }
1061   //******** END OF CREATING SCROLLPANE AND EDITOR COMPONENT(PEJGRAPH) **********
1062

1063   /** Gets the current date and time string in ISO-8601 format. */
1064   public static String JavaDoc getCurrentDateAndTime () {
1065      String JavaDoc dateSeparator="-";
1066      String JavaDoc timeSeparator=":";
1067      Calendar JavaDoc cal=new GregorianCalendar JavaDoc();
1068      String JavaDoc dateTime="";
1069      dateTime=dateTime+String.valueOf(cal.get(Calendar.YEAR))+dateSeparator;
1070      int mnth=cal.get(Calendar.MONTH)+1;
1071      if (mnth<10) {
1072         dateTime=dateTime+"0";
1073      }
1074      dateTime=dateTime+String.valueOf(mnth)+dateSeparator;
1075      int dayOfMnth=cal.get(Calendar.DAY_OF_MONTH);
1076      if (dayOfMnth<10) {
1077         dateTime=dateTime+"0";
1078      }
1079      dateTime=dateTime+String.valueOf(dayOfMnth)+" ";
1080      int hr=cal.get(Calendar.HOUR_OF_DAY);
1081      int ampm=cal.get(Calendar.AM_PM);
1082      if (ampm==Calendar.PM && hr<12) {
1083         hr+=12;
1084      }
1085      if (hr<10) {
1086         dateTime=dateTime+"0";
1087      }
1088      dateTime=dateTime+String.valueOf(hr)+timeSeparator;
1089      int min=cal.get(Calendar.MINUTE);
1090      if (min<10) {
1091         dateTime=dateTime+"0";
1092      }
1093      dateTime=dateTime+String.valueOf(min)+timeSeparator;
1094      int sec=cal.get(Calendar.SECOND);
1095      if (sec<10) {
1096         dateTime=dateTime+"0";
1097      }
1098      dateTime=dateTime+String.valueOf(sec);
1099
1100      return dateTime;
1101   }
1102
1103   /**
1104    * Checks if formal and actual parameters are matched by number and by type.
1105    * @return 0 - if parameters are matched, 1 - if numbere of formal and
1106    * actual parameters is not the same, 2 - if types of parameters are not
1107    * matched
1108    */

1109   public static int checkParameterMatching (FormalParameters fps,ActualParameters aps) {
1110      if (fps==null || aps==null || fps.size()!=aps.size()) {
1111         return 1;
1112      }
1113
1114      for (int i=0; i<fps.size(); i++) {
1115         FormalParameter fp=(FormalParameter)fps.get(i);
1116         ActualParameter ap=(ActualParameter)aps.get(i);
1117
1118         String JavaDoc fpMode=fp.getMode();
1119
1120         // if the formal parameter mode is IN, do not check validity because
1121
// that could be expression written in any scripting language
1122
if (fpMode.equals(XPDLConstants.FORMAL_PARAMETER_MODE_IN)) continue;
1123
1124         // find the type of formal param.
1125
DataType fpdt=fp.getDataType();
1126         DataTypes fpdtt=fpdt.getDataTypes();
1127         XMLElement fpType=fpdtt.getChoosen();
1128
1129         // find the type of actual param.
1130
Map JavaDoc idToDFOrFP=XMLUtil.getWorkflowProcess(aps).getAllVariables();
1131         String JavaDoc apWRD=ap.toValue();
1132         XMLCollectionElement ce=(XMLCollectionElement)idToDFOrFP.get(apWRD);
1133         // if the actual parameter is an expression, and the mode is not
1134
// IN, return 2, which signals that parameter types don't match
1135
if (ce==null) {
1136            return 2;
1137         }
1138         XMLElement apType=null;
1139         DataType apdt=(DataType)ce.get("DataType");
1140         DataTypes apdtt=apdt.getDataTypes();
1141         apType=apdtt.getChoosen();
1142
1143         if (fpType.getClass().equals(apType.getClass())) {
1144            // if this is BasicType check for subtype matching
1145
if (fpType instanceof BasicType) {
1146               String JavaDoc fpAT=((BasicType)fpType).getType();
1147               String JavaDoc apAT=((BasicType)apType).getType();
1148               if (!fpAT.equals(apAT)) {
1149                  return 2;
1150               }
1151            }
1152            // if this is EnumerationType check for Enumeration values matching
1153
if (fpType instanceof EnumerationType) {
1154               // first check the size of enums
1155
if (((EnumerationType)fpType).size()!=((EnumerationType)apType).size()) {
1156                  return 2;
1157               }
1158               // check the enum elements values
1159
for (int j=0; j<((EnumerationType)fpType).size(); j++) {
1160                  EnumerationValue evFP=(EnumerationValue)((EnumerationType)fpType).get(j);
1161                  EnumerationValue evAP=(EnumerationValue)((EnumerationType)apType).get(j);
1162                  if (!evFP.getName().equals(evAP.getName())) {
1163                     return 2;
1164                  }
1165               }
1166            }
1167            // if this is DeclaredType check if their IDs are the same
1168
if (fpType instanceof DeclaredType) {
1169               if (!((DeclaredType)fpType).getId().
1170                   equals(((DeclaredType)apType).getId())) {
1171                  return 2;
1172               }
1173            }
1174
1175         } else {
1176            return 2;
1177         }
1178      }
1179      return 0;
1180   }
1181
1182   public static String JavaDoc replaceBackslashesWithSlashes (String JavaDoc repBS) {
1183      if (repBS!=null) {
1184         int ind=-1;
1185         while ((ind=repBS.indexOf("\\"))!=-1) {
1186            repBS=repBS.substring(0,ind)+"/"+repBS.substring(ind+1);
1187         }
1188      }
1189      return repBS;
1190   }
1191
1192   public static String JavaDoc getExtendedAttributesString (ExtendedAttributes eas) throws Exception JavaDoc {
1193      Document JavaDoc document = null;
1194
1195      DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
1196      DocumentBuilder JavaDoc dbuilder = dbf.newDocumentBuilder();
1197      document = dbuilder.newDocument();
1198      Node JavaDoc eac=document.createElement("EAC");
1199      toXML(eac,eas);
1200
1201      String JavaDoc cont=XMLUtil.getContent(eac.getFirstChild(),true);
1202      return XMLUtil.getContent(eac.getFirstChild(),true);
1203   }
1204
1205   public static String JavaDoc getExtendedAttributesString (Node JavaDoc node) {
1206      String JavaDoc nameSpacePrefix=node.getPrefix();
1207      if (nameSpacePrefix!=null) {
1208         nameSpacePrefix+=":";
1209      } else {
1210         nameSpacePrefix="";
1211      }
1212      Node JavaDoc eas=getChildByName(node,nameSpacePrefix+"ExtendedAttributes");
1213      return XMLUtil.getContent(eas,true);
1214   }
1215
1216   public static Set JavaDoc getStartingActivities (XMLCollectionElement procOrASDef) {
1217      Activities acts=((Activities)procOrASDef.get("Activities"));
1218      Set JavaDoc starts=new HashSet JavaDoc();
1219      Iterator JavaDoc it=acts.toElements().iterator();
1220      Transitions ts=(Transitions)procOrASDef.get("Transitions");
1221      while (it.hasNext()) {
1222         Activity act=(Activity)it.next();
1223         Set JavaDoc trs=getIncomingTransitions(act);
1224         // the activity is starting one if it has no input transitions ...
1225
if (trs.size()==0) {
1226            starts.add(act);
1227            // or there is a one input transition, but it is a selfreference
1228
} else if (trs.size()==1) {
1229            Transition t=(Transition)trs.toArray()[0];
1230            if (t.getFrom().equals(t.getTo())) {
1231               starts.add(act);
1232            }
1233         }
1234      }
1235      return starts;
1236   }
1237
1238   public static Set JavaDoc getEndingActivities (XMLCollectionElement procOrASDef) {
1239      Activities acts=((Activities)procOrASDef.get("Activities"));
1240      Set JavaDoc ends=new HashSet JavaDoc();
1241      Iterator JavaDoc it=acts.toElements().iterator();
1242      Transitions ts=(Transitions)procOrASDef.get("Transitions");
1243      while (it.hasNext()) {
1244         Activity act=(Activity)it.next();
1245         Set JavaDoc trs=getNonExceptionalOutgoingTransitions(act);
1246         // the activity is ending one if it has no output transitions ...
1247
if (trs.size()==0) {
1248            ends.add(act);
1249            // or there is a one output transition, but it is a selfreference
1250
} else if (trs.size()==1) {
1251            Transition t=(Transition)trs.toArray()[0];
1252            if (t.getFrom().equals(t.getTo())) {
1253               ends.add(act);
1254            }
1255         }
1256      }
1257
1258      return ends;
1259   }
1260
1261
1262   /**
1263    * Returns the list of responsibles for the process, and responsibles
1264    * for whole package.
1265    */

1266   public static List JavaDoc getResponsibles (WorkflowProcess wp) {
1267      List JavaDoc resp=new ArrayList JavaDoc();
1268      RedefinableHeader rh=wp.getRedefinableHeader();
1269      Responsibles rsps=rh.getResponsibles();
1270      Iterator JavaDoc it=rsps.toElements().iterator();
1271      while (it.hasNext()) {
1272         Responsible rsp=(Responsible)it.next();
1273         if (!resp.contains(rsp)) {
1274            resp.add(rsp);
1275         }
1276      }
1277      // from package
1278
rh=getPackage(wp).getRedefinableHeader();
1279      rsps=rh.getResponsibles();
1280      it=rsps.toElements().iterator();
1281      while (it.hasNext()) {
1282         Responsible rsp=(Responsible)it.next();
1283         if (!resp.contains(rsp)) {
1284            resp.add(rsp);
1285         }
1286      }
1287      return resp;
1288   }
1289
1290   /**
1291    * Returns if given activity has AND type split or join.
1292    * @param act The activity that is checked if it has a AND type
1293    * split or join, depending on the second parameter.
1294    * @param sOrJ if 0, activity is checked for AND type split, otherwise it is
1295    * checked for AND type join
1296    * @return true if given activity has AND type split or join
1297    */

1298   public static boolean isANDTypeSplitOrJoin (Activity act,int sOrJ) {
1299      String JavaDoc sjType = XPDLConstants.JOIN_SPLIT_TYPE_XOR; // default type is XOR
1300

1301      if (sOrJ==0) { // it is split that we search for
1302
Split s=getSplit(act);
1303         if (s!=null) {
1304            sjType=s.getType();
1305         }
1306      } else { // it is join that we search for
1307
Join j=getJoin(act);
1308         if (j!=null) {
1309            sjType=j.getType();
1310         }
1311      }
1312
1313      if (sjType.equals(XPDLConstants.JOIN_SPLIT_TYPE_AND)) {
1314         return true;
1315      } else {
1316         return false;
1317      }
1318   }
1319
1320   public static boolean isSubflowSynchronous (Activity sbflwActivityDefinition) {
1321      String JavaDoc type = XPDLConstants.EXECUTION_SYNCHR;
1322      // Determine subflow type, if it is SYNCHR, terminate it
1323
SubFlow subflow=sbflwActivityDefinition.getActivityTypes().getImplementation().getImplementationTypes().getSubFlow();
1324      type = subflow.getExecution();
1325
1326      if (type.equals(XPDLConstants.EXECUTION_ASYNCHR)) {
1327         return false;
1328      } else {
1329         return true;
1330      }
1331   }
1332
1333   public static int getStartMode (Activity act) {
1334      int ret=XPDLConstants.ACTIVITY_MODE_AUTOMATIC;
1335      StartMode startMode = act.getStartMode();
1336      Object JavaDoc mode=startMode.getStartFinishModes().getChoosen();
1337      if(mode instanceof Manual) {
1338         ret=XPDLConstants.ACTIVITY_MODE_MANUAL;
1339      }
1340      return ret;
1341   }
1342
1343   public static int getFinishMode (Activity act) {
1344      int ret=XPDLConstants.ACTIVITY_MODE_AUTOMATIC;
1345      FinishMode finishMode = act.getFinishMode();
1346      Object JavaDoc mode=finishMode.getStartFinishModes().getChoosen();
1347      if(mode instanceof Manual) {
1348         ret=XPDLConstants.ACTIVITY_MODE_MANUAL;
1349      }
1350      return ret;
1351   }
1352
1353   public static OutputStream JavaDoc packageToStream (
1354      org.enhydra.shark.xpdl.elements.Package pkg,OutputStream JavaDoc os) {
1355      try {
1356         Document JavaDoc document = null;
1357
1358         DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
1359         DocumentBuilder JavaDoc dbuilder = dbf.newDocumentBuilder();
1360         document = dbuilder.newDocument();
1361
1362         // Here we get all document elements set
1363
toXML(document,pkg);
1364
1365         // Use a Transformer for output
1366
TransformerFactory JavaDoc tFactory =
1367            TransformerFactory.newInstance();
1368         Transformer JavaDoc transformer = tFactory.newTransformer();
1369         transformer.setOutputProperty("indent","yes");
1370         transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
1371         transformer.setOutputProperty("encoding","UTF-8");
1372         DOMSource JavaDoc source = new DOMSource JavaDoc(document);
1373         StreamResult JavaDoc result = new StreamResult JavaDoc(os);
1374         transformer.transform(source,result);
1375         return os;
1376      } catch (Exception JavaDoc ex) {
1377         ex.printStackTrace();
1378         return null;
1379      }
1380   }
1381
1382   public static List JavaDoc getOrderedOutgoingTransitions (Activity fromActDef,
1383                                                     Set JavaDoc outTransitions) {
1384      // the iteration should be done on TransitionReferences collection,
1385
// in order to make ordered transition's list
1386
Set JavaDoc otCopy=new HashSet JavaDoc(outTransitions);
1387      List JavaDoc orderedOutTransitions=new ArrayList JavaDoc();
1388      Map JavaDoc trIdToTr=new HashMap JavaDoc();
1389      Iterator JavaDoc it=outTransitions.iterator();
1390      while (it.hasNext()) {
1391         Transition trans=(Transition)it.next();
1392         trIdToTr.put(trans.getId(),trans);
1393      }
1394      Split s=getSplit(fromActDef);
1395      if (s!=null) {
1396         TransitionRefs trfs=s.getTransitionRefs();
1397         Iterator JavaDoc trefs=trfs.toElements().iterator();
1398         while (trefs.hasNext()) {
1399            TransitionRef tref=(TransitionRef)trefs.next();
1400            Transition trans=(Transition)trIdToTr.get(tref.getId());
1401            if (trans==null) continue;
1402            orderedOutTransitions.add(trans);
1403            otCopy.remove(trans);
1404         }
1405      }
1406      // if some of the transitions haven't been within transition refs
1407
// collection, put them into ordered transition list at the end
1408
orderedOutTransitions.addAll(otCopy);
1409      return orderedOutTransitions;
1410   }
1411
1412   public static String JavaDoc createPath (String JavaDoc basedir,String JavaDoc relpath) {
1413      basedir=XMLUtil.convertToSystemPath(basedir);
1414      relpath=XMLUtil.convertToSystemPath(relpath);
1415      return (basedir+File.separator+relpath);
1416   }
1417
1418   public static String JavaDoc convertToSystemPath (String JavaDoc path) {
1419      char separatorChar=File.separatorChar;
1420      char charToReplace;
1421      if (separatorChar=='\\') {
1422         charToReplace='/';
1423      } else {
1424         charToReplace='\\';
1425      }
1426
1427      String JavaDoc systemPath=path.replace(charToReplace,separatorChar);
1428      return systemPath;
1429   }
1430
1431
1432   public static void main (String JavaDoc[] args) throws Throwable JavaDoc {
1433      long t1,t2,t3, ts, te;
1434      ts=System.currentTimeMillis();
1435      boolean readExt=false;
1436      readExt=new Boolean JavaDoc(args[0]).booleanValue();
1437      for (int i=1; i<args.length; i++) {
1438         String JavaDoc inputFile=args[i];
1439System.out.println("Handling file "+inputFile);
1440         t1=System.currentTimeMillis();
1441         XMLInterface xmli=new XMLInterfaceForJDK13();
1442         Package JavaDoc pkg=readFromFile(xmli,inputFile,readExt);
1443Package JavaDoc p1=pkg;
1444         PackageValidator pv=new PackageValidator(xmli,pkg,true,readExt,true,true);
1445         System.out.println("VALIDATING ...");
1446         boolean valid=pv.validateAll(true);
1447         System.out.println("VALID="+valid);
1448         t2=System.currentTimeMillis();
1449         pkg.setReadOnly(true);
1450         writeToFile(xmli,inputFile+"r", pkg);
1451         t3=System.currentTimeMillis();
1452         pkg=clonePackage(pkg);
1453//System.out.println(pkg.getExtendedAttributes().eaMap);
1454
pkg.initCaches();
1455//System.out.println(pkg.getExtendedAttributes().eaMap);
1456
Package JavaDoc p2=pkg;
1457         long t4=System.currentTimeMillis();
1458         writeToFile(xmli,inputFile+"rr", pkg);
1459         long t5=System.currentTimeMillis();
1460         pkg=clonePackageBySerialization(pkg);
1461         System.out.println("P1=P2="+p1.equals(p2)+", P2=P3="+p2.equals(pkg));
1462         long t6=System.currentTimeMillis();
1463         writeToFile(xmli,inputFile+"rrr", pkg);
1464         long t7=System.currentTimeMillis();
1465         System.out.println("TOverall ="+(t6-t1));
1466         System.out.println("TOpenPKG "+(t2-t1));
1467         System.out.println("TSavePKG1 ="+(t3-t2));
1468         System.out.println("TClonePkg1 ="+(t4-t3));
1469         System.out.println("TSavePKG2 ="+(t5-t3));
1470         System.out.println("TClonePkg2 ="+(t6-t5));
1471         System.out.println("TSavePKG4 ="+(t7-t6));
1472      }
1473      te=System.currentTimeMillis();
1474      System.out.println("Handling of "+(args.length-1)+" XPDLs lasted "+((te-ts)/1000)+" sec");
1475   }
1476
1477   public static Package JavaDoc readFromFile (XMLInterface xmli,String JavaDoc inputFile,boolean readExt) throws Exception JavaDoc {
1478      return xmli.openPackage(inputFile, readExt);
1479   }
1480
1481   public static void writeToFile (XMLInterface xmli,String JavaDoc outputFile,Package JavaDoc pkg) throws Exception JavaDoc {
1482      System.out.println("PKGEPS="+pkg.getExternalPackageIds());
1483      Document JavaDoc document = null;
1484      DocumentBuilderFactory JavaDoc dbf = DocumentBuilderFactory.newInstance();
1485      DocumentBuilder JavaDoc dbuilder = dbf.newDocumentBuilder();
1486      document = dbuilder.newDocument();
1487      // output stream will either be the FileOutputStream in the
1488
// case of save as, or the ByteArrayOutputStream if we are
1489
// saving an existing file
1490
FileOutputStream JavaDoc os;
1491      // try to open random access file as rw, if it fails
1492
// the saving shouldn't occur
1493
os=new FileOutputStream JavaDoc(outputFile);
1494
1495      // Here we get all document elements set
1496
toXML(document,pkg);
1497
1498      // Use a Transformer for output
1499
TransformerFactory JavaDoc tFactory =
1500            TransformerFactory.newInstance();
1501      Transformer JavaDoc transformer = tFactory.newTransformer();
1502      transformer.setOutputProperty("indent","yes");
1503      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
1504      transformer.setOutputProperty("encoding","UTF8");
1505      DOMSource JavaDoc source = new DOMSource JavaDoc(document);
1506      StreamResult JavaDoc result = new StreamResult JavaDoc(os);
1507      transformer.transform(source,result);
1508
1509      os.close();
1510   }
1511
1512   public static Package JavaDoc clonePackage (Package JavaDoc pkg) throws Exception JavaDoc {
1513      Package JavaDoc cloned=(Package JavaDoc)pkg.clone();
1514      return cloned;
1515   }
1516
1517   public static Package JavaDoc clonePackageBySerialization (Package JavaDoc pkg) throws Exception JavaDoc {
1518      byte[] ser=serialize(pkg);
1519      Package JavaDoc cloned=(Package JavaDoc)deserialize(ser);
1520      return cloned;
1521   }
1522
1523   public static byte[] serialize(Object JavaDoc obj) throws Exception JavaDoc {
1524      //System.err.println(" ser ##"+obj);
1525
ByteArrayOutputStream JavaDoc bout = new ByteArrayOutputStream JavaDoc();
1526      ObjectOutputStream JavaDoc oout = new ObjectOutputStream JavaDoc(bout);
1527      oout.writeObject(obj);
1528      oout.flush();
1529      byte array[] = bout.toByteArray();
1530      oout.close();
1531      bout.close();
1532      //System.err.println(" ser #"+new String(array));
1533
return array;
1534   }
1535
1536   public static Object JavaDoc deserialize(byte[]array) throws Exception JavaDoc {
1537      //System.err.println("neser#"+new String(array));
1538
ObjectInputStream JavaDoc rin = new ObjectInputStream JavaDoc
1539         (new ByteArrayInputStream JavaDoc(array));
1540      Object JavaDoc obj = rin.readObject();
1541      rin.close();
1542      //System.err.println("neser##"+obj);
1543
return obj;
1544   }
1545
1546}
1547
1548
Popular Tags