01: /*
02: * Copyright 2004 Outerthought bvba and Schaubroeck nv
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.outerj.daisy.frontend.components.misc;
17:
18: import org.apache.cocoon.forms.validation.WidgetValidator;
19: import org.apache.cocoon.forms.validation.ValidationErrorAware;
20: import org.apache.cocoon.forms.validation.ValidationError;
21: import org.apache.cocoon.forms.formmodel.Widget;
22: import org.xml.sax.InputSource;
23: import org.xml.sax.SAXException;
24: import org.xml.sax.helpers.DefaultHandler;
25: import org.outerj.daisy.xmlutil.LocalSAXParserFactory;
26:
27: import javax.xml.parsers.SAXParserFactory;
28: import javax.xml.parsers.SAXParser;
29: import java.io.StringReader;
30: import java.io.IOException;
31:
32: /**
33: * An XML well-formedness validator for CForms.
34: */
35: public class XmlValidator implements WidgetValidator {
36: public boolean validate(Widget widget) {
37: Object value = widget.getValue();
38: if (value != null && value instanceof String) {
39: SAXParserFactory parserFactory = LocalSAXParserFactory
40: .getSAXParserFactory();
41: SAXParser parser;
42: try {
43: parser = parserFactory.newSAXParser();
44: } catch (Exception e) {
45: throw new RuntimeException(
46: "Unexpected error constructing SAX parser in XML validator.",
47: e);
48: }
49: try {
50: parser.parse(new InputSource(new StringReader(
51: (String) value)), new DefaultHandler());
52: } catch (SAXException e) {
53: ((ValidationErrorAware) widget)
54: .setValidationError(new ValidationError(
55: "Well-formed XML required.", false));
56: return false;
57: } catch (IOException e) {
58: throw new RuntimeException(
59: "Unexpected IO exception in XML validator.", e);
60: }
61: }
62: return true;
63: }
64: }
|