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.xml.ParserContext;
13  import org.w3c.dom.Element;
14  import org.w3c.dom.Node;
15  
16  /**
17   * Grabs the text from an element and injects it into the parent, for example:
18   * 
19   * <foo>
20   *   <bar-text>A bunch of text.</bar-text>
21   * </foo>
22   * 
23   *   registerBeanDefinitionParser("foo", new OrphanDefinitionParser(Foo.class));
24   *   registerBeanDefinitionParser("bar-text", new TextDefinitionParser("barText"));
25   * 
26   * will result in a call to Foo.setBarText("A bunch of text.")
27   */
28  public class TextDefinitionParser extends ChildDefinitionParser
29  {
30      private boolean requireCdata = false;
31  
32      public TextDefinitionParser(String setterMethod)
33      {
34          super(setterMethod, String.class);
35      }
36  
37       public TextDefinitionParser(String setterMethod, boolean requireCdata)
38      {
39          super(setterMethod, String.class);
40          this.requireCdata = requireCdata;
41      }
42  
43      @Override
44      protected void postProcess(ParserContext context, BeanAssembler assembler, Element element)
45      {        
46          Node node = element.getFirstChild();
47  
48          if(requireCdata && node.getNodeType() != Node.CDATA_SECTION_NODE)
49          {
50              node = node.getNextSibling();
51              if(node == null)
52              {
53                   throw new IllegalArgumentException("No CDATA node found in " + element.getNodeName());
54              }
55              else if(node.getNodeType() != Node.CDATA_SECTION_NODE)
56              {
57                   throw new IllegalArgumentException("Sibling node is not a CDATA section, but one should be defined. Elements is " + element.getNodeName());
58              }
59          }
60          if (node != null)
61          {
62              String value = node.getNodeValue();
63              if (!StringUtils.isBlank(value))
64              {
65                  assembler.getTarget().getPropertyValues().addPropertyValue(setterMethod, value);
66              }
67          }
68      }
69  }