KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > outerj > daisy > frontend > components > misc > XmlValidator


1 /*
2  * Copyright 2004 Outerthought bvba and Schaubroeck nv
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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 JavaDoc;
23 import org.xml.sax.SAXException JavaDoc;
24 import org.xml.sax.helpers.DefaultHandler JavaDoc;
25
26 import javax.xml.parsers.SAXParserFactory JavaDoc;
27 import javax.xml.parsers.SAXParser JavaDoc;
28 import java.io.StringReader JavaDoc;
29 import java.io.IOException JavaDoc;
30
31 /**
32  * An XML well-formedness validator for CForms.
33  */

34 public class XmlValidator implements WidgetValidator {
35     public boolean validate(Widget widget) {
36         Object JavaDoc value = widget.getValue();
37         if (value != null && value instanceof String JavaDoc) {
38             // TODO: quite ineffecient to construct the factory each time
39
SAXParserFactory JavaDoc parserFactory = SAXParserFactory.newInstance();
40             SAXParser JavaDoc parser = null;
41             try {
42                 parser = parserFactory.newSAXParser();
43             } catch (Exception JavaDoc e) {
44                 throw new RuntimeException JavaDoc("Unexpected error constructing SAX parser in XML validator.", e);
45             }
46             try {
47                 parser.parse(new InputSource JavaDoc(new StringReader JavaDoc((String JavaDoc)value)), new DefaultHandler JavaDoc());
48             } catch (SAXException JavaDoc e) {
49                 ((ValidationErrorAware)widget).setValidationError(new ValidationError("Well-formed XML required.", false));
50                 return false;
51             } catch (IOException JavaDoc e) {
52                 throw new RuntimeException JavaDoc("Unexpected IO exception in XML validator.", e);
53             }
54         }
55         return true;
56     }
57 }
58
Popular Tags