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.generic;
8   
9   import org.mule.config.spring.parsers.assembly.BeanAssembler;
10  import org.mule.util.StringUtils;
11  
12  import org.springframework.beans.factory.config.BeanDefinition;
13  import org.springframework.beans.factory.support.BeanDefinitionBuilder;
14  import org.springframework.beans.factory.xml.ParserContext;
15  import org.w3c.dom.Element;
16  
17  /**
18   * This class should be used when the same element can be configured as a child or an orphan 
19   * (i.e., top-level).  It will inject the bean into the parent if the parent exists, otherwise 
20   * it will not complain (ChildDefinitionParser throws an exception if no parent exists).
21   */
22  public class OptionalChildDefinitionParser extends ChildDefinitionParser
23  {
24      private boolean isChild;
25      
26      public OptionalChildDefinitionParser(String setterMethod)
27      {
28          super(setterMethod);
29      }
30      
31      public OptionalChildDefinitionParser(String setterMethod, Class clazz)
32      {
33          super(setterMethod, clazz);
34      }
35      
36      public OptionalChildDefinitionParser(String setterMethod, Class clazz, Class constraint)
37      {
38          super(setterMethod, clazz, constraint);
39      }
40      
41      public OptionalChildDefinitionParser(String setterMethod, Class clazz, Class constraint, boolean allowClassAttribute)
42      {
43          super(setterMethod, clazz, constraint, allowClassAttribute);
44      }
45  
46      @Override
47      protected void parseChild(Element element, ParserContext parserContext, BeanDefinitionBuilder builder)
48      {
49          isChild = isChild(element, parserContext, builder);
50          super.parseChild(element, parserContext, builder);
51      }
52  
53      protected boolean isChild(Element element, ParserContext parserContext, BeanDefinitionBuilder builder)
54      {
55          String parentBean = getParentBeanName(element);
56          return !(StringUtils.isBlank(parentBean));
57      }
58      
59      public BeanDefinition getParentBeanDefinition(Element element)
60      {
61          if (isChild)
62          {
63              return super.getParentBeanDefinition(element);
64          }
65          else
66          {
67              return null;
68          }
69      }
70  
71      protected void postProcess(ParserContext context, BeanAssembler assembler, Element element)
72      {
73          if (isChild)
74          {
75              super.postProcess(context, assembler, element);
76          }
77      }
78  }
79  
80