1 package org.objectweb.celtix.tools.common.dom; 2 3 import java.io.IOException ; 4 import java.io.InputStream ; 5 import java.util.logging.Level ; 6 import java.util.logging.Logger ; 7 8 import javax.xml.XMLConstants ; 9 import javax.xml.parsers.DocumentBuilder ; 10 import javax.xml.parsers.DocumentBuilderFactory ; 11 import javax.xml.transform.stream.StreamSource ; 12 import javax.xml.validation.Schema ; 13 import javax.xml.validation.SchemaFactory ; 14 15 import org.w3c.dom.Document ; 16 import org.xml.sax.SAXException ; 17 18 import org.objectweb.celtix.common.logging.LogUtils; 19 20 24 public class ExtendedDocumentBuilder { 25 26 private static final Logger LOG = LogUtils.getL7dLogger(ExtendedDocumentBuilder.class); 27 28 private final DocumentBuilderFactory parserFactory; 29 private DocumentBuilder parser; 30 31 private SchemaFactory schemaFactory; 32 private Schema schema; 33 34 public ExtendedDocumentBuilder() { 35 parserFactory = DocumentBuilderFactory.newInstance(); 36 parserFactory.setNamespaceAware(true); 37 } 38 39 private InputStream getSchemaLocation() { 40 String toolspec = "/org/objectweb/celtix/tools/common/toolspec/tool-specification.xsd"; 41 return getClass().getResourceAsStream(toolspec); 42 } 43 44 public void setValidating(boolean validate) { 45 if (validate) { 46 this.schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 47 try { 48 this.schema = schemaFactory.newSchema(new StreamSource (getSchemaLocation())); 49 } catch (org.xml.sax.SAXException e) { 50 LOG.log(Level.SEVERE, "SCHEMA_FACTORY_EXCEPTION_MSG"); 51 } 52 this.parserFactory.setSchema(this.schema); 53 } 54 } 55 56 57 private DocumentBuilder getParser() { 58 if (parser == null) { 59 try { 60 parser = parserFactory.newDocumentBuilder(); 61 } catch (javax.xml.parsers.ParserConfigurationException e) { 62 LOG.log(Level.SEVERE, "NEW_DOCUMENT_BUILDER_EXCEPTION_MSG"); 63 } 64 } 65 return parser; 66 } 67 68 public Document parse(InputStream in) throws SAXException , IOException { 69 if (in == null && LOG.isLoggable(Level.FINE)) { 70 LOG.fine("ExtendedDocumentBuilder trying to parse a null inputstream"); 71 } 72 return getParser().parse(in); 73 } 74 75 } 76 | Popular Tags |