KickJava   Java API By Example, From Geeks To Geeks.

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


1 /* XML.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 import org.enhydra.jawe.xml.elements.Package;
15
16 import java.util.*;
17 import java.io.*;
18
19 import org.w3c.dom.*;
20 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
21 import javax.xml.parsers.DocumentBuilder JavaDoc;
22 import org.apache.xerces.parsers.DOMParser;
23 import org.xml.sax.*;
24
25 /**
26  * Class which purpose is to provide methods which are
27  * used by classes that represents program apstraction of
28  * XML elements. These methods offers support for reading or
29  * writting an XML document and for generating the tooltips for
30  * for the classes that needs it.
31  */

32 public class XMLInterfaceForJDK13 implements XMLInterface {
33
34    protected Map idToPackage=new HashMap();
35    protected Map xmlFileToPackage=new HashMap();
36    protected Map pkgIdToFileContent=new HashMap();
37    protected Map packageToParentDirectory=new HashMap();
38
39    protected String JavaDoc mainPackageReference;
40
41    protected Map parsingErrorMessages=new HashMap();
42    protected boolean isValidationON=true;
43
44    public void setValidation (boolean isActive) {
45       isValidationON=isActive;
46    }
47
48    public void clearParserErrorMessages () {
49       parsingErrorMessages.clear();
50    }
51
52    /**
53     * This method has to be called from the newly created package after its
54     * Id is entered.
55     * @param pkg
56     */

57    public void register (Package JavaDoc pkg) {
58       idToPackage.put(pkg.get("Id").toString(),pkg);
59    }
60
61    /**
62     * This method is called when first saving new package, or when saving it with
63     * a different name.
64     * @param filename
65     * @param pkg
66     */

67    public void registerPackageFilename (String JavaDoc filename,Package JavaDoc pkg) {
68       String JavaDoc pkgId=pkg.get("Id").toString();
69       Iterator it=xmlFileToPackage.entrySet().iterator();
70       String JavaDoc uToRem=getAbsoluteFilePath(pkg);
71       if (uToRem!=null) {
72          xmlFileToPackage.remove(uToRem);
73       }
74
75       String JavaDoc cp=XMLUtil.getCanonicalPath(filename, false);
76       xmlFileToPackage.put(cp,pkg);
77
78       File f=new File(cp);
79
80       // register parent directory with the package
81
try {
82          packageToParentDirectory.put(pkg,f.getParentFile().getCanonicalPath());
83       } catch (Exception JavaDoc ex) {
84          packageToParentDirectory.put(pkg,f.getParentFile().getAbsolutePath());
85       }
86    }
87
88    public boolean isPackageOpened (String JavaDoc pkgId) {
89       return idToPackage.containsKey(pkgId);
90    }
91
92    public void putPkgIdToFileContentMapping (String JavaDoc pkgId,
93                                              String JavaDoc fileContent) {
94       //System.out.println("Adding mapping for file with id="+pkgId);
95
pkgIdToFileContent.put(pkgId,fileContent);
96    }
97
98    public String JavaDoc getPackageFileContent (String JavaDoc pkgId) {
99       return (String JavaDoc)pkgIdToFileContent.get(pkgId);
100    }
101
102    public Package JavaDoc getPackageById (String JavaDoc pkgId) {
103       return (Package JavaDoc)idToPackage.get(pkgId);
104    }
105
106    public Package JavaDoc getPackageByFilename (String JavaDoc filename) {
107       filename=XMLUtil.getCanonicalPath(filename, false);
108       return (Package JavaDoc)xmlFileToPackage.get(filename);
109    }
110
111    public Package JavaDoc getExternalPackageByRelativeFilePath (
112       String JavaDoc relativePathToExtPkg,Package JavaDoc rootPkg) {
113
114       File f=new File(relativePathToExtPkg);
115       if (!f.isAbsolute()) {
116          f=new File(getParentDirectory(rootPkg)+File.separator+relativePathToExtPkg);
117       }
118       if (f.exists()) {
119          //System.out.println("Pkg for "+relativePathToExtPkg+"->"+f.getAbsolutePath()+" is found");
120
return getPackageByFilename(f.getAbsolutePath());
121       } else {
122          //System.out.println("Pkg for "+relativePathToExtPkg+"->"+f.getAbsolutePath()+" is not found");
123
return null;
124       }
125    }
126
127    public String JavaDoc getAbsoluteFilePath (Package JavaDoc pkg) {
128       Iterator it=xmlFileToPackage.entrySet().iterator();
129       String JavaDoc fullPath=null;
130       while (it.hasNext()) {
131          Map.Entry me=(Map.Entry)it.next();
132          String JavaDoc u=(String JavaDoc)me.getKey();
133          Package JavaDoc p=(Package JavaDoc)me.getValue();
134          if (p.equals(pkg)) {
135             fullPath=u;
136             break;
137          }
138       }
139       return fullPath;
140    }
141
142    public Collection getAllPackages () {
143       return idToPackage.values();
144    }
145
146    public Collection getAllPackageIds () {
147       return idToPackage.keySet();
148    }
149
150    public Collection getAllPackageFilenames () {
151       return xmlFileToPackage.keySet();
152    }
153
154    public boolean doesPackageFileExists (String JavaDoc xmlFile) {
155       if (new File(xmlFile).exists() || getPackageFileContent(xmlFile)!=null) {
156          return true;
157       } else {
158          return false;
159       }
160    }
161
162    public String JavaDoc getParentDirectory (Package JavaDoc pkg) {
163       return (String JavaDoc)packageToParentDirectory.get(pkg);
164    }
165
166    public Package JavaDoc openPackage (String JavaDoc pkgReference,boolean openFromStream) {
167       parsingErrorMessages.clear();
168       if (!openFromStream) {
169          mainPackageReference=pkgReference;
170       }
171       // remember the all packages before opening the given package
172
Set pre=new HashSet(getAllPackages());
173       // this method opens the package and all of it's external packages
174
Package JavaDoc pkg=openDocument(pkgReference,openFromStream);
175       // get all packages after opening the given package
176
Set post=new HashSet(getAllPackages());
177       // extract newly opened packages
178
post.removeAll(pre);
179       //System.out.println("Newly opened packages are: "+post);
180
// append all external packages of each newly added package (this means
181
// the packages referenced by the package's external packages, because
182
// till now, only the first level external packages are added).
183
// (there can be cross-reference, so it must be done this way).
184
Iterator newPackages=post.iterator();
185       while (newPackages.hasNext()) {
186          Package JavaDoc p=(Package JavaDoc)newPackages.next();
187          appendAllExternalPackagesForPackage(p);
188          //System.out.println("Eps for p "+p+" are "+p.getAllExternalPackages());
189
}
190
191       // calling afterImporting method on package and all ext. packages
192
// NOTE: this can't be done within the previous loop
193
newPackages=post.iterator();
194       while (newPackages.hasNext()) {
195          Package JavaDoc p=(Package JavaDoc)newPackages.next();
196          p.afterImporting();
197       }
198       if (pkg!=null && !openFromStream) {
199          System.setProperty("user.dir",getParentDirectory(pkg));
200       }
201       //printDebug();
202
return pkg;
203    }
204
205    public void printDebug () {
206       System.out.println("idToPackage="+idToPackage);
207       System.out.println("xmlFileToPackage="+xmlFileToPackage);
208       System.out.println("pkgIdToFileContent="+pkgIdToFileContent);
209       System.out.println("packageToWorkingDirectory="+packageToParentDirectory);
210    }
211
212    // Recursive implementation
213
protected Package JavaDoc openDocument (String JavaDoc pkgReference,boolean openFromStream) {
214
215       Package JavaDoc pkg=null;
216       File f=null;
217       String JavaDoc oldP=pkgReference;
218
219       if (!openFromStream) {
220          pkgReference=XMLUtil.getCanonicalPath(pkgReference, false);
221          if (pkgReference==null) {
222             Set fem=new HashSet();
223             fem.add("File does not exist");
224             parsingErrorMessages.put(oldP,fem);
225             return null;
226          } else {
227
228             f=new File(pkgReference);
229             // set the proper user dir
230
try {
231                System.setProperty("user.dir",f.getParentFile().getCanonicalPath());
232             } catch (Exception JavaDoc ex) {
233                System.setProperty("user.dir",f.getParentFile().getAbsolutePath());
234             }
235          }
236       }
237
238       if (xmlFileToPackage.containsKey(pkgReference)) {
239          return getPackageByFilename(pkgReference);
240       }
241
242       if (!openFromStream) {
243          pkg=parseDocument(pkgReference,true);
244          /*try {
245           // trying to open main package file as 'rw'
246           // and to lock it exclusivly
247           if (oldP.equals(mainPackageReference)) {
248           RandomAccessFile raf=new RandomAccessFile(f,"rw");
249           rndAccessFiles.put(pkg,raf);
250           if (fileLocking) {
251           FileLock fl=raf.getChannel().tryLock();
252           // this happens if the main package is not already locked
253           if (fl!=null) {
254           fileLocks.put(pkg,fl);
255           // this happens if the file is already opened as 'rw' and locked
256           // exclusivly, or if it is opened as 'r' and locked as shared
257           } else {
258           Set errorMessages = new HashSet();
259           errorMessages.add(XMLUtil.getLanguageDependentString("ErrorTheFileIsLocked"));
260           parsingErrorMessages.put(pkgReference,errorMessages);
261           return null;
262           }
263           }
264           // trying to open external package file as 'rw'
265           // and to lock it exclusivly
266           } else {
267           RandomAccessFile raf=new RandomAccessFile(f,"r");
268           rndAccessFiles.put(pkg,raf);
269           if (fileLocking) {
270           FileLock fl=raf.getChannel().tryLock(0L,Long.MAX_VALUE,true);
271           // this happens if the file isn't already opened as
272           // 'rw' and locked exclusivly
273           if (fl!=null) {
274           fileLocks.put(pkg,fl);
275           // this happens if the file is opened as 'rw' and locked exclusivly
276           } else {
277           Set errorMessages = new HashSet();
278           errorMessages.add(XMLUtil.getLanguageDependentString("ErrorTheFileIsLocked"));
279           parsingErrorMessages.put(pkgReference,errorMessages);
280           return null;
281           }
282           }
283           }
284           // this exception happens if using jdk1.4.0 under Linux
285           } catch (Exception ex) {
286           //ex.printStackTrace();
287           }*/

288       } else {
289          pkg=parseDocument(getPackageFileContent(pkgReference),false);
290       }
291
292       if (pkg!=null) {
293          String JavaDoc pkgId=pkg.get("Id").toString();
294          // check if package is already imported
295
if (idToPackage.containsKey(pkgId)) {
296             // check if this is the same package, or just the one with the same id
297
if ((!openFromStream && xmlFileToPackage.containsKey(pkgReference)) ||
298                    (openFromStream && getPackageFileContent(pkgReference)!=null)) {
299                return getPackageById(pkgId);
300             } else {
301                return null;
302             }
303          }
304          idToPackage.put(pkgId,pkg);
305          if (!openFromStream) {
306             xmlFileToPackage.put(pkgReference,pkg);
307             try {
308                packageToParentDirectory.put(pkg,f.getParentFile().getCanonicalPath());
309             } catch (Exception JavaDoc ex) {
310                packageToParentDirectory.put(pkg,f.getParentFile().getAbsolutePath());
311             }
312          }
313
314          // open all external packages
315
Iterator eps=((ExternalPackages)pkg.get("ExternalPackages")).
316             toCollection().iterator();
317          while (eps.hasNext()) {
318             String JavaDoc pathToExtPackage=((ExternalPackage)eps.next()).get("href").toString();
319             // setting working dir to be the one of the current package
320
if (!openFromStream) {
321                System.setProperty("user.dir",packageToParentDirectory.get(pkg).toString());
322             }
323             Package JavaDoc extPkg=openDocument(pathToExtPackage,openFromStream);
324             if (extPkg!=null) {
325                pkg.addExternalPackage(extPkg);
326             }
327          }
328       } else {
329          System.err.println("Problems with opening file "+pkgReference);
330       }
331       return pkg;
332    }
333
334    protected void appendAllExternalPackagesForPackage(Package JavaDoc m) {
335       Stack s = new Stack();
336       s.addAll(m.getAllExternalPackages());
337       Set result=new HashSet();
338       while (!s.isEmpty()) {
339          Package JavaDoc tmp=(Package JavaDoc)s.pop();
340          Iterator extPkgs=tmp.getAllExternalPackages().iterator();
341          while (extPkgs.hasNext()) {
342             Object JavaDoc nextP=extPkgs.next();
343             if (!m.getAllExternalPackages().contains(nextP) && !s.contains(nextP) && nextP!=m) {
344                s.add(nextP);
345                m.addExternalPackage((Package JavaDoc)nextP);
346             }
347          }
348       }
349    }
350
351    public Package JavaDoc parseDocument (String JavaDoc toParse,boolean isFile) {
352       Package JavaDoc pkg=null;
353       // Create a Xerces DOM Parser
354
DOMParser parser = new DOMParser();
355
356       // Parse the Document and traverse the DOM
357
try {
358          parser.setFeature("http://apache.org/xml/features/continue-after-fatal-error",true);
359          ParsingErrors pErrors=new ParsingErrors();
360          parser.setErrorHandler(pErrors);
361          if (isValidationON) {
362             parser.setEntityResolver(new XPDLEntityResolver());
363             parser.setFeature("http://xml.org/sax/features/validation",true);
364             parser.setFeature("http://apache.org/xml/features/validation/schema",true);
365             //parser.setFeature("http://apache.org/xml/features/validation/schema-full-checking",true);
366
}
367          if (isFile) {
368             //System.out.println("Parsing from file");
369
File f=new File(toParse);
370             if (!f.exists()) {
371                f=new File(f.getCanonicalPath());
372             }
373             //parser.parse(xmlFile);
374
parser.parse(new InputSource(new FileInputStream(f))); // Fixed by Harald Meister
375
} else {
376             //System.out.println("Parsing from stream");
377
parser.parse(new InputSource(new StringReader(toParse)));
378          }
379          Document document = parser.getDocument();
380          Set errorMessages = pErrors.getErrorMessages();
381          if (errorMessages.size()>0) {
382             //System.err.println("Errors during document parsing");
383
if (isFile) {
384                parsingErrorMessages.put(toParse,errorMessages);
385             } else {
386                parsingErrorMessages.put("",errorMessages);
387             }
388          }
389          if (document!=null) {
390             pkg=new Package JavaDoc(this);
391             pkg.fromXML(document.getDocumentElement());
392             //System.out.println("package "+pkg+" imported");
393
}
394       } catch (Exception JavaDoc ex) {
395          //ex.printStackTrace();
396
System.err.println("Fatal error while parsing document");
397          Set fem=new HashSet();
398          fem.add("Fatal error while parsing document");
399          if (isFile) {
400             parsingErrorMessages.put(toParse,fem);
401          } else {
402             parsingErrorMessages.put("",fem);
403          }
404          return null;
405       }
406       return pkg;
407    }
408
409    /**
410     * This method should be called immediatelly after opening a document,
411     * otherwise, messages could be invalid.
412     * @return The map which keys are opened packages, and values are the sets
413     * of errors for corresponding package.
414     */

415    public Map getParsingErrorMessages () {
416       return parsingErrorMessages;
417    }
418
419    public void closePackage (String JavaDoc pkgId) {
420       Package JavaDoc toRemove=(Package JavaDoc)idToPackage.remove(pkgId);
421       if (toRemove!=null) {
422          // removing file to package mapping
423
Iterator it=xmlFileToPackage.entrySet().iterator();
424          Object JavaDoc keyToRemove=null;
425          while (it.hasNext()) {
426             Map.Entry me=(Map.Entry)it.next();
427             Object JavaDoc key=me.getKey();
428             Object JavaDoc val=me.getValue();
429             if (val.equals(toRemove)) {
430                keyToRemove=key;
431                break;
432             }
433          }
434          if (keyToRemove!=null) {
435             xmlFileToPackage.remove(keyToRemove);
436          }
437
438          packageToParentDirectory.remove(toRemove);
439       }
440
441       pkgIdToFileContent.remove(pkgId);
442    }
443
444    public void closeAllPackages () {
445       idToPackage.clear();
446       xmlFileToPackage.clear();
447       packageToParentDirectory.clear();
448       pkgIdToFileContent.clear();
449    }
450
451    public String JavaDoc getIDFromFile (String JavaDoc xmlFile) {
452       try {
453          // Create parser
454
DocumentBuilderFactory JavaDoc factory = DocumentBuilderFactory.newInstance();
455          factory.setValidating(false);
456          DocumentBuilder JavaDoc parser = factory.newDocumentBuilder();
457          Document document=null;
458
459          // Parse the Document
460
try {
461             File f=new File(xmlFile);
462             if (!f.exists()) {
463                f=new File(f.getCanonicalPath());
464             }
465             //document=parser.parse(xmlFile);
466
document=parser.parse(new InputSource(new FileInputStream(f))); // Fixed by Harald Meister
467
} catch (Exception JavaDoc ex) {
468             document=parser.parse(new InputSource(new StringReader(getPackageFileContent(xmlFile))));
469          }
470          return XMLUtil.getID(document.getDocumentElement());
471       } catch (Exception JavaDoc ex) {
472          return "";
473       }
474    }
475
476 }
477
478
Popular Tags