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