KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > enhydra > jawe > xml > XMLUtil


1 /* XMLUtil.java
2  *
3  * Authors:
4  * Stefanovic Nenad chupo@iis.ns.ac.yu
5  * Bojanic Sasa sasaboy@neobee.net
6  * Puskas Vladimir vpuskas@eunet.yu
7  * Pilipovic Goran zboniek@uns.ac.yu
8  *
9  */

10
11 package org.enhydra.jawe.xml;
12
13 import org.enhydra.jawe.xml.elements.*;
14
15 import java.util.*;
16 import java.io.*;
17 import java.net.URL JavaDoc;
18 import javax.swing.*;
19 import java.awt.*;
20 import javax.swing.tree.*;
21
22 import javax.xml.transform.*;
23 import javax.xml.transform.dom.*;
24 import javax.xml.transform.stream.*;
25 import org.w3c.dom.*;
26
27 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
28 import javax.xml.parsers.DocumentBuilder JavaDoc;
29 import org.apache.xml.serialize.XMLSerializer;
30 import org.apache.xml.serialize.OutputFormat;
31 import org.apache.xerces.parsers.DOMParser;
32 import org.xml.sax.*;
33
34 import org.enhydra.jawe.xml.elements.Package;
35
36 /**
37  * Class which purpose is to provide static methods which are
38  * used by classes that represents program apstraction of
39  * XML elements. These methods offers support for reading or
40  * writting an XML document and for generating the tooltips for
41  * for the classes that needs it.
42  */

43 public class XMLUtil {
44
45    /** Used for tooltips */
46    private static final String JavaDoc EMPTY_STRING ="";
47    /** Used for tooltips */
48    private static final String JavaDoc HTML_OPEN ="<html>";
49    /** Used for tooltips */
50    private static final String JavaDoc HTML_CLOSE ="</html>";
51    /** Used for tooltips */
52    private static final String JavaDoc STRONG_OPEN ="<strong>";
53    /** Used for tooltips */
54    private static final String JavaDoc STRONG_CLOSE ="</strong>";
55    /** Used for tooltips */
56    private static final String JavaDoc LINE_BREAK ="<br>";
57    /** Used for tooltips */
58    private static final String JavaDoc COLON_SPACE =": ";
59
60    private static Window myWindow;
61
62    private static ResourceBundle defaultResources;
63    private static ResourceBundle choosenResources;
64    private static Properties properties;
65
66    // filter for XML files
67
private static XMLUtil.XMLFilter allFilter = new XMLUtil.XMLFilter(null);
68    private static XMLUtil.XMLFilter xmlFilter = new XMLUtil.XMLFilter("xml");
69    private static XMLUtil.XMLFilter xpdlFilter = new XMLUtil.XMLFilter("xpdl");
70    private static XMLUtil.XMLFilter jpgFilter = new XMLUtil.XMLFilter("jpg");
71    private static XMLUtil.XMLFilter svgFilter = new XMLUtil.XMLFilter("svg");
72    private static XMLUtil.XMLFilter txtFilter = new XMLUtil.XMLFilter("txt");
73
74    private static javax.swing.filechooser.FileFilter JavaDoc[] lastChoosenFilter=
75       new javax.swing.filechooser.FileFilter JavaDoc[5];
76    static {
77       lastChoosenFilter[0]=xpdlFilter;
78       lastChoosenFilter[1]=jpgFilter;
79       lastChoosenFilter[2]=svgFilter;
80       lastChoosenFilter[3]=txtFilter;
81       lastChoosenFilter[4]=allFilter;
82    }
83
84    private static JFileChooser chooser;
85
86    static {
87       String JavaDoc userDir=System.getProperty("user.dir");
88       chooser=new JFileChooser(userDir);
89    }
90
91    public static final int INFORMATION_MESSAGE = JOptionPane.INFORMATION_MESSAGE;
92    public static final int ERROR_MESSAGE = JOptionPane.ERROR_MESSAGE;
93
94    //************************* XMLFILTER CLASS ***********************************
95
/**
96     * Used to filter XML files during opening or saving.
97     */

98    private static final class XMLFilter extends javax.swing.filechooser.FileFilter JavaDoc {
99       private String JavaDoc myExtension=null;
100
101       XMLFilter (String JavaDoc extension) {
102          this.myExtension=extension;
103       }
104
105       public String JavaDoc getExtension () {
106          return myExtension;
107       }
108
109       public boolean accept (File f) {
110          if(f != null) {
111             if(f.isDirectory()) {
112                return true;
113             }
114             if (myExtension!=null) {
115                String JavaDoc extension = null;
116                String JavaDoc fName = f.getName();
117                int i = fName.lastIndexOf('.');
118                if(i>0 && i<fName.length()-1) {
119                   extension=fName.substring(i+1).toLowerCase();
120                }
121
122                if(extension != null && extension.equalsIgnoreCase(myExtension)) {
123                   return true;
124                }
125             } else {
126                return true;
127             }
128          }
129          return false;
130       }
131
132       public String JavaDoc getDescription () {
133          if (myExtension!=null) {
134             return XMLUtil.getLanguageDependentString(myExtension.toUpperCase()+"Description");
135          } else {
136             return XMLUtil.getLanguageDependentString("ALLDescription");
137          }
138       }
139    }
140    //********************** END OF XMLFILTER CLASS ******************************
141

142    public static void setApplicationWindow (Window w) {
143       myWindow=w;
144    }
145
146    public static void setDefaultResources (ResourceBundle defaultR) {
147       defaultResources=defaultR;
148    }
149
150    public static void setChoosenResources (ResourceBundle choosenR) {
151       choosenResources=choosenR;
152    }
153
154    public static void setProperties (Properties props) {
155       properties=props;
156    }
157
158    /* Show a dialog with the given error message. */
159    public static void message(String JavaDoc message,int type) {
160       JOptionPane.showMessageDialog(myWindow,message,
161                                     XMLUtil.getLanguageDependentString("Title"),type);
162    }
163
164    /* Open a dialog and return the filename. Returns null if canceled.
165     * @param parent The parent component of dialog.
166     * @param message The message to write in the title of dialog
167     * @param mode 0 - open dialog, 1 - save dialog
168     * @param filteringMode if 0 - displays .xml and .xpdl files, if 1 - displays
169     * .jpg files, 2 - displays SVG files, 3 - displays .xml and .xpdl files,
170     * otherwise displays all files
171     * @param initialName The initial name of the file to be saved or opened
172     * @return The filename of opened/saved file.
173     */

174    public static String JavaDoc dialog(Component parent,String JavaDoc message,
175                                int mode,int filteringMode,String JavaDoc initialName) {
176       chooser.updateUI();
177       chooser.setDialogTitle(message);
178       int setFilterIndex = 0;
179       switch (filteringMode) {
180          case 0:
181             chooser.setAcceptAllFileFilterUsed(false);
182             chooser.setFileFilter(allFilter);
183             chooser.setFileFilter(xmlFilter);
184             chooser.setFileFilter(xpdlFilter);
185             chooser.removeChoosableFileFilter(jpgFilter);
186             chooser.removeChoosableFileFilter(svgFilter);
187             chooser.removeChoosableFileFilter(txtFilter);
188             setFilterIndex = 0;
189             break;
190          case 1:
191             chooser.setAcceptAllFileFilterUsed(false);
192             chooser.setFileFilter(allFilter);
193             chooser.setFileFilter(jpgFilter);
194             chooser.removeChoosableFileFilter(xmlFilter);
195             chooser.removeChoosableFileFilter(xpdlFilter);
196             chooser.removeChoosableFileFilter(svgFilter);
197             chooser.removeChoosableFileFilter(txtFilter);
198             setFilterIndex = 1;
199             break;
200          case 2:
201             chooser.setAcceptAllFileFilterUsed(false);
202             chooser.setFileFilter(allFilter);
203             chooser.setFileFilter(svgFilter);
204             chooser.removeChoosableFileFilter(xmlFilter);
205             chooser.removeChoosableFileFilter(xpdlFilter);
206             chooser.removeChoosableFileFilter(jpgFilter);
207             chooser.removeChoosableFileFilter(txtFilter);
208             setFilterIndex = 2;
209             break;
210          case 3:
211             chooser.setAcceptAllFileFilterUsed(false);
212             chooser.setFileFilter(allFilter);
213             chooser.setFileFilter(txtFilter);
214             chooser.removeChoosableFileFilter(xmlFilter);
215             chooser.removeChoosableFileFilter(xpdlFilter);
216             chooser.removeChoosableFileFilter(jpgFilter);
217             chooser.removeChoosableFileFilter(svgFilter);
218             setFilterIndex = 3;
219             break;
220          default:
221             chooser.setAcceptAllFileFilterUsed(false);
222             chooser.setFileFilter(allFilter);
223             chooser.removeChoosableFileFilter(xmlFilter);
224             chooser.removeChoosableFileFilter(xpdlFilter);
225             chooser.removeChoosableFileFilter(jpgFilter);
226             chooser.removeChoosableFileFilter(svgFilter);
227             chooser.removeChoosableFileFilter(txtFilter);
228             setFilterIndex = 4;
229             break;
230       }
231       try {
232          chooser.setFileFilter(lastChoosenFilter[setFilterIndex]);
233       } catch (Exception JavaDoc ex) {}
234
235       if (initialName!=null && initialName.length()>0) {
236          chooser.setSelectedFile(new File(initialName));
237       }
238
239       int returnVal=-1;
240       String JavaDoc fileName=null;
241
242       while (true) {
243          if (mode==0) {
244             returnVal = chooser.showOpenDialog(parent);
245          }
246          else {
247             returnVal = chooser.showSaveDialog(parent);
248          }
249
250          if(returnVal == JFileChooser.APPROVE_OPTION) {
251             File f=chooser.getSelectedFile();
252             fileName=f.getAbsolutePath();
253             // SAVING:
254
// - if extension isn't specified, tries to save the file with default extension
255
// - it will not save file with extension if the file with extension already exists
256
String JavaDoc extension=((XMLUtil.XMLFilter)chooser.getFileFilter()).getExtension();
257             int dotIndex=f.getName().lastIndexOf(".");
258
259             String JavaDoc oldFilename=fileName;
260             if (mode==1) {
261                if ((filteringMode>=0 && filteringMode<=2) && extension!=null &&
262                    dotIndex==-1) {
263                   fileName+="."+extension;
264                }
265                // check if user have choosed an existing filename
266
if (new File(fileName).exists()) {
267                   int r=JOptionPane.showConfirmDialog(myWindow,
268                                                       XMLUtil.getLanguageDependentString("WarningFileAlreadyExistsDoYouWantToReplaceIt"),
269                                                       XMLUtil.getLanguageDependentString("Title"),JOptionPane.YES_NO_OPTION);
270                   if (r==JOptionPane.NO_OPTION) {
271                      fileName=oldFilename;
272                      continue;
273                   }
274                }
275
276                // OPENING:
277
// - if extension isn't specified, and given file doesn't exist, tries
278
// to open the .xml file with the same name
279
} else {
280                if (mode==0 && !f.exists()) {
281                   if ((filteringMode>=0 && filteringMode<=2) && dotIndex==-1) {
282                      fileName+="."+extension;
283                      if (!new File(fileName).exists()) {
284                         fileName=null;
285                      }
286                   } else {
287                      fileName=null;
288                   }
289                }
290                if (fileName==null) {
291                   XMLUtil.message(
292                      XMLUtil.getLanguageDependentString("WarningFileDoesNotExistPleaseSelectExistingFileToOpen"),
293                      JOptionPane.WARNING_MESSAGE);
294                   fileName=oldFilename;
295                   continue;
296                }
297             }
298          }
299          break;
300       }
301
302       try {
303          lastChoosenFilter[setFilterIndex]=chooser.getFileFilter();
304       } catch (Exception JavaDoc ex) {}
305
306       return fileName;
307    }
308
309    /**
310     * Gets a resource string from the resource bundle.<p> Resource bundle
311     * represents the <i>property file</i>. For example, if property file
312     * contains something like this:<BR><CENTER>menubar=file edit help</CENTER>
313     * method call getLanguageDependentString("menubar") will give the string
314     * <i>file edit help</i> as a result. <BR> This method reads information
315     * from property file. If can't find desired resource, returns <b>null</b>.
316     * @param nm name of the resource to fetch.
317     * @return String value of named resource.
318     */

319    public static String JavaDoc getLanguageDependentString(String JavaDoc nm) {
320       String JavaDoc str;
321       try {
322          str=choosenResources.getString(nm);
323       } catch (MissingResourceException mre) {
324          try {
325             str=defaultResources.getString(nm);
326          } catch (MissingResourceException mre1) {
327             str = null;
328          } catch (NullPointerException JavaDoc npe) {
329             str=null;
330          }
331       } catch (NullPointerException JavaDoc npe) {
332          /*ResourceBundle orig=ResourceBundle.
333           getBundle("org.enhydra.jawe.resources.JaWE",new Locale(""));*/

334          ResourceBundle orig=ResourceBundle.
335             getBundle("org.enhydra.jawe.resources.JaWE");
336          try {
337             str=orig.getString(nm);
338          } catch (Exception JavaDoc ex) {
339             str=null;
340          }
341       }
342       return str;
343    }
344
345    /**
346     * Gets the url from a resource string.
347     * @param key the string key to the url in the properties.
348     * @return the resource location.
349     * @see java.lang.Class#getResource
350     */

351    public static URL JavaDoc getResource(String JavaDoc key) {
352       try {
353          String JavaDoc name=properties.getProperty(key);
354          if (name != null) {
355             URL JavaDoc url = XMLUtil.class.getClassLoader().getResource(name);
356             return url;
357          }
358       } catch (Exception JavaDoc ex) {}
359       return null;
360    }
361
362    /**
363     * Take the given string and chop it up into a series
364     * of strings on given boundries. This is useful
365     * for trying to get an array of strings out of the
366     * resource file.
367     */

368    public static String JavaDoc[] tokenize(String JavaDoc input,String JavaDoc boundary) {
369       if (input==null) input="";
370       Vector v = new Vector();
371       StringTokenizer t = new StringTokenizer(input,boundary);
372       String JavaDoc cmd[];
373
374       while (t.hasMoreTokens())
375          v.addElement(t.nextToken());
376       cmd = new String JavaDoc[v.size()];
377       for (int i = 0; i < cmd.length; i++)
378          cmd[i] = (String JavaDoc)v.elementAt(i);
379
380       return cmd;
381    }
382
383    /**
384     * Determines the number of string toFind within string toSearch.
385     */

386    public static int howManyStringsWithinString (String JavaDoc toSearch,String JavaDoc toFind) {
387       try {
388          int startAt=0;
389          int howMany=0;
390
391          int fnd;
392          while ((fnd=toSearch.indexOf(toFind,startAt))!=-1) {
393             howMany++;
394             startAt=(fnd+toFind.length());
395          }
396          return howMany;
397       } catch (Exception JavaDoc ex) {
398          return -1;
399       }
400    }
401
402    /**
403     * Neat little thing. Makes HTML formated string for tooltip
404     * (made of property names and coresponding values).
405     */

406    public static String JavaDoc makeTooltip(XMLElement[] elements){
407       if (elements==null) return "";
408       String JavaDoc s = HTML_OPEN;
409       for (int i=0; i<elements.length; i++) {
410          s+=makeAnotherHtmlLine(elements[i]);
411       }
412       s=s.substring(0, s.length() - LINE_BREAK.length());
413       s+=HTML_CLOSE;
414       return s;
415    }
416
417    /** Helps when generating tooltip for some element. */
418    private static String JavaDoc makeAnotherHtmlLine(XMLElement el) {
419       int MAX_LENGTH=100;
420       int MAX_LINES_PER_TEXT=15;
421       String JavaDoc textToAppend="";
422       textToAppend += STRONG_OPEN;
423       textToAppend += el.toLabel()+COLON_SPACE;
424       textToAppend += STRONG_CLOSE;
425       String JavaDoc val=el.toString();
426       val=val.replaceAll("<","&lt;");
427       val=val.replaceAll(">","&gt;");
428       int vl=val.length();
429       if (vl>MAX_LENGTH) {
430          String JavaDoc newVal="";
431          int hm=vl/MAX_LENGTH;
432          for (int i=0; i<=hm; i++) {
433             int startI=i*MAX_LENGTH;
434             int endI=(i+1)*MAX_LENGTH;
435             if (endI>vl) {
436                endI=vl;
437             }
438             newVal=newVal+val.substring(startI,endI);
439             if (i==MAX_LINES_PER_TEXT) {
440                newVal=newVal+" ...";
441                break;
442             }
443             if (i<hm) {
444                newVal+=LINE_BREAK;
445                newVal+=XMLUtil.makeEmptyHTMLText((el.toLabel()+COLON_SPACE).length());
446             }
447          }
448          val=newVal;
449       }
450       textToAppend += val;
451       textToAppend += LINE_BREAK;
452
453       return textToAppend;
454    }
455
456    public static String JavaDoc getCanonicalPath (String JavaDoc path, boolean canBeDirectory) {
457       File f=new File(path);
458       if (!f.isAbsolute()) {
459          f=new File(System.getProperty("user.dir")+File.separator+path);
460       }
461       if (!f.exists() || (f.isDirectory() && !canBeDirectory)) {
462          System.err.println("The file "+f.getAbsolutePath()+" does not exist");
463          return null;
464       } else {
465          return getCanonicalPath(f);
466       }
467    }
468
469    private static String JavaDoc getCanonicalPath (File f) {
470       try {
471          return f.getCanonicalPath();
472       } catch (Exception JavaDoc ex) {
473          return f.getAbsolutePath();
474       }
475    }
476
477    /**
478     * Used to parse all elements from the given collection according to the
479     * given tagContent. The method is iterating through elements and
480     * searching it's name within tagContent. If the name is found, the
481     * method calls fromXML method of element.
482     * NOTE: The tagContent has to be already parsed to contain only element's
483     * part of XML tag without attributes.
484     */

485    public static void parseElements (Node node,Collection complexStructure) {
486       String JavaDoc nameSpacePrefix=node.getPrefix();
487       if (nameSpacePrefix!=null) {
488          nameSpacePrefix+=":";
489       } else {
490          nameSpacePrefix="";
491       }
492       // getting elements
493
Iterator it=complexStructure.iterator();
494       while (it.hasNext()) {
495          XMLElement el=(XMLElement)it.next();
496          if (!(el instanceof XMLAttribute) && !(el instanceof XMLComplexChoice)
497              && node!=null) {
498             //System.out.println("Elem="+el.name);
499
// external parser
500
Node child = getChildByName(node,nameSpacePrefix+el.name);
501             if (child!=null) {
502                el.fromXML(child);
503             }
504          }
505          else {
506             if (el instanceof XMLComplexChoice) {
507                Object JavaDoc[] ch=((XMLComplexChoice)el).getChoices();
508                if (ch != null && node!=null) {
509                   for (int i=0; i<ch.length; i++) {
510                      XMLElement chc=(XMLElement)ch[i];
511                      // external parser
512
Node child = getChildByName(node,nameSpacePrefix+chc.name);
513                      if (child!=null) {
514                         ((XMLComplexChoice)el).fromXML(chc.name,child);
515                      }
516                   }
517                }
518             }
519          }
520       }
521    }
522
523    public static Node getChildByName(Node parent,String JavaDoc childName) {
524       NodeList children = parent.getChildNodes();
525       for (int i = 0; i < children.getLength(); ++i) {
526          Node child = (Node) children.item(i);
527          if (child.getNodeName().equals(childName)) {
528             return child;
529          }
530       }
531       return null;
532    }
533
534    public static String JavaDoc getID (Node node) {
535       try {
536          NamedNodeMap nnm=node.getAttributes();
537          Node attrib=nnm.getNamedItem("Id");
538          Object JavaDoc ID;
539          if (attrib.hasChildNodes()) {
540             ID=attrib.getChildNodes().item(0).getNodeValue();
541          } else {
542             ID=attrib.getNodeValue();
543          }
544          return ID.toString();
545       } catch (Exception JavaDoc ex) {
546          return "";
547       }
548    }
549
550    public static String JavaDoc getContent (Node node,boolean omitXMLDeclaration) {
551       try {
552          ByteArrayOutputStream baos=new ByteArrayOutputStream();
553
554          // Use a Transformer for output
555
TransformerFactory tFactory =
556             TransformerFactory.newInstance();
557          Transformer transformer = tFactory.newTransformer();
558          transformer.setOutputProperty("indent","yes");
559          transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4");
560          transformer.setOutputProperty("encoding","UTF-8");
561          if (omitXMLDeclaration) {
562             transformer.setOutputProperty("omit-xml-declaration","yes");
563          }
564
565          DOMSource source = new DOMSource(node);
566          StreamResult result = new StreamResult(baos);
567          transformer.transform(source,result);
568
569          String JavaDoc cont=baos.toString("UTF8");
570
571          baos.close();
572          return cont;
573       } catch (Exception JavaDoc ex) {
574          return "";
575       }
576    }
577
578    public static String JavaDoc getChildNodesContent (Node node) {
579       String JavaDoc txt="";
580       if (node!=null) {
581          if (node.hasChildNodes()) {
582             txt=XMLUtil.getContent(node,true);
583             try {
584                Node fc=node.getFirstChild();
585                String JavaDoc fcnc=XMLUtil.getContent(fc,true);
586                String JavaDoc closedTag="</"+node.getNodeName()+">";
587                if (fcnc.trim().length()>0) {
588                   fcnc=fcnc.trim();
589                }
590
591                int i1,i2;
592                i1=txt.indexOf(fcnc);
593                i2=txt.lastIndexOf(closedTag);
594                txt=txt.substring(i1,i2).trim();
595             } catch (Exception JavaDoc ex) {
596                NodeList nl=node.getChildNodes();
597                txt="";
598                try {
599                   for (int i=0; i<nl.getLength(); i++) {
600                      Node sn=nl.item(i);
601                      if (sn instanceof Element) {
602                         txt+=XMLUtil.getContent(sn,true);
603                      } else {
604                         String JavaDoc nv=sn.getNodeValue();
605                         // trim only the begining of the string
606
if (i>0) {
607                            txt+=nv.substring(1);
608                         } else if (i==0 && nv.trim().length()==0) {
609                            continue;
610                         } else {
611                            txt+=nv;
612                         }
613                      }
614                   }
615                } catch (Exception JavaDoc ex2){}
616             }
617          }
618       }
619       return txt;
620    }
621
622    /**
623     * Returns if given activity has AND type split or join.
624     * @param act The activity that is checked if it has AND type
625     * split or join, depending on the second parameter.
626     * @param sOrJ if 0, activity is checked for AND type split, otherwise it is
627     * checked for AND type join
628     * @return true if activity has AND type of split or join
629     */

630    public static boolean isANDTypeSplitOrJoin (Activity act,int sOrJ) {
631       String JavaDoc splitOrJoin="Split";
632       if (sOrJ!=0) {
633          splitOrJoin="Join";
634       }
635       String JavaDoc sjType = "XOR"; // default type is XOR
636
// loop through the transitions restrictions specified for the
637
// activity to find the type of the activity split/join
638
Collection transitionRestrictions =
639          ((TransitionRestrictions)act.get("TransitionRestrictions")).toCollection();
640       Iterator iter = transitionRestrictions.iterator();
641       while(iter.hasNext()){
642          TransitionRestriction restriction=(TransitionRestriction)iter.next();
643          XMLComplexElement sj=(XMLComplexElement)restriction.get(splitOrJoin);
644          if(sj==null){
645             // continue until we find it
646
continue;
647          }
648          sjType = sj.get("Type").toValue().toString();
649       }
650
651       if (sjType.equals("AND")) {
652          return true;
653       } else {
654          return false;
655       }
656    }
657
658    /**
659     * Returns the set of (XML) activities that have split or join.
660     * @param acts The activities graph objects that are checked if their
661     * XML object have split or join, depending on the second parameter.
662     * @param sOrJ if 0, activity is checked for split, otherwise it is
663     * checked for join
664     */

665    public static Set getSplitOrJoinActivities (Collection acts,int sOrJ) {
666       Set sOrJactivities=new HashSet();
667       if (acts==null) return sOrJactivities;
668       Transitions ts=null;
669       Iterator it=acts.iterator();
670       while (it.hasNext()) {
671          Activity act=(Activity)it.next();
672          if (ts==null) {
673             ts=(Transitions)act.getCollection().getOwner().get("Transitions");
674          }
675          Iterator iter;
676          if (sOrJ==0) {
677             iter=ts.getTransitions(act.getID(),-1).iterator();
678          } else {
679             iter=ts.getTransitions(act.getID(),1).iterator();
680          }
681          int noOfTrans=0;
682          while (iter.hasNext()) {
683             Transition t = (Transition)iter.next();
684             if (t!=null && t.getFrom()!=null && t.getTo()!=null) {
685                noOfTrans++;
686             }
687          }
688          if (noOfTrans>1) {
689             sOrJactivities.add(act);
690          }
691       }
692
693       return sOrJactivities;
694    }
695
696    /**
697     * Returns the set of BlockActivity objects contained within given
698     * process or block activity. If the BlockActivity objects contains
699     * other BlockActivity objects, and the second parameter is set to true,
700     * these are also returned, and so on - which means that
701     * implementation is recursive.
702     */

703    public static Set getBlockActivities(XMLComplexElement wpOrAs,boolean recursivly) {
704       Collection allActs=((Activities)wpOrAs.get("Activities")).toCollection();
705       Set bas=new HashSet();
706       Iterator it=allActs.iterator();
707       Activity act;
708       while (it.hasNext()) {
709          act=(Activity)it.next();
710          BlockActivity ba=act.getBlockActivity();
711          if (ba!=null) {
712             bas.add(act);
713             if (!recursivly) continue;
714             ActivitySets ass=(ActivitySets)act.getOwnerProcess().get("ActivitySets");
715             String JavaDoc asId=ba.get("BlockId").toString();
716             ActivitySet as=ass.getActivitySet(asId);
717             if (as!=null) {
718                bas.addAll(getBlockActivities(as,true));
719             }
720          }
721       }
722       return bas;
723    }
724
725
726    /**
727     * Returns predefined conformanceClass number.
728     * @param conformanceClass The conformance class we are looking for number
729     * @return 0 if conformance class is NON_BLOCKED, 1 if conformance class is
730     * LOOP_BLOCKED, 2 if conformance class is FULL_BLOCKED, and -1 otherwise
731     */

732    public static int getConformanceClassNo (String JavaDoc conformanceClass) {
733       if (conformanceClass.equals("NON_BLOCKED")) {
734          return 0;
735       } else if (conformanceClass.equals("LOOP_BLOCKED")) {
736          return 1;
737       } else if (conformanceClass.equals("FULL_BLOCKED")) {
738          return 2;
739       } else {
740          return -1;
741       }
742    }
743
744    /**
745     * Converts a file specified by the path, to the String.
746     */

747    public static String JavaDoc fileToString (String JavaDoc fileName) {
748       if (fileName != null) {
749          //String sLine;
750
byte[] utf8Bytes;
751          String JavaDoc sFile = new String JavaDoc();
752          // Reading input by lines:
753
try {
754             FileInputStream fis=new FileInputStream(fileName);
755             int noOfBytes=fis.available();
756             if (noOfBytes>0) {
757                utf8Bytes=new byte[noOfBytes];
758                fis.read(utf8Bytes);
759                sFile=new String JavaDoc(utf8Bytes,"UTF8");
760             }
761          }
762          catch (Exception JavaDoc ex) {
763             return null;
764          }
765          return sFile;
766       }
767       return null;
768    }
769    //******** END OF CREATING SCROLLPANE AND EDITOR COMPONENT(PEJGRAPH) **********
770

771    /** Gets the current date and time string in ISO-8601 format. */
772    public static String JavaDoc getCurrentDateAndTime () {
773       String JavaDoc dateSeparator="-";
774       String JavaDoc timeSeparator=":";
775       Calendar cal=new GregorianCalendar();
776       String JavaDoc dateTime="";
777       dateTime=dateTime+String.valueOf(cal.get(Calendar.YEAR))+dateSeparator;
778       int mnth=cal.get(Calendar.MONTH)+1;
779       if (mnth<10) {
780          dateTime=dateTime+"0";
781       }
782       dateTime=dateTime+String.valueOf(mnth)+dateSeparator;
783       int dayOfMnth=cal.get(Calendar.DAY_OF_MONTH);
784       if (dayOfMnth<10) {
785          dateTime=dateTime+"0";
786       }
787       dateTime=dateTime+String.valueOf(dayOfMnth)+" ";
788       int hr=cal.get(Calendar.HOUR_OF_DAY);
789       int ampm=cal.get(Calendar.AM_PM);
790       if (ampm==Calendar.PM && hr<12) {
791          hr+=12;
792       }
793       if (hr<10) {
794          dateTime=dateTime+"0";
795       }
796       dateTime=dateTime+String.valueOf(hr)+timeSeparator;
797       int min=cal.get(Calendar.MINUTE);
798       if (min<10) {
799          dateTime=dateTime+"0";
800       }
801       dateTime=dateTime+String.valueOf(min)+timeSeparator;
802       int sec=cal.get(Calendar.SECOND);
803       if (sec<10) {
804          dateTime=dateTime+"0";
805       }
806       dateTime=dateTime+String.valueOf(sec);
807
808       return dateTime;
809    }
810
811    /**
812     * Checks if formal and actual parameters are matched by number and by type.
813     * @return 0 - if parameters are matched, 1 - if numbere of formal and
814     * actual parameters is not the same, 2 - if types of parameters are not
815     * matched
816     */

817    public static int checkParameterMatching (FormalParameters fps,ActualParameters aps) {
818       if (fps==null || aps==null || fps.size()!=aps.size()) {
819          return 1;
820       }
821
822       for (int i=0; i<fps.size(); i++) {
823          FormalParameter fp=(FormalParameter)fps.get(i);
824          ActualParameter ap=(ActualParameter)aps.get(i);
825
826          String JavaDoc fpMode=fp.get("Mode").toValue().toString();
827
828          // if the formal parameter mode is IN, do not check validity because
829
// that could be expression written in any scripting language
830
if (fpMode.equals("IN")) continue;
831
832          // find the type of formal param.
833
DataType fpdt=(DataType)fp.get("DataType");
834          XMLComplexChoice fpdtt=(XMLComplexChoice)fpdt.get("Type");
835          XMLElement fpType=(XMLElement)fpdtt.getChoosen();
836
837          // find the type of actual param.
838
Object JavaDoc apWRD=ap.toValue();
839          XMLElement apType=null;
840          if ((apWRD instanceof DataField) || (apWRD instanceof FormalParameter)) {
841             DataType apdt=(DataType)((XMLCollectionElement)apWRD).get("DataType");
842             XMLComplexChoice apdtt=(XMLComplexChoice)apdt.get("Type");
843             apType=(XMLElement)apdtt.getChoosen();
844          }
845
846          // if the actual parameter is an expression, and the mode is not
847
// IN, return 2, which signals that parameter types don't match
848
if (apType==null) {
849             return 2;
850          }
851
852          if (fpType.getClass().equals(apType.getClass())) {
853             // if this is BasicType check for subtype matching
854
if (fpType instanceof BasicType) {
855                XMLAttribute fpAT=(XMLAttribute)((BasicType)fpType).get("Type");
856                XMLAttribute apAT=(XMLAttribute)((BasicType)apType).get("Type");
857                if (!fpAT.toValue().toString().equals(apAT.toValue().toString())) {
858                   return 2;
859                }
860             }
861             // if this is EnumerationType check for Enumeration values matching
862
if (fpType instanceof EnumerationType) {
863                // first check the size of enums
864
if (((EnumerationType)fpType).size()!=((EnumerationType)apType).size()) {
865                   return 2;
866                }
867                // check the enum elements values
868
for (int j=0; j<((EnumerationType)fpType).size(); j++) {
869                   if (!((EnumerationType)fpType).get(j).toString().
870                       equals(((EnumerationType)apType).get(j).toString())) {
871                      return 2;
872                   }
873                }
874             }
875             // if this is DeclaredType check if their IDs are the same
876
if (fpType instanceof DeclaredType) {
877                if (!((DeclaredType)fpType).get("Id").toString().
878                    equals(((DeclaredType)apType).get("Id").toString())) {
879                   return 2;
880                }
881             }
882
883          } else {
884             return 2;
885          }
886       }
887       return 0;
888    }
889
890    public static String JavaDoc replaceBackslashesWithSlashes (String JavaDoc repBS) {
891       if (repBS!=null) {
892          int ind=-1;
893          while ((ind=repBS.indexOf("\\"))!=-1) {
894             repBS=repBS.substring(0,ind)+"/"+repBS.substring(ind+1);
895          }
896       }
897       return repBS;
898    }
899
900    /**
901     * If expand is true, expands all nodes in the tree.
902     * Otherwise, collapses all nodes in the tree.
903     * @param tree jtree to expand or collapse
904     * @param expand if true expand, otherwise collapses
905     */

906    public static void expandAll(JTree tree, boolean expand) {
907       TreeNode root = (TreeNode)tree.getModel().getRoot();
908
909       // Traverse tree from root
910
expandAll(tree, new TreePath(root), expand);
911    }
912
913    /**
914     * Collapse or expand specified three path.
915     * @param tree jtree to expand or collapse
916     * @param parent path to collapse or expand
917     * @param expand if true expand, otherwise collapses
918     */

919    public static void expandAll(JTree tree, TreePath parent, boolean expand) {
920       try {
921          // Traverse children
922
TreeNode node = ( TreeNode ) parent.getLastPathComponent();
923          if ( node.getChildCount() >= 0 ) {
924             for ( Enumeration e = node.children(); e.hasMoreElements(); ) {
925                TreeNode n = ( TreeNode ) e.nextElement();
926                TreePath path = parent.pathByAddingChild( n );
927                expandAll( tree, path, expand );
928             }
929          }
930          // Expansion or collapse must be done bottom-up
931
if ( expand ) {
932             tree.expandPath( parent );
933          }
934          else {
935             tree.collapsePath( parent );
936          }
937       }catch(Exception JavaDoc e) {
938          //do nothing, because if somebody click somewhere where node do not exist
939
}
940    }
941
942    /**
943     * Collapse or expand specified three path, depends of state of flag isCollapsed
944     * in user object.
945     * @param tree jtree to expand or collapse
946     * @param parent path to collapse or expand
947     */

948    public static void initExpand(JTree tree, TreePath parent) {
949       try {
950          // Traverse children
951
TreeNode node = ( TreeNode ) parent.getLastPathComponent();
952          ArrayList expandedChilds = new ArrayList();
953          if ( node.getChildCount() >= 0 ) {
954             for ( Enumeration e = node.children(); e.hasMoreElements(); ) {
955                TreeNode n = ( TreeNode ) e.nextElement();
956                if( !((XMLElement)((DefaultMutableTreeNode)n).getUserObject()).isCollapsed())
957                   expandedChilds.add(n);
958             }
959             for(int i = 0; i < expandedChilds.size(); i++ ) {
960                TreePath path = parent.pathByAddingChild( (TreeNode)expandedChilds.get(i) );
961                initExpand( tree, path );
962             }
963
964          }
965          tree.expandPath( parent );
966       }catch(Exception JavaDoc e) {
967          //do nothing
968
}
969    }
970
971    public static Set getStartingActivities (XMLCollectionElement procOrASDef) {
972       Activities acts=((Activities)procOrASDef.get("Activities"));
973       Set starts=new HashSet();
974       Iterator it=acts.toCollection().iterator();
975       Transitions ts=(Transitions)procOrASDef.get("Transitions");
976       while (it.hasNext()) {
977          Activity act=(Activity)it.next();
978          Set trs=act.getIncomingTransitions();
979          // the activity is starting one if it has no input transitions ...
980
if (trs.size()==0) {
981             starts.add(act);
982             // or there is a one input transition, but it is a selfreference
983
} else if (trs.size()==1) {
984             Transition t=(Transition)trs.toArray()[0];
985             if (t.getFrom()!=null && t.getFrom().equals(t.getTo())) {
986                starts.add(act);
987             }
988          }
989       }
990       return starts;
991    }
992
993    public static Set getEndingActivities (XMLCollectionElement procOrASDef) {
994       Activities acts=((Activities)procOrASDef.get("Activities"));
995       Set ends=new HashSet();
996       Iterator it=acts.toCollection().iterator();
997       Transitions ts=(Transitions)procOrASDef.get("Transitions");
998       while (it.hasNext()) {
999          Activity act=(Activity)it.next();
1000         Set trs=act.getNonExceptionalOutgoingTransitions();
1001         // the activity is ending one if it has no output transitions ...
1002
if (trs.size()==0) {
1003            ends.add(act);
1004            // or there is a one output transition, but it is a selfreference
1005
} else if (trs.size()==1) {
1006            Transition t=(Transition)trs.toArray()[0];
1007            if (t.getFrom()!=null && t.getFrom().equals(t.getTo())) {
1008               ends.add(act);
1009            }
1010         }
1011      }
1012
1013      return ends;
1014   }
1015
1016   public static Set getAllExtendedAttributeNames (XMLComplexElement cel) {
1017      Set extAttribNames=new HashSet();
1018      XMLInterface xmlInterface=null;
1019
1020      if (cel instanceof Activity) {
1021         xmlInterface=((Activity)cel).getOwnerProcess().getPackage().getXMLInterface();
1022      } else if (cel instanceof Application) {
1023         xmlInterface=((Application)cel).getPackage().getXMLInterface();
1024      } else if (cel instanceof DataField) {
1025         xmlInterface=((DataField)cel).getPackage().getXMLInterface();
1026      } else if (cel instanceof ExternalPackage) {
1027         xmlInterface=((ExternalPackage)cel).getMyPackage().getXMLInterface();
1028      } else if (cel instanceof Package JavaDoc) {
1029         xmlInterface=((Package JavaDoc)cel).getXMLInterface();
1030      } else if (cel instanceof Participant) {
1031         xmlInterface=((Participant)cel).getPackage().getXMLInterface();
1032      } else if (cel instanceof Tool) {
1033         xmlInterface=((Tool)cel).getPackage().getXMLInterface();
1034      } else if (cel instanceof Transition) {
1035         xmlInterface=((Transition)cel).getPackage().getXMLInterface();
1036      } else if (cel instanceof TypeDeclaration) {
1037         xmlInterface=((TypeDeclaration)cel).getPackage().getXMLInterface();
1038      } else if (cel instanceof WorkflowProcess) {
1039         xmlInterface=((WorkflowProcess)cel).getPackage().getXMLInterface();
1040      }
1041
1042      if (xmlInterface!=null) {
1043         Iterator it=xmlInterface.getAllPackages().iterator();
1044         while (it.hasNext()) {
1045            extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames((Package JavaDoc)it.next(),cel));
1046         }
1047      }
1048      return extAttribNames;
1049   }
1050
1051   private static Set getAllExtendedAttributeNames (Package JavaDoc pkg,XMLComplexElement cel) {
1052      Set extAttribNames=new HashSet();
1053      if (cel instanceof Activity) {
1054         Iterator it=((WorkflowProcesses)pkg.get("WorkflowProcesses")).toCollection().iterator();
1055         while (it.hasNext()) {
1056            WorkflowProcess wp=(WorkflowProcess)it.next();
1057            Activities acts=(Activities)wp.get("Activities");
1058            Iterator acti=acts.toCollection().iterator();
1059            while (acti.hasNext()) {
1060               Activity act=(Activity)acti.next();
1061               Collection extAttribs=((ExtendedAttributes)act.get("ExtendedAttributes")).toCollection();
1062               extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1063            }
1064            Iterator asets=((ActivitySets)wp.get("ActivitySets")).toCollection().iterator();
1065            while (asets.hasNext()) {
1066               ActivitySet as=(ActivitySet)asets.next();
1067               acts=(Activities)as.get("Activities");
1068               acti=acts.toCollection().iterator();
1069               while (acti.hasNext()) {
1070                  Activity act=(Activity)acti.next();
1071                  Collection extAttribs=((ExtendedAttributes)act.get("ExtendedAttributes")).toCollection();
1072                  extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1073               }
1074            }
1075         }
1076      } else if (cel instanceof Application) {
1077         Applications aps=(Applications)pkg.get("Applications");
1078         Iterator api=aps.toCollection().iterator();
1079         while (api.hasNext()) {
1080            Application ap=(Application)api.next();
1081            Collection extAttribs=((ExtendedAttributes)ap.get("ExtendedAttributes")).toCollection();
1082            extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1083         }
1084         Iterator it=((WorkflowProcesses)pkg.get("WorkflowProcesses")).toCollection().iterator();
1085         while (it.hasNext()) {
1086            WorkflowProcess wp=(WorkflowProcess)it.next();
1087            aps=(Applications)wp.get("Applications");
1088            api=aps.toCollection().iterator();
1089            while (api.hasNext()) {
1090               Application ap=(Application)api.next();
1091               Collection extAttribs=((ExtendedAttributes)ap.get("ExtendedAttributes")).toCollection();
1092               extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1093            }
1094         }
1095      } else if (cel instanceof DataField) {
1096         DataFields dfs=(DataFields)pkg.get("DataFields");
1097         Iterator dfi=dfs.toCollection().iterator();
1098         while (dfi.hasNext()) {
1099            DataField df=(DataField)dfi.next();
1100            Collection extAttribs=((ExtendedAttributes)df.get("ExtendedAttributes")).toCollection();
1101            extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1102         }
1103         Iterator it=((WorkflowProcesses)pkg.get("WorkflowProcesses")).toCollection().iterator();
1104         while (it.hasNext()) {
1105            WorkflowProcess wp=(WorkflowProcess)it.next();
1106            dfs=(DataFields)wp.get("DataFields");
1107            dfi=dfs.toCollection().iterator();
1108            while (dfi.hasNext()) {
1109               DataField df=(DataField)dfi.next();
1110               Collection extAttribs=((ExtendedAttributes)df.get("ExtendedAttributes")).toCollection();
1111               extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1112            }
1113         }
1114      } else if (cel instanceof ExternalPackage) {
1115         ExternalPackages eps=(ExternalPackages)pkg.get("ExternalPackages");
1116         Iterator it=eps.toCollection().iterator();
1117         while (it.hasNext()) {
1118            ExternalPackage ep=(ExternalPackage)it.next();
1119            Collection extAttribs=((ExtendedAttributes)ep.get("ExtendedAttributes")).toCollection();
1120            extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1121         }
1122      } else if (cel instanceof Package JavaDoc) {
1123         Collection extAttribs=((ExtendedAttributes)pkg.get("ExtendedAttributes")).toCollection();
1124         extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1125      } else if (cel instanceof Participant) {
1126         Participants ps=(Participants)pkg.get("Participants");
1127         Iterator psi=ps.toCollection().iterator();
1128         while (psi.hasNext()) {
1129            Participant p=(Participant)psi.next();
1130            Collection extAttribs=((ExtendedAttributes)p.get("ExtendedAttributes")).toCollection();
1131            extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1132         }
1133         Iterator it=((WorkflowProcesses)pkg.get("WorkflowProcesses")).toCollection().iterator();
1134         while (it.hasNext()) {
1135            WorkflowProcess wp=(WorkflowProcess)it.next();
1136            ps=(Participants)wp.get("Participants");
1137            psi=ps.toCollection().iterator();
1138            while (psi.hasNext()) {
1139               Participant p=(Participant)psi.next();
1140               Collection extAttribs=((ExtendedAttributes)p.get("ExtendedAttributes")).toCollection();
1141               extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1142            }
1143         }
1144      } else if (cel instanceof Tool) {
1145         Iterator it=((WorkflowProcesses)pkg.get("WorkflowProcesses")).toCollection().iterator();
1146         while (it.hasNext()) {
1147            WorkflowProcess wp=(WorkflowProcess)it.next();
1148            Activities acts=(Activities)wp.get("Activities");
1149            Iterator acti=acts.toCollection().iterator();
1150            while (acti.hasNext()) {
1151               Activity act=(Activity)acti.next();
1152               Tools ts=act.getTools();
1153               if (ts!=null) {
1154                  Iterator ti=ts.toCollection().iterator();
1155                  while (ti.hasNext()) {
1156                     Tool t=(Tool)ti.next();
1157                     Collection extAttribs=((ExtendedAttributes)t.get("ExtendedAttributes")).toCollection();
1158                     extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1159                  }
1160               }
1161            }
1162            Iterator asets=((ActivitySets)wp.get("ActivitySets")).toCollection().iterator();
1163            while (asets.hasNext()) {
1164               ActivitySet as=(ActivitySet)asets.next();
1165               acts=(Activities)as.get("Activities");
1166               acti=acts.toCollection().iterator();
1167               while (acti.hasNext()) {
1168                  Activity act=(Activity)acti.next();
1169                  Tools ts=act.getTools();
1170                  if (ts!=null) {
1171                     Iterator ti=ts.toCollection().iterator();
1172                     while (ti.hasNext()) {
1173                        Tool t=(Tool)ti.next();
1174                        Collection extAttribs=((ExtendedAttributes)t.get("ExtendedAttributes")).toCollection();
1175                        extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1176                     }
1177                  }
1178               }
1179            }
1180         }
1181      } else if (cel instanceof Transition) {
1182         Iterator it=((WorkflowProcesses)pkg.get("WorkflowProcesses")).toCollection().iterator();
1183         while (it.hasNext()) {
1184            WorkflowProcess wp=(WorkflowProcess)it.next();
1185            Transitions ts=(Transitions)wp.get("Transitions");
1186            Iterator tsi=ts.toCollection().iterator();
1187            while (tsi.hasNext()) {
1188               Transition t=(Transition)tsi.next();
1189               Collection extAttribs=((ExtendedAttributes)t.get("ExtendedAttributes")).toCollection();
1190               extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1191            }
1192            Iterator asets=((ActivitySets)wp.get("ActivitySets")).toCollection().iterator();
1193            while (asets.hasNext()) {
1194               ActivitySet as=(ActivitySet)asets.next();
1195               ts=(Transitions)as.get("Transitions");
1196               tsi=ts.toCollection().iterator();
1197               while (tsi.hasNext()) {
1198                  Transition t=(Transition)tsi.next();
1199                  Collection extAttribs=((ExtendedAttributes)t.get("ExtendedAttributes")).toCollection();
1200                  extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1201               }
1202            }
1203         }
1204      } else if (cel instanceof TypeDeclaration) {
1205         Iterator tds=((TypeDeclarations)pkg.get("TypeDeclarations")).toCollection().iterator();
1206         while (tds.hasNext()) {
1207            TypeDeclaration td=(TypeDeclaration)tds.next();
1208            Collection extAttribs=((ExtendedAttributes)td.get("ExtendedAttributes")).toCollection();
1209            extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1210         }
1211      } else if (cel instanceof WorkflowProcess) {
1212         Iterator it=((WorkflowProcesses)pkg.get("WorkflowProcesses")).toCollection().iterator();
1213         while (it.hasNext()) {
1214            WorkflowProcess wp=(WorkflowProcess)it.next();
1215            Collection extAttribs=((ExtendedAttributes)wp.get("ExtendedAttributes")).toCollection();
1216            extAttribNames.addAll(XMLUtil.getAllExtendedAttributeNames(extAttribs));
1217         }
1218      }
1219      return extAttribNames;
1220   }
1221
1222   private static Set getAllExtendedAttributeNames (Collection extAttribs) {
1223      Set eaNames=new HashSet();
1224      Iterator it=extAttribs.iterator();
1225      while (it.hasNext()) {
1226         ExtendedAttribute ea=(ExtendedAttribute)it.next();
1227         eaNames.add(ea.get("Name").toString());
1228      }
1229      return eaNames;
1230   }
1231
1232   public static String JavaDoc makeEmptyHTMLText (int length) {
1233      if (length<0) return null;
1234      String JavaDoc es="";
1235      for (int i=0; i<length; i++) {
1236         es+="&nbsp;";
1237      }
1238      return es;
1239   }
1240
1241/* public static XMLElement makeCopyOfCollectionElement (XMLCollectionElement ce) {
1242      if (ce==null) return null;
1243
1244      Document document=null;
1245      try {
1246         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1247         DocumentBuilder dbuilder = dbf.newDocumentBuilder();
1248         document = dbuilder.newDocument();
1249      } catch (Exception ex) {}
1250
1251      Node node = document.createElement(ce.toName());
1252      ce.toXML(node);
1253      document.appendChild(node);
1254
1255      XMLCollectionElement copyOfEl=(XMLCollectionElement)ce.getCollection().generateNewElement();
1256      String ID=copyOfEl.getID();
1257
1258      NodeList nl=document.getElementsByTagName(ce.toName());
1259      Node wantedNode=null;
1260      if (nl.getLength()>0) {
1261         String extID=ce.getID();
1262         for (int i=0; i<nl.getLength(); i++) {
1263            Node n=nl.item(i);
1264            String IDOfNode=XMLUtil.getID(n);
1265            if (IDOfNode.equals(extID)) {
1266               wantedNode=n;
1267               break;
1268            }
1269         }
1270      } else {
1271         return null;
1272      }
1273
1274      if (wantedNode==null) return null;
1275      //String XML=wp.toXML(null,0).trim(); // trimming is neccessary for our parser
1276      copyOfEl.fromXML(wantedNode);
1277
1278      // Setting back newly generated ID
1279      copyOfEl.set("Id",ID);
1280      if (copyOfEl.get("Name")!=null) {
1281         copyOfEl.set("Name",
1282                      XMLUtil.getLanguageDependentString("CopyOfKey")+
1283                         " "+copyOfEl.get("Name").toString());
1284      }
1285
1286      return copyOfEl;
1287   }*/

1288}
1289
1290
Popular Tags