01: /*
02: * This file is part of PFIXCORE.
03: *
04: * PFIXCORE is free software; you can redistribute it and/or modify
05: * it under the terms of the GNU Lesser General Public License as published by
06: * the Free Software Foundation; either version 2 of the License, or
07: * (at your option) any later version.
08: *
09: * PFIXCORE is distributed in the hope that it will be useful,
10: * but WITHOUT ANY WARRANTY; without even the implied warranty of
11: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12: * GNU Lesser General Public License for more details.
13: *
14: * You should have received a copy of the GNU Lesser General Public License
15: * along with PFIXCORE; if not, write to the Free Software
16: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17: */
18:
19: package de.schlund.pfixxml.config.impl;
20:
21: import java.util.HashMap;
22: import java.util.Map;
23: import java.util.Set;
24:
25: import org.apache.commons.digester.Rule;
26: import org.xml.sax.Attributes;
27: import org.xml.sax.SAXException;
28:
29: public abstract class CheckedRule extends Rule {
30: protected abstract Map<String, Boolean> wantsAttributes();
31:
32: protected void check(String namespace, String name,
33: Attributes attributes) throws Exception {
34: Map<String, Boolean> atts = wantsAttributes();
35: if (atts == null) {
36: atts = new HashMap<String, Boolean>();
37: }
38:
39: Set<String> allowedAttributes = atts.keySet();
40:
41: for (String attName : allowedAttributes) {
42: if (atts.get(attName).booleanValue()) {
43: if (attributes.getValue(attName) == null)
44: throw new SAXException("Required attribute \""
45: + attName + "\" missing on element \""
46: + name + "\" [" + namespace + "]");
47: }
48: }
49:
50: for (int i = 0; i < attributes.getLength(); i++) {
51: String attName = attributes.getLocalName(i);
52: if (!allowedAttributes.contains(attName)) {
53: throw new SAXException("Unknown attribute \"" + attName
54: + "\" specified on element \"" + name + "\" ["
55: + namespace + "]");
56: }
57: }
58:
59: }
60:
61: public void body(String namespace, String name, String text)
62: throws Exception {
63: if (text != null && !isWhitespace(text)) {
64: throw new SAXException("Got text below element \"" + name
65: + "\" [" + namespace
66: + "] although not allowed here");
67: }
68: }
69:
70: private boolean isWhitespace(String text) {
71: if (text.length() == 0) {
72: return true;
73: }
74: return text.matches("\\s*");
75: }
76:
77: }
|