/Users/lyon/j4p/src/xml/musicCatalog/MyJaxpDomParser.java

1    /** 
2     * MyJaxpDomParser.java 
3     * @author Thomas Rowland 
4     * @version 02-08-03 
5     */ 
6    package xml.musicCatalog; 
7     
8    import org.w3c.dom.*; 
9    import org.xml.sax.ErrorHandler; 
10   import org.xml.sax.SAXException; 
11   import org.xml.sax.SAXParseException; 
12    
13   import javax.xml.parsers.DocumentBuilder; 
14   import javax.xml.parsers.DocumentBuilderFactory; 
15   import javax.xml.parsers.FactoryConfigurationError; 
16   import javax.xml.parsers.ParserConfigurationException; 
17   import java.io.*; 
18    
19   /* 
20    *  DomParser program demonstrating how to parse an xml file 
21    * using the DOM Level 2 api and JAXP 1.2. You need to have 
22    * jaxp-api.jar and xercesImpl.jar in your classpath. 
23    */ 
24    
25   public class MyJaxpDomParser { 
26       private String xmlFile = null; 
27       private PrintStream out = null; 
28       private Document domDoc = null; 
29       private Element root = null; 
30    
31       // Node type constants 
32       final int ELEMENT_NODE = 1; 
33       final int ATTR_NODE = 2; 
34       final int TEXT_NODE = 3; 
35    
36       // Constants used for JAXP 1.2 DocumentBuilderFactory attributes 
37       static final String JAXP_SCHEMA_LANGUAGE = 
38               "http://java.sun.com/xml/jaxp/properties/schemaLanguage"; 
39       static final String W3C_XML_SCHEMA = 
40               "http://www.w3.org/2001/XMLSchema"; 
41       static final String JAXP_SCHEMA_SOURCE = 
42               "http://java.sun.com/xml/jaxp/properties/schemaSource"; 
43    
44       /* 
45        * Parses an XML Document with no validation. 
46        * @args uri the uri of the xml source 
47        * @args os the OutputStream to send the output to 
48        * @return the DOM Document 
49        */ 
50       public Document parse(String uri, OutputStream os) 
51               throws Exception { 
52           xmlFile = uri; 
53           out = new PrintStream(os); 
54           return parse(false, false); 
55       } 
56    
57       /* 
58        * Parses an XML Document with DTD validation. 
59        * @args uri the uri of the xml source 
60        * @args os the OutputStream to send the output to 
61        * @return the DOM Document 
62        */ 
63       public Document dtdParse(String uri, OutputStream os) 
64               throws Exception { 
65           xmlFile = uri; 
66           out = new PrintStream(os); 
67           return parse(true, false); 
68       } 
69    
70       /** 
71        * Parses an XML Document with XMLSchema validation. 
72        * @args uri the uri of the xml source 
73        * @args os the OutputStream to send the output to 
74        * @return the DOM Document 
75        */ 
76       public Document xsdParse(String uri, OutputStream os) 
77               throws Exception { 
78           xmlFile = uri; 
79           out = new PrintStream(os); 
80           return parse(false, true); 
81       } 
82    
83       /* 
84        * Parses an XML Document with no validation, 
85   * DTD validation, or XSD validation. 
86        * @args dtdValidate DTD validation feature setting on or off 
87        * @args dtdValidate DTD validation feature setting on or off 
88        * @return the DOM Document 
89        */ 
90       private Document parse(boolean dtdValidate, boolean xsdValidate) 
91               throws Exception { 
92           try { 
93               //out = new PrintStream(os); 
94               DocumentBuilderFactory dbf = 
95                       DocumentBuilderFactory.newInstance(); 
96               dbf.setIgnoringElementContentWhitespace(false); 
97    
98               /*  Set the validation mode to either: 
99                    no validation, DTD validation, or XSD validation */ 
100              dbf.setValidating(dtdValidate || xsdValidate); 
101              if (xsdValidate) { 
102                  dbf.setNamespaceAware(true); 
103                  try { 
104                      dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA); 
105                  } catch (IllegalArgumentException e) { 
106                      // Parser does not support JAXP 1.2 
107                      System.err.println("Error: " + JAXP_SCHEMA_LANGUAGE 
108                              + " is not recognized by the DocumentBuilderFactory."); 
109                      System.exit(1); 
110                  } 
111   
112                  /*  You can also explicitly indentify the XMLSchema source file as 
113                      follows, however we defined it within the XML file itself */ 
114                  String schemaSource = null; 
115                  if (schemaSource != null) 
116                      dbf.setAttribute(JAXP_SCHEMA_SOURCE, new File(schemaSource)); 
117              } 
118   
119              //******************************************* 
120              DocumentBuilder db = dbf.newDocumentBuilder(); 
121              db.setErrorHandler(new MyErrorHandler()); 
122              domDoc = db.parse(xmlFile); 
123              root = domDoc.getDocumentElement(); 
124              traverse(root); 
125              out.flush(); 
126              return domDoc; 
127          } catch (FactoryConfigurationError e) { 
128              // Unable to create the factory 
129              throw new Exception( 
130                      "** FactoryConfigurationError\n" 
131                      + e.getMessage()); 
132          } catch (ParserConfigurationException e) { 
133              // Factory unable to create the parser. 
134              throw new Exception( 
135                      "** ParserConfigurationException\n" 
136                      + e.getMessage()); 
137          } catch (SAXException e) { 
138              // Exceptions thrown by the parser 
139              // Get the wrapped exception, if any 
140              Exception ex = e.getException(); 
141              String msg = null; 
142              if (ex != null) { 
143                  ex.printStackTrace(); 
144                  msg = ex.getMessage(); 
145              } 
146              throw new Exception( 
147                      "** SAXException:\n" + e.getMessage()); 
148          } catch (IOException e) { 
149              throw new Exception( 
150                      "IOException:\n" + e.getMessage()); 
151          } 
152      } 
153   
154   
155      /** 
156       *  Recursive method which traverses the DOM Document 
157       *  and outputs the content. 
158       *  @args elem the root element to begin recursion on 
159       */ 
160      private void traverse(Node elem) { 
161          try { 
162   
163              //handle the attributes 
164              if (elem.hasAttributes()) { 
165                  NamedNodeMap attrs = elem.getAttributes(); 
166                  int alength = attrs.getLength(); 
167   
168                  //loop 
169                  for (int i = 0; i < alength; i++) { 
170                      Attr attr = (Attr) attrs.item(i); 
171                      out.println(attr.getName() + ":\t" + attr.getValue()); 
172                  } 
173              } 
174              //handle the child nodes 
175              if (elem.hasChildNodes()) { 
176                  NodeList children = elem.getChildNodes(); 
177                  int length = children.getLength(); 
178   
179                  //loop 
180                  for (int i = 0; i < length; i++) { 
181                      Node n = children.item(i); 
182                      String name = n.getNodeName(); 
183   
184                      if (n.getNodeType() == ELEMENT_NODE) { 
185                          if (name.equals("Item")) 
186                              out.println("\n"); 
187                          else 
188                              out.print(name + ":\t"); 
189   
190                          traverse(n); //recurse 
191                      } else if (n.getNodeType() == TEXT_NODE) { 
192                          String txt = n.getNodeValue().trim(); 
193                          if (!txt.equals("")) { 
194                              out.println(txt); 
195                          } 
196                      } 
197                  } 
198                  return; 
199              } 
200          } catch (DOMException e) { 
201              System.out.println("*** DOMException\n" 
202                      + e.getMessage()); 
203          } 
204      } 
205   
206      /** 
207       *  Creates and returns a new Item object 
208       *  @return the new Item 
209       */ 
210      public Item createItem() { 
211          return new Item(); 
212      } 
213   
214   
215      /** 
216       *  Adds a newly created Item object to the DOM Document 
217       *  @args item the Item object 
218       */ 
219      public void addItem(Item item) throws Exception { 
220   
221          Element itemElem = null; 
222          Element elem = null; 
223          Text txtNode = null; 
224   
225          itemElem = domDoc.createElement("Item"); 
226          itemElem.setAttribute("media", item.getMedia()); 
227          root.appendChild(itemElem); 
228   
229          elem = domDoc.createElement("Artist"); 
230          txtNode = domDoc.createTextNode(item.getArtist()); 
231          elem.appendChild(txtNode); 
232          itemElem.appendChild(elem); 
233   
234          elem = domDoc.createElement("Title"); 
235          txtNode = domDoc.createTextNode(item.getTitle()); 
236          elem.appendChild(txtNode); 
237          itemElem.appendChild(elem); 
238   
239          elem = domDoc.createElement("Year"); 
240          txtNode = domDoc.createTextNode(item.getYear()); 
241          elem.appendChild(txtNode); 
242          itemElem.appendChild(elem); 
243   
244          //...Write code to add the <members> elements 
245   
246          traverse(root); 
247      } 
248   
249   
250      /** 
251       *  Writes a DOM Document as HTML 
252       */ 
253      public void toHtml(File stylesheet) throws Exception { 
254   
255          //try { 
256          System.out.println("\nXML File: " + xmlFile); 
257          String fn = xmlFile.substring(0, xmlFile.lastIndexOf(".")); 
258          File htmlFile = new File(fn + ".html"); 
259          BufferedWriter out = new BufferedWriter( 
260                  new FileWriter(htmlFile)); 
261   
262          System.out.println("\nStylesheet: " + stylesheet); 
263          System.out.println("\nOutput: " + htmlFile); 
264          //OutputStream out = new FileOutputStream(htmlFile); 
265   
266          XmlTransformer.transform(domDoc, stylesheet, out); 
267          //out.flush(); 
268          //out.close(); 
269          //} catch (IOException e) { 
270          //e.printStackTrace(); 
271          //} 
272      } 
273   
274   
275      /** 
276       *  Writes a DOM Document as XML 
277       */ 
278      public void toXml() 
279              throws Exception { 
280          XmlTransformer.writeXml(domDoc, xmlFile); 
281          System.out.println("\nOutput should have been written to : " 
282                  + xmlFile); 
283      } 
284   
285      /** 
286       * Inner class Error Handler to report validation errors 
287       * and warnings. DOM uses these SAX error handlers. 
288       */ 
289      private class MyErrorHandler implements ErrorHandler { 
290   
291          //-- The following methods are standard SAX ErrorHandler methods. 
292          public void warning(SAXParseException spe) throws SAXException { 
293              System.out.println("Warning: " + getParseExceptionInfo(spe)); 
294          } 
295   
296          public void error(SAXParseException spe) throws SAXException { 
297              String message = "Error: " + getParseExceptionInfo(spe); 
298              throw new SAXException(message); 
299          } 
300   
301          public void fatalError(SAXParseException spe) throws SAXException { 
302              String message = "Fatal Error: " + getParseExceptionInfo(spe); 
303              throw new SAXException(message); 
304          } 
305   
306          /** 
307           * Returns a string describing parse exception details 
308           */ 
309          private String getParseExceptionInfo(SAXParseException spe) { 
310              String systemId = spe.getSystemId(); 
311              if (systemId == null) { 
312                  systemId = "null"; 
313              } 
314              String info = "URI=" + systemId + 
315                      "\nLine=" + spe.getLineNumber() + 
316                      "\n" + spe.getMessage(); 
317              return info; 
318          } 
319      } 
320   
321  }// 
322   
323