View Javadoc

1   /*
2    * $Id: RequireAttribute.java 19191 2010-08-25 21:05:23Z tcarlson $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
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  
34      private Set required;
35  
36      public RequireAttribute(String required)
37      {
38          this(new String[]{required});
39      }
40  
41      public RequireAttribute(String[] required)
42      {
43          this.required = new HashSet(Arrays.asList(required));
44      }
45  
46      public void preProcess(PropertyConfiguration config, Element element)
47      {
48          NamedNodeMap attributes = element.getAttributes();
49          Iterator names = required.iterator();
50          while (names.hasNext())
51          {
52              String name = (String) names.next();
53              boolean found = false;
54              for (int i = 0; i < attributes.getLength() && !found; i++)
55              {
56                  String alias = SpringXMLUtils.attributeName((Attr) attributes.item(i));
57                  // don't translate to alias because the error message is in terms of the attributes
58                  // the user enters - we don't want to expose the details of translations
59  //                found = name.equals(config.translateName(alias));
60                  found = name.equals(alias);
61              }
62              if (!found)
63              {
64                  throw new RequireAttributeException("Attribute " + name + " is required here.");
65              }
66          }
67      }
68  
69      public static class RequireAttributeException extends IllegalStateException
70      {
71  
72          public RequireAttributeException(String message)
73          {
74              super(message);
75          }
76  
77      }
78  
79  }