01: /**
02: * Licensed to the Apache Software Foundation (ASF) under one
03: * or more contributor license agreements. See the NOTICE file
04: * distributed with this work for additional information
05: * regarding copyright ownership. The ASF licenses this file
06: * to you under the Apache License, Version 2.0 (the
07: * "License"); you may not use this file except in compliance
08: * with the License. You may obtain a copy of the License at
09: *
10: * http://www.apache.org/licenses/LICENSE-2.0
11: *
12: * Unless required by applicable law or agreed to in writing,
13: * software distributed under the License is distributed on an
14: * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15: * KIND, either express or implied. See the License for the
16: * specific language governing permissions and limitations
17: * under the License.
18: */package org.apache.cxf.tools.common.dom;
19:
20: import java.io.InputStream;
21: import java.util.logging.Level;
22: import java.util.logging.Logger;
23:
24: import javax.xml.XMLConstants;
25: import javax.xml.parsers.SAXParser;
26: import javax.xml.parsers.SAXParserFactory;
27: import javax.xml.transform.stream.StreamSource;
28: import javax.xml.validation.Schema;
29: import javax.xml.validation.SchemaFactory;
30:
31: import org.apache.cxf.common.logging.LogUtils;
32:
33: /**
34: * (not thread safe)
35: *
36: */
37: public final class SchemaValidatingSAXParser {
38:
39: private static final Logger LOG = LogUtils
40: .getL7dLogger(SchemaValidatingSAXParser.class);
41:
42: private final SAXParserFactory parserFactory = SAXParserFactory
43: .newInstance();
44: private SAXParser parser;
45: private SchemaFactory schemaFactory;
46: private Schema schema;
47:
48: public SchemaValidatingSAXParser() {
49: try {
50: parserFactory.setNamespaceAware(true);
51: parser = parserFactory.newSAXParser();
52: } catch (javax.xml.parsers.ParserConfigurationException e) {
53: LOG.log(Level.SEVERE, "SAX_PARSER_CONFIG_ERR_MSG");
54: } catch (org.xml.sax.SAXException saxe) {
55: LOG.log(Level.SEVERE, "SAX_PARSER_EXCEPTION_MSG");
56: }
57: setValidating(true);
58: }
59:
60: private InputStream getSchemaLocation() {
61: String toolspec = "/org/apache/cxf/tools/common/toolspec/tool-specification.xsd";
62: return getClass().getResourceAsStream(toolspec);
63: }
64:
65: public void setValidating(boolean validate) {
66: if (validate) {
67: this .schemaFactory = SchemaFactory
68: .newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
69: try {
70: this .schema = schemaFactory.newSchema(new StreamSource(
71: getSchemaLocation()));
72: } catch (org.xml.sax.SAXException e) {
73: LOG.log(Level.SEVERE, "SCHEMA_FACTORY_EXCEPTION_MSG");
74: }
75: try {
76: this .parserFactory.setSchema(this .schema);
77: } catch (UnsupportedOperationException e) {
78: LOG.log(Level.WARNING, "SAX_PARSER_NOT_SUPPORTED", e);
79: }
80: }
81: }
82:
83: public SAXParser getSAXParser() {
84: return parser;
85: }
86: }
|