KickJava   Java API By Example, From Geeks To Geeks.

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


1 package org.enhydra.shark.xpdl;
2
3 import java.io.File JavaDoc;
4 import java.io.FileInputStream JavaDoc;
5 import java.io.StringReader JavaDoc;
6 import java.util.ArrayList JavaDoc;
7 import java.util.Collection JavaDoc;
8 import java.util.HashMap JavaDoc;
9 import java.util.HashSet JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.List JavaDoc;
12 import java.util.Map JavaDoc;
13 import java.util.Set JavaDoc;
14
15 import javax.xml.parsers.DocumentBuilder JavaDoc;
16 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
17
18 import org.apache.xerces.parsers.DOMParser;
19 import org.enhydra.shark.utilities.SequencedHashMap;
20 import org.enhydra.shark.xpdl.elements.ExternalPackage;
21 import org.enhydra.shark.xpdl.elements.Package;
22 import org.w3c.dom.Document JavaDoc;
23 import org.xml.sax.InputSource JavaDoc;
24
25 /**
26  * Implementation of XMLInterface that works with JDK1.3.
27  *
28  * @author Sasa Bojanic
29  */

30 public class XMLInterfaceForJDK13 implements XMLInterface {
31
32    protected Map JavaDoc idToPackages=new SequencedHashMap();
33    protected Map JavaDoc xmlFileToPackage=new SequencedHashMap();
34    protected Map JavaDoc packageToParentDirectory=new SequencedHashMap();
35
36    protected String JavaDoc mainPackageReference;
37
38    protected Map JavaDoc parsingErrorMessages=new SequencedHashMap();
39    protected boolean isValidationON=true;
40    public void setValidation (boolean isActive) {
41       isValidationON=isActive;
42    }
43
44    public void clearParserErrorMessages () {
45       parsingErrorMessages.clear();
46    }
47
48    public synchronized boolean isPackageOpened (String JavaDoc pkgId) {
49       return idToPackages.containsKey(pkgId);
50    }
51
52    public synchronized Package JavaDoc getPackageById (String JavaDoc pkgId) {
53       ArrayList JavaDoc l=(ArrayList JavaDoc)idToPackages.get(pkgId);
54       Package JavaDoc toRet=null;
55       if (l!=null) {
56          Iterator JavaDoc it=l.iterator();
57          String JavaDoc lastVersion="-1";
58          while (it.hasNext()) {
59             Package JavaDoc p=(Package JavaDoc)it.next();
60             String JavaDoc v=p.getInternalVersion();
61             if (v.compareTo(lastVersion)>=0) {
62                lastVersion=v;
63                toRet=p;
64             }
65          }
66       }
67       return toRet;
68    }
69
70    public synchronized Package JavaDoc getPackageByIdAndVersion (String JavaDoc pkgId,String JavaDoc version) {
71       ArrayList JavaDoc l=(ArrayList JavaDoc)idToPackages.get(pkgId);
72       Package JavaDoc toRet=null;
73       if (l!=null) {
74          Iterator JavaDoc it=l.iterator();
75          while (it.hasNext()) {
76             Package JavaDoc p=(Package JavaDoc)it.next();
77             String JavaDoc v=p.getInternalVersion();
78             if (v.equals(version)) {
79                toRet=p;
80                break;
81             }
82          }
83       }
84       return toRet;
85    }
86
87    public synchronized Package JavaDoc getPackageByFilename (String JavaDoc filename) {
88       filename=XMLUtil.getCanonicalPath(filename,"",false);
89       return (Package JavaDoc)xmlFileToPackage.get(filename);
90    }
91
92    public synchronized Package JavaDoc getExternalPackageByRelativeFilePath (
93       String JavaDoc relativePathToExtPkg,Package JavaDoc rootPkg) {
94
95       File JavaDoc f=new File JavaDoc(relativePathToExtPkg);
96       if (!f.isAbsolute()) {
97          f=new File JavaDoc(getParentDirectory(rootPkg)+File.separator+relativePathToExtPkg);
98       }
99       if (f.exists()) {
100          //System.out.println("Pkg for "+relativePathToExtPkg+"->"+f.getAbsolutePath()+" is found");
101
return getPackageByFilename(f.getAbsolutePath());
102       } else {
103          //System.out.println("Pkg for "+relativePathToExtPkg+"->"+f.getAbsolutePath()+" is not found");
104
return null;
105       }
106    }
107
108    public synchronized String JavaDoc getAbsoluteFilePath (Package JavaDoc pkg) {
109       Iterator JavaDoc it=xmlFileToPackage.entrySet().iterator();
110       String JavaDoc fullPath=null;
111       while (it.hasNext()) {
112          Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
113          String JavaDoc u=(String JavaDoc)me.getKey();
114          Package JavaDoc p=(Package JavaDoc)me.getValue();
115          if (p.equals(pkg)) {
116             fullPath=u;
117             break;
118          }
119       }
120       return fullPath;
121    }
122
123    public synchronized Collection JavaDoc getAllPackages () {
124       ArrayList JavaDoc l=new ArrayList JavaDoc();
125       Iterator JavaDoc it=idToPackages.values().iterator();
126       while (it.hasNext()) {
127          l.addAll((ArrayList JavaDoc)it.next());
128       }
129       return l;
130    }
131
132    public synchronized Collection JavaDoc getAllPackageIds () {
133       return idToPackages.keySet();
134    }
135
136    public Collection JavaDoc getAllPackageVersions (String JavaDoc pkgId) {
137       ArrayList JavaDoc l=new ArrayList JavaDoc();
138       ArrayList JavaDoc all=(ArrayList JavaDoc)idToPackages.get(pkgId);
139       if (all!=null) {
140          Iterator JavaDoc it=all.iterator();
141          while (it.hasNext()) {
142             l.add(((Package JavaDoc)it.next()).getInternalVersion());
143          }
144       }
145       return l;
146    }
147
148    public synchronized Collection JavaDoc getAllPackageFilenames () {
149       return xmlFileToPackage.keySet();
150    }
151
152    public synchronized boolean doesPackageFileExists (String JavaDoc xmlFile) {
153       if (new File JavaDoc(xmlFile).exists()) {// || getPackageFileContent(xmlFile)!=null) {
154
return true;
155       } else {
156          return false;
157       }
158    }
159
160    public synchronized String JavaDoc getParentDirectory (Package JavaDoc pkg) {
161       return (String JavaDoc)packageToParentDirectory.get(pkg);
162    }
163
164    public Package JavaDoc openPackage (String JavaDoc pkgReference,
165                                boolean handleExternalPackages) {
166       //long t1,t2;
167
//t1=System.currentTimeMillis();
168
parsingErrorMessages.clear();
169       mainPackageReference=pkgReference;
170
171       // this method opens the package. It also opens all of it's external packages
172
// if handleExternalPackages is set to true
173
Package JavaDoc pkg=openPackageRecursively(pkgReference,handleExternalPackages);
174
175       //printDebug();
176
//t2=System.currentTimeMillis();
177
//System.out.println("OPT="+(t2-t1));
178
return pkg;
179    }
180
181    public void printDebug () {
182       System.out.println("idToPackage="+idToPackages);
183       System.out.println("xmlFileToPackage="+xmlFileToPackage);
184       System.out.println("packageToWorkingDirectory="+packageToParentDirectory);
185       //Package.printDebug();
186
}
187
188    // Recursive implementation
189
// pkgReference MUST be absolute path
190
protected Package JavaDoc openPackageRecursively (String JavaDoc pkgReference,
191                                    boolean handleExternalPackages) {
192
193       Package JavaDoc pkg=null;
194       File JavaDoc f=null;
195       String JavaDoc oldP=pkgReference;
196
197       String JavaDoc baseDirectory=null;
198       pkgReference=XMLUtil.getCanonicalPath(pkgReference,"",false);
199       if (pkgReference==null) {
200          Set JavaDoc fem=new HashSet JavaDoc();
201          fem.add("File does not exist");
202          parsingErrorMessages.put(oldP,fem);
203          return null;
204       } else {
205          f=new File JavaDoc(pkgReference);
206          try {
207             baseDirectory=f.getParentFile().getCanonicalPath();
208          } catch (Exception JavaDoc ex) {
209             baseDirectory=f.getParentFile().getAbsolutePath();
210          }
211          }
212
213       if (xmlFileToPackage.containsKey(pkgReference)) {
214          return getPackageByFilename(pkgReference);
215       }
216
217       pkg=parseDocument(pkgReference,true);
218
219       if (pkg!=null) {
220          String JavaDoc pkgId=pkg.getId();
221          // check if package is already imported
222
if (idToPackages.containsKey(pkgId)) {
223             // check if this is the same package, or just the one with the same id
224
if (xmlFileToPackage.containsKey(pkgReference)) {
225                return getPackageById(pkgId);
226             } else {
227                throw new RuntimeException JavaDoc("Can't open two packages with the same Id");
228             }
229          }
230          ArrayList JavaDoc l=(ArrayList JavaDoc)idToPackages.get(pkgId);
231          if (l==null) {
232             l=new ArrayList JavaDoc();
233          }
234          l.add(pkg);
235          idToPackages.put(pkgId,l);
236          xmlFileToPackage.put(pkgReference,pkg);
237          try {
238             packageToParentDirectory.put(pkg,f.getParentFile().getCanonicalPath());
239          } catch (Exception JavaDoc ex) {
240             packageToParentDirectory.put(pkg,f.getParentFile().getAbsolutePath());
241          }
242
243          // open all external packages if handleExternalPackages is set to true,
244
// otherwise, it assumes that if there are external packages, the
245
// href element is similar to their Ids
246
Iterator JavaDoc eps=pkg.getExternalPackages().toElements().iterator();
247          while (eps.hasNext()) {
248             String JavaDoc pathToExtPackage=((ExternalPackage)eps.next()).getHref();
249             String JavaDoc extPkgId=null;
250             if (handleExternalPackages) {
251                // setting working dir to be the one of the current package
252
String JavaDoc ptep=XMLUtil.getCanonicalPath(pathToExtPackage,baseDirectory,false);
253                //System.setProperty("user.dir",packageToParentDirectory.get(pkg).toString());
254
Package JavaDoc extPkg=openPackageRecursively(ptep,handleExternalPackages);
255                extPkgId=extPkg.getId();
256             } else {
257                extPkgId=XMLUtil.getExternalPackageId(pathToExtPackage);
258             }
259             pkg.addExternalPackageMapping(pathToExtPackage, extPkgId);
260          }
261       } else {
262          System.err.println("Problems with opening file "+pkgReference);
263       }
264       return pkg;
265    }
266
267
268    /**
269     * Opens all the packages represented by their streams, and returns first of them.
270     * This implementation assumes that external package references have the similar
271     * name as Id of external package, i.e. if external package reference
272     * is ../tests/maintest/testPackage.xpdl, it is assumed that external package's Id
273     * is testPackage.
274     */

275    public Package JavaDoc openPackagesFromStreams (List JavaDoc pkgContents,boolean isFileStream) throws Exception JavaDoc {
276       Package JavaDoc pkg=null;
277       for (int i=0; i<pkgContents.size(); i++) {
278          byte[] pkgCont=(byte[])pkgContents.get(i);
279          Package JavaDoc p=openPackageFromStream(pkgCont,isFileStream);
280          if (i==0) {
281             pkg=p;
282          }
283       }
284       return pkg;
285    }
286
287    /**
288     * This implementation assumes that external package references have the similar
289     * name as Id of external package, i.e. if external package reference
290     * is ../tests/maintest/testPackage.xpdl, it is assumed that external package's Id
291     * is testPackage.
292     */

293    public Package JavaDoc openPackageFromStream (byte[] pkgContent,boolean isFileStream) throws Exception JavaDoc {
294       Package JavaDoc pkg=null;
295       if (isFileStream) {
296          String JavaDoc fileContStr=new String JavaDoc(pkgContent,"UTF8");
297          pkg=parseDocument(fileContStr, false);
298       } else {
299          pkg=(Package JavaDoc)XMLUtil.deserialize(pkgContent);
300       }
301       if (pkg!=null) {
302          String JavaDoc pkgId=pkg.getId();
303          ArrayList JavaDoc l=(ArrayList JavaDoc)idToPackages.get(pkgId);
304          if (l==null) {
305             l=new ArrayList JavaDoc();
306          }
307          if (!l.contains(pkg)) {
308             l.add(pkg);
309          }
310          idToPackages.put(pkgId,l);
311          Iterator JavaDoc eps=pkg.getExternalPackages().toElements().iterator();
312          while (eps.hasNext()) {
313             String JavaDoc pathToExtPackage=((ExternalPackage)eps.next()).getHref();
314             String JavaDoc extPkgId=pkg.getExternalPackageId(pathToExtPackage);
315             if (extPkgId==null) {
316                extPkgId=XMLUtil.getExternalPackageId(pathToExtPackage);
317                pkg.addExternalPackageMapping(pathToExtPackage, extPkgId);
318             }
319          }
320       }
321       return pkg;
322    }
323
324    public Package JavaDoc parseDocument (String JavaDoc toParse,boolean isFile) {
325       //long t1=0, t2=0, t3=0;
326
//t1=System.currentTimeMillis();
327
Package JavaDoc pkg=null;
328       // Create a Xerces DOM Parser
329
DOMParser parser = new DOMParser();
330
331       // Parse the Document and traverse the DOM
332
try {
333          parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error",true);
334          ParsingErrors pErrors=new ParsingErrors();
335          parser.setErrorHandler(pErrors);
336          if (isValidationON) {
337             parser.setEntityResolver(new XPDLEntityResolver());
338             parser.setFeature("http://xml.org/sax/features/validation",true);
339             parser.setFeature("http://apache.org/xml/features/validation/schema",true);
340             //parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);
341
}
342          if (isFile) {
343             //System.out.println("Parsing from file");
344
//parser.parse(toParse);
345
File JavaDoc f=new File JavaDoc(toParse);
346             if (!f.exists()) {
347                f=new File JavaDoc(f.getCanonicalPath());
348             }
349             parser.parse(new InputSource JavaDoc(new FileInputStream JavaDoc(f))); // Fixed by Harald Meister
350
} else {
351             //System.out.println("Parsing from stream");
352
parser.parse(new InputSource JavaDoc(new StringReader JavaDoc(toParse)));
353          }
354          Document JavaDoc document = parser.getDocument();
355          Set JavaDoc errorMessages = pErrors.getErrorMessages();
356          if (errorMessages.size()>0) {
357             //System.err.println("Errors during document parsing");
358
if (isFile) {
359                parsingErrorMessages.put(toParse,errorMessages);
360             } else {
361                parsingErrorMessages.put("",errorMessages);
362             }
363          }
364          if (document!=null) {
365             //pkg=new Package(this);
366
pkg=new Package JavaDoc();
367             //t2=System.currentTimeMillis();
368
XMLUtil.fromXML(document.getDocumentElement(),pkg);
369             //System.out.println("package "+pkg+" imported");
370
}
371       } catch (Exception JavaDoc ex) {
372          ex.printStackTrace();
373          System.err.println("Fatal error while parsing document");
374          Set JavaDoc fem=new HashSet JavaDoc();
375          fem.add("Fatal error while parsing document");
376          if (isFile) {
377             parsingErrorMessages.put(toParse,fem);
378          } else {
379             parsingErrorMessages.put("",fem);
380          }
381          return null;
382       }
383       //t3=System.currentTimeMillis();
384
//System.out.println("TOverall ="+(t3-t1));
385
//System.out.println("TParse ="+(t2-t1));
386
//System.out.println("TFXML ="+(t3-t2));
387

388       return pkg;
389    }
390
391    /**
392     * This method should be called immediatelly after opening a document,
393     * otherwise, messages could be invalid.
394     * @return The map which keys are opened packages, and values are the sets
395     * of errors for corresponding package.
396     */

397    public Map JavaDoc getParsingErrorMessages () {
398       return parsingErrorMessages;
399    }
400
401    public synchronized List JavaDoc closePackages (String JavaDoc pkgId) {
402       ArrayList JavaDoc l=(ArrayList JavaDoc)idToPackages.remove(pkgId);
403       if (l!=null) {
404          // removing file to package mapping
405
Iterator JavaDoc itr=l.iterator();
406          while (itr.hasNext()) {
407             Package JavaDoc toRemove=(Package JavaDoc)itr.next();
408             Iterator JavaDoc it=xmlFileToPackage.entrySet().iterator();
409             Object JavaDoc keyToRemove=null;
410             while (it.hasNext()) {
411                Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
412                Object JavaDoc key=me.getKey();
413                Object JavaDoc val=me.getValue();
414                if (val.equals(toRemove)) {
415                   keyToRemove=key;
416                   break;
417                }
418             }
419             if (keyToRemove!=null) {
420                xmlFileToPackage.remove(keyToRemove);
421             }
422             packageToParentDirectory.remove(toRemove);
423          }
424
425       }
426       return l;
427    }
428
429    public synchronized Package JavaDoc closePackageVersion (String JavaDoc pkgId,String JavaDoc pkgVer) {
430       ArrayList JavaDoc l=(ArrayList JavaDoc)idToPackages.get(pkgId);
431       Package JavaDoc toRemove=null;
432       if (l!=null) {
433          // removing file to package mapping
434
Iterator JavaDoc itr=l.iterator();
435          while (itr.hasNext()) {
436             Package JavaDoc p=(Package JavaDoc)itr.next();
437             if (p.getInternalVersion().equals(pkgVer)) {
438                toRemove=p;
439                break;
440             }
441          }
442          if (toRemove!=null) {
443             Iterator JavaDoc it=xmlFileToPackage.entrySet().iterator();
444             Object JavaDoc keyToRemove=null;
445             while (it.hasNext()) {
446                Map.Entry JavaDoc me=(Map.Entry JavaDoc)it.next();
447                Object JavaDoc key=me.getKey();
448                Object JavaDoc val=me.getValue();
449                if (val.equals(toRemove)) {
450                   keyToRemove=key;
451                   break;
452                }
453             }
454             if (keyToRemove!=null) {
455                xmlFileToPackage.remove(keyToRemove);
456             }
457             packageToParentDirectory.remove(toRemove);
458          }
459
460       }
461       return toRemove;
462    }
463
464    public synchronized void closeAllPackages () {
465       /*System.out.println("I'm XI "+this.hashCode() +" - closing pkgs=");
466        Iterator it=idToPackage.values().iterator();
467        while(it.hasNext()) {
468        Package p=(Package)it.next();
469        System.out.println(" p="+p.getId()+", hc="+p.hashCode());
470        }*/

471       idToPackages.clear();
472       xmlFileToPackage.clear();
473       packageToParentDirectory.clear();
474    }
475
476    public synchronized String JavaDoc getIdFromFile (String JavaDoc xmlFile) {
477       try {
478          // Create parser
479
DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
480          factory.setValidating(false);
481          DocumentBuilder JavaDoc parser = factory.newDocumentBuilder();
482          Document JavaDoc document=null;
483
484          // Parse the Document
485
try {
486             //document=parser.parse(xmlFile);
487
File JavaDoc f=new File JavaDoc(xmlFile);
488             if (!f.exists()) {
489                f=new File JavaDoc(f.getCanonicalPath());
490             }
491             document=parser.parse(new InputSource JavaDoc(new FileInputStream JavaDoc(f))); // Fixed by Harald Meister
492
} catch (Exception JavaDoc ex) {
493             document=parser.parse(new InputSource JavaDoc(new StringReader JavaDoc(xmlFile)));
494          }
495          return XMLUtil.getId(document.getDocumentElement());
496       } catch (Exception JavaDoc ex) {
497          return "";
498       }
499    }
500
501    public synchronized void synchronizePackages (XMLInterface xmlInterface) {
502       closeAllPackages();
503
504       Iterator JavaDoc it=xmlInterface.getAllPackages().iterator();
505       while (it.hasNext()) {
506          Package JavaDoc pkg=(Package JavaDoc)it.next();
507          String JavaDoc pkgId=pkg.getId();
508
509          ArrayList JavaDoc l=(ArrayList JavaDoc)idToPackages.get(pkgId);
510          if (l==null) {
511             l=new ArrayList JavaDoc();
512          }
513          l.add(pkg);
514          idToPackages.put(pkgId,l);
515          String JavaDoc fp=xmlInterface.getAbsoluteFilePath(pkg);
516          if (fp!=null) {
517             xmlFileToPackage.put(fp,pkg);
518          }
519          String JavaDoc pd=xmlInterface.getParentDirectory(pkg);
520          if (pd!=null) {
521             packageToParentDirectory.put(pkg,pd);
522          }
523       }
524    }
525
526 }
527
528
Popular Tags