01: package org.objectweb.celtix.tools.common.dom;
02:
03: import java.io.IOException;
04: import java.io.InputStream;
05: import java.util.logging.Level;
06: import java.util.logging.Logger;
07:
08: import javax.xml.XMLConstants;
09: 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: /**
21: * (not thread safe)
22: *
23: */
24: public class ExtendedDocumentBuilder {
25:
26: private static final Logger LOG = LogUtils
27: .getL7dLogger(ExtendedDocumentBuilder.class);
28:
29: private final DocumentBuilderFactory parserFactory;
30: private DocumentBuilder parser;
31:
32: private SchemaFactory schemaFactory;
33: private Schema schema;
34:
35: public ExtendedDocumentBuilder() {
36: parserFactory = DocumentBuilderFactory.newInstance();
37: parserFactory.setNamespaceAware(true);
38: }
39:
40: private InputStream getSchemaLocation() {
41: String toolspec = "/org/objectweb/celtix/tools/common/toolspec/tool-specification.xsd";
42: return getClass().getResourceAsStream(toolspec);
43: }
44:
45: public void setValidating(boolean validate) {
46: if (validate) {
47: this .schemaFactory = SchemaFactory
48: .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
49: try {
50: this .schema = schemaFactory.newSchema(new StreamSource(
51: getSchemaLocation()));
52: } catch (org.xml.sax.SAXException e) {
53: LOG.log(Level.SEVERE, "SCHEMA_FACTORY_EXCEPTION_MSG");
54: }
55: this .parserFactory.setSchema(this .schema);
56: }
57: }
58:
59: private DocumentBuilder getParser() {
60: if (parser == null) {
61: try {
62: parser = parserFactory.newDocumentBuilder();
63: } catch (javax.xml.parsers.ParserConfigurationException e) {
64: LOG.log(Level.SEVERE,
65: "NEW_DOCUMENT_BUILDER_EXCEPTION_MSG");
66: }
67: }
68: return parser;
69: }
70:
71: public Document parse(InputStream in) throws SAXException,
72: IOException {
73: if (in == null && LOG.isLoggable(Level.FINE)) {
74: LOG
75: .fine("ExtendedDocumentBuilder trying to parse a null inputstream");
76: }
77: return getParser().parse(in);
78: }
79:
80: }
|