01: /*
02: * $Id: RequireAttribute.java 10346 2008-01-16 13:55:31Z acooke $
03: * --------------------------------------------------------------------------------------
04: * Copyright (c) MuleSource, Inc. All rights reserved. http://www.mulesource.com
05: *
06: * The software in this package is published under the terms of the CPAL v1.0
07: * license, a copy of which has been included with this distribution in the
08: * LICENSE.txt file.
09: */
10:
11: package org.mule.config.spring.parsers.processors;
12:
13: import org.mule.config.spring.parsers.PreProcessor;
14: import org.mule.config.spring.parsers.assembly.configuration.PropertyConfiguration;
15: import org.mule.config.spring.util.SpringXMLUtils;
16:
17: import java.util.Arrays;
18: import java.util.HashSet;
19: import java.util.Iterator;
20: import java.util.Set;
21:
22: import org.w3c.dom.Attr;
23: import org.w3c.dom.Element;
24: import org.w3c.dom.NamedNodeMap;
25:
26: /**
27: * Throws an exception if any of the required attributes (after translation) are missing.
28: * Designed to cooperates with
29: * {@link org.mule.config.spring.parsers.delegate.AbstractSerialDelegatingDefinitionParser#addHandledException(Class)}
30: */
31: public class RequireAttribute implements PreProcessor {
32:
33: private Set required;
34:
35: public RequireAttribute(String required) {
36: this (new String[] { required });
37: }
38:
39: public RequireAttribute(String[] required) {
40: this .required = new HashSet(Arrays.asList(required));
41: }
42:
43: public void preProcess(PropertyConfiguration config, Element element) {
44: NamedNodeMap attributes = element.getAttributes();
45: Iterator names = required.iterator();
46: while (names.hasNext()) {
47: String name = (String) names.next();
48: boolean found = false;
49: for (int i = 0; i < attributes.getLength() && !found; i++) {
50: String alias = SpringXMLUtils
51: .attributeName((Attr) attributes.item(i));
52: // don't translate to alias because the error message is in terms of the attributes
53: // the user enters - we don't want to expose the details of translations
54: // found = name.equals(config.translateName(alias));
55: found = name.equals(alias);
56: }
57: if (!found) {
58: throw new RequireAttributeException("Attribute " + name
59: + " is required here.");
60: }
61: }
62: }
63:
64: public static class RequireAttributeException extends
65: IllegalStateException {
66:
67: public RequireAttributeException(String message) {
68: super(message);
69: }
70:
71: }
72:
73: }
|