View Javadoc

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