/src/org/mt4j/util/xml/XmlHandler.java

http://mt4j.googlecode.com/ · Java · 266 lines · 136 code · 42 blank · 88 comment · 9 complexity · 275d1c6a9e573c1303519120316dec59 MD5 · raw file

  1. /***********************************************************************
  2. * mt4j Copyright (c) 2008 - 2009 C.Ruff, Fraunhofer-Gesellschaft All rights reserved.
  3. *
  4. * This program is free software: you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation, either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. *
  17. ***********************************************************************/
  18. package org.mt4j.util.xml;
  19. import java.io.ByteArrayInputStream;
  20. import java.io.File;
  21. import java.io.FileOutputStream;
  22. import java.io.IOException;
  23. import java.io.InputStream;
  24. import javax.xml.parsers.DocumentBuilder;
  25. import javax.xml.parsers.DocumentBuilderFactory;
  26. import javax.xml.parsers.ParserConfigurationException;
  27. import javax.xml.parsers.SAXParser;
  28. import javax.xml.parsers.SAXParserFactory;
  29. import org.w3c.dom.Document;
  30. import org.xml.sax.EntityResolver;
  31. import org.xml.sax.InputSource;
  32. import org.xml.sax.SAXException;
  33. import org.xml.sax.helpers.DefaultHandler;
  34. import com.sun.org.apache.xml.internal.serialize.OutputFormat;
  35. import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
  36. /**
  37. * The Class XmlHandler.
  38. *
  39. * @author Christopher Ruff
  40. */
  41. public class XmlHandler {
  42. /** The xml handler. */
  43. private static XmlHandler xmlHandler = null;
  44. /** The name space aware. */
  45. private boolean nameSpaceAware;
  46. /** The validatig. */
  47. private boolean validatig;
  48. /**
  49. * Instantiates a new xml handler.
  50. */
  51. private XmlHandler(){
  52. nameSpaceAware = false;
  53. validatig = false;
  54. }
  55. /**
  56. * Gets the single instance of XmlHandler.
  57. *
  58. * @return single instance of XmlHandler
  59. */
  60. public static XmlHandler getInstance(){
  61. if (xmlHandler == null){
  62. xmlHandler = new XmlHandler();
  63. return xmlHandler;
  64. }else
  65. return xmlHandler;
  66. }
  67. /**
  68. * loads a xml file into memory and returns a document object.
  69. *
  70. * @param file the file
  71. *
  72. * @return the document
  73. */
  74. public Document load(File file) {
  75. DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
  76. Document document = null;
  77. factory.setValidating(validatig);
  78. factory.setNamespaceAware(nameSpaceAware);
  79. try {
  80. DocumentBuilder builder = factory.newDocumentBuilder();
  81. document = builder.parse(file);
  82. System.out.println("--> Parsed the xml file : " + file);
  83. } catch (SAXException sxe) {
  84. // Error generated during parsing
  85. Exception x = sxe;
  86. if (sxe.getException() != null)
  87. x = sxe.getException();
  88. x.printStackTrace();
  89. } catch (ParserConfigurationException pce) {
  90. // Parser with specified options can't be built
  91. pce.printStackTrace();
  92. } catch (IOException ioe) {
  93. // I/O error
  94. ioe.printStackTrace();
  95. }
  96. return document;
  97. }
  98. /**
  99. * This method writes a DOM document to a file.
  100. *
  101. * @param doc the doc
  102. * @param file the file
  103. *
  104. * @return true, if write xml file
  105. */
  106. public boolean writeXmlFile(Document doc, File file) {
  107. try {
  108. FileOutputStream fileOut = new FileOutputStream(file);
  109. OutputFormat format = new OutputFormat(doc);
  110. format.setLineWidth(900);
  111. format.setIndenting(true);
  112. format.setIndent(6);
  113. format.setOmitComments(false);
  114. XMLSerializer serializer = new XMLSerializer(fileOut, format);
  115. serializer.serialize(doc);
  116. fileOut.close();
  117. System.out.println("Wrote the content of the document into the file: " + file);
  118. } catch (IOException e) {
  119. e.printStackTrace();
  120. return false;
  121. }
  122. return true;
  123. }
  124. /**
  125. * parses an xml file with the SaxParser and uses the provided
  126. * defaulthandler to process the input.
  127. *
  128. * @param defaultHandler the default handler
  129. * @param filePath the file path
  130. */
  131. public void saxParse(String filePath, DefaultHandler defaultHandler){
  132. SAXParserFactory spf = SAXParserFactory.newInstance();
  133. spf.setValidating(validatig);
  134. spf.setNamespaceAware(nameSpaceAware);
  135. try{
  136. //Dont parse external dtd, so we dont have to connect to http etc
  137. spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
  138. SAXParser parser = spf.newSAXParser();
  139. parser.getXMLReader().setEntityResolver(new EntityResolver(){
  140. public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException {
  141. return new InputSource(new ByteArrayInputStream(new byte[0]));
  142. }
  143. });
  144. File file = new File(filePath);
  145. if (file.exists()){
  146. parser.parse(new File(filePath), defaultHandler);
  147. }else{
  148. InputStream in = null;
  149. in = Thread.currentThread().getContextClassLoader().getResourceAsStream(filePath);
  150. if (in == null){
  151. in = getClass().getResourceAsStream(filePath);
  152. }
  153. parser.parse(in, defaultHandler);
  154. }
  155. }
  156. catch (Exception e){
  157. System.err.println("Error while parsing! : " + filePath);
  158. e.printStackTrace();
  159. }
  160. }
  161. /**
  162. * parses an xml file with the SaxParser and uses the provided
  163. * defaulthandler to process the input.
  164. *
  165. * @param defaultHandler the default handler
  166. * @param string the string
  167. */
  168. public void saxParseString(String string, DefaultHandler defaultHandler){
  169. SAXParserFactory spf = SAXParserFactory.newInstance();
  170. spf.setValidating(validatig);
  171. spf.setNamespaceAware(nameSpaceAware);
  172. byte stringAsByteArray[] = string.getBytes();
  173. ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(stringAsByteArray);
  174. try{
  175. SAXParser parser = spf.newSAXParser();
  176. parser.getXMLReader().setEntityResolver(new EntityResolver(){
  177. public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
  178. // return new InputSource(new ByteArrayInputStream(new byte[0]));
  179. if (systemId.endsWith(".dtd"))
  180. // this deactivates all DTDs by giving empty XML docs
  181. return new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes()));
  182. else return null;
  183. }
  184. });
  185. parser.parse(byteArrayInputStream, defaultHandler);
  186. }
  187. catch (Exception e){
  188. System.err.println("Error while parsing!");
  189. System.err.println(e);
  190. }
  191. }
  192. /**
  193. * Checks if is name space aware.
  194. *
  195. * @return true, if is name space aware
  196. */
  197. public boolean isNameSpaceAware() {
  198. return nameSpaceAware;
  199. }
  200. /**
  201. * Sets the name space aware.
  202. *
  203. * @param nameSpaceAware the new name space aware
  204. */
  205. public void setNameSpaceAware(boolean nameSpaceAware) {
  206. this.nameSpaceAware = nameSpaceAware;
  207. }
  208. /**
  209. * Checks if is validatig.
  210. *
  211. * @return true, if is validatig
  212. */
  213. public boolean isValidatig() {
  214. return validatig;
  215. }
  216. /**
  217. * Sets the validatig.
  218. *
  219. * @param validatig the new validatig
  220. */
  221. public void setValidatig(boolean validatig) {
  222. this.validatig = validatig;
  223. }
  224. }