01: package org.objectweb.celtix.tools.common.dom;
02:
03: import java.io.InputStream;
04: import java.util.logging.Level;
05: import java.util.logging.Logger;
06:
07: import javax.xml.XMLConstants;
08: import javax.xml.parsers.SAXParser;
09: import javax.xml.parsers.SAXParserFactory;
10: import javax.xml.transform.stream.StreamSource;
11: import javax.xml.validation.Schema;
12: import javax.xml.validation.SchemaFactory;
13:
14: import org.objectweb.celtix.common.logging.LogUtils;
15:
16: /**
17: * (not thread safe)
18: *
19: */
20: public final class SchemaValidatingSAXParser {
21:
22: private static final Logger LOG = LogUtils
23: .getL7dLogger(SchemaValidatingSAXParser.class);
24:
25: private final SAXParserFactory parserFactory = SAXParserFactory
26: .newInstance();
27: private SAXParser parser;
28: private SchemaFactory schemaFactory;
29: private Schema schema;
30:
31: public SchemaValidatingSAXParser() {
32: try {
33: parserFactory.setNamespaceAware(true);
34: parser = parserFactory.newSAXParser();
35: } catch (javax.xml.parsers.ParserConfigurationException e) {
36: LOG.log(Level.SEVERE, "SAX_PARSER_CONFIG_ERR_MSG");
37: } catch (org.xml.sax.SAXException saxe) {
38: LOG.log(Level.SEVERE, "SAX_PARSER_EXCEPTION_MSG");
39: }
40: setValidating(true);
41: }
42:
43: private InputStream getSchemaLocation() {
44: String toolspec = "/org/objectweb/celtix/tools/common/toolspec/tool-specification.xsd";
45: return getClass().getResourceAsStream(toolspec);
46: }
47:
48: public void setValidating(boolean validate) {
49: if (validate) {
50: this .schemaFactory = SchemaFactory
51: .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
52: try {
53: this .schema = schemaFactory.newSchema(new StreamSource(
54: getSchemaLocation()));
55: } catch (org.xml.sax.SAXException e) {
56: LOG.log(Level.SEVERE, "SCHEMA_FACTORY_EXCEPTION_MSG");
57: }
58: this .parserFactory.setSchema(this .schema);
59: }
60: }
61:
62: public SAXParser getSAXParser() {
63: return parser;
64: }
65: }
|