Squiz Matrix  4.12.2
 All Data Structures Namespaces Functions Variables Pages
XML.java
1 
16 package net.squiz.matrix.core;
17 
18 import javax.xml.transform.stream.StreamSource;
19 import javax.xml.parsers.*;
20 import org.w3c.dom.Document;
21 import org.xml.sax.SAXException;
22 import java.io.*;
23 
31 public class XML {
32 
33  /* the static Document Builder instance */
34  private static DocumentBuilder builder;
35 
36  // cannot instantiate
37  private XML() {}
38 
44  public static DocumentBuilder getParser() throws SAXException {
45 
46  if (builder == null) {
47  try {
48  DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
49  factory.setIgnoringElementContentWhitespace(false);
50  builder = factory.newDocumentBuilder();
51  } catch (ParserConfigurationException pce) {
52  throw new SAXException("Error creating the document builder : "
53  + pce.getMessage());
54  }
55  }
56  return builder;
57  }
58 
65  public static synchronized Document getDocumentFromInputStream(InputStream is)
66  throws SAXException {
67 
68  Document doc = null;
69  DocumentBuilder db = getParser();
70 
71  if (is == null)
72  throw new SAXException("Input Stream of XML source cannot be null");
73 
74  try {
75  doc = db.parse(is);
76  } catch (IOException se) {
77  throw new SAXException("Could not create the document from the " +
78  "Input Stream : " + se.getMessage());
79  }
80 
81  if (doc.getDocumentElement().getTagName().equals("error"))
82  throw new SAXException("Could not create the document");
83 
84  return doc;
85  }
86 
94  public static synchronized Document getDocumentFromString(String xmlStr)
95  throws SAXException {
96 
97  byte [] xmlArray = xmlStr.getBytes();
98  ByteArrayInputStream xmlStream = new ByteArrayInputStream(xmlArray);
99 
100  StreamSource ss = new StreamSource(xmlStream);
101  Document doc = null;
102 
103  try {
104  doc = getDocumentFromInputStream(ss.getInputStream());
105  } catch (SAXException se) {
106  throw new SAXException("Could not create document from String: "
107  + se.getMessage());
108  }
109 
110  return doc;
111  }
112 }