View Javadoc

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