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.delegate;
8   
9   import org.mule.config.spring.parsers.MuleDefinitionParser;
10  import org.mule.config.spring.util.SpringXMLUtils;
11  import org.mule.util.CollectionUtils;
12  
13  import java.util.HashMap;
14  import java.util.Map;
15  
16  import org.springframework.beans.factory.xml.ParserContext;
17  import org.w3c.dom.Attr;
18  import org.w3c.dom.Element;
19  import org.w3c.dom.NamedNodeMap;
20  
21  /**
22   * Select sub parser depending on presence of a particular attribute
23   */
24  public class AttributeSelectionDefinitionParser extends AbstractParallelDelegatingDefinitionParser
25  {
26  
27      private Map attributeToParserIndex = new HashMap();
28  
29      public AttributeSelectionDefinitionParser(String attribute, MuleDefinitionParser delegate)
30      {
31          super();
32          addDelegate(attribute, delegate);
33      }
34  
35      public void addDelegate(String attribute, MuleDefinitionParser delegate)
36      {
37          addDelegate(delegate);
38          attributeToParserIndex.put(attribute, new Integer(size() - 1));
39          delegate.setIgnoredDefault(true);
40          delegate.removeIgnored(attribute);
41      }
42  
43      protected MuleDefinitionParser getDelegate(Element element, ParserContext parserContext)
44      {
45          NamedNodeMap attributes = element.getAttributes();
46          for (int i = 0; i < attributes.getLength(); ++i)
47          {
48              String attribute = SpringXMLUtils.attributeName((Attr) attributes.item(i));
49              if (attributeToParserIndex.containsKey(attribute))
50              {
51                  return getDelegate(((Integer) attributeToParserIndex.get(attribute)).intValue());
52              }
53          }
54          throw new IllegalArgumentException("Element " + SpringXMLUtils.elementToString(element) +
55                  " does not contain any attribute from " +
56                  CollectionUtils.toString(attributeToParserIndex.keySet(), 10, false));
57      }
58  
59  }