Coverage Report - org.mule.config.spring.parsers.AbstractMuleBeanDefinitionParser
 
Classes in this File Line Coverage Branch Coverage Complexity
AbstractMuleBeanDefinitionParser
0%
0/132
0%
0/54
0
 
 1  
 /*
 2  
  * $Id:AbstractMuleBeanDefinitionParser.java 5187 2007-02-16 18:00:42Z rossmason $
 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;
 11  
 
 12  
 import org.mule.api.MuleContext;
 13  
 import org.mule.api.component.Component;
 14  
 import org.mule.api.config.MuleProperties;
 15  
 import org.mule.api.lifecycle.Disposable;
 16  
 import org.mule.api.lifecycle.Initialisable;
 17  
 import org.mule.api.routing.OutboundRouter;
 18  
 import org.mule.api.routing.OutboundRouterCollection;
 19  
 import org.mule.api.source.MessageSource;
 20  
 import org.mule.config.spring.MuleHierarchicalBeanDefinitionParserDelegate;
 21  
 import org.mule.config.spring.parsers.assembly.BeanAssembler;
 22  
 import org.mule.config.spring.parsers.assembly.BeanAssemblerFactory;
 23  
 import org.mule.config.spring.parsers.assembly.DefaultBeanAssemblerFactory;
 24  
 import org.mule.config.spring.parsers.assembly.configuration.ReusablePropertyConfiguration;
 25  
 import org.mule.config.spring.parsers.assembly.configuration.ValueMap;
 26  
 import org.mule.config.spring.parsers.generic.AutoIdUtils;
 27  
 import org.mule.exception.AbstractExceptionListener;
 28  
 import org.mule.util.ClassUtils;
 29  
 import org.mule.util.StringUtils;
 30  
 import org.mule.util.XMLUtils;
 31  
 
 32  
 import java.util.HashSet;
 33  
 import java.util.Iterator;
 34  
 import java.util.LinkedList;
 35  
 import java.util.List;
 36  
 import java.util.Map;
 37  
 import java.util.Set;
 38  
 
 39  
 import org.apache.commons.logging.Log;
 40  
 import org.apache.commons.logging.LogFactory;
 41  
 import org.springframework.beans.factory.BeanDefinitionStoreException;
 42  
 import org.springframework.beans.factory.config.BeanDefinition;
 43  
 import org.springframework.beans.factory.support.AbstractBeanDefinition;
 44  
 import org.springframework.beans.factory.support.BeanDefinitionBuilder;
 45  
 import org.springframework.beans.factory.support.BeanDefinitionRegistry;
 46  
 import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser;
 47  
 import org.springframework.beans.factory.xml.ParserContext;
 48  
 import org.w3c.dom.Attr;
 49  
 import org.w3c.dom.Element;
 50  
 import org.w3c.dom.NamedNodeMap;
 51  
 
 52  
 /**
 53  
  * This parser extends the Spring provided {@link AbstractBeanDefinitionParser} to provide additional features for
 54  
  * consistently customising bean representations for Mule bean definition parsers.  Most custom bean definition parsers
 55  
  * in Mule will use this base class. The following enhancements are made -
 56  
  *
 57  
  * <ol>
 58  
  * <li>A property name which ends with the suffix "-ref" is assumed to be a reference to another bean.
 59  
  * Alternatively, a property can be explicitly registered as a bean reference via registerBeanReference()
 60  
  *
 61  
  * <p>For example,
 62  
  * <code> &lt;bpm:connector bpms-ref=&quot;testBpms&quot;/&gt;</code>
 63  
  * will automatically set a property "bpms" on the connector to reference a bean named "testBpms"
 64  
  * </p></li>
 65  
  *
 66  
  * <li>Attribute mappings can be registered to control how an attribute name in Mule Xml maps to the bean name in the
 67  
  * object being created.
 68  
  *
 69  
  * <p>For example -
 70  
  * <code>addAlias("poolExhaustedAction", "poolExhaustedActionString");</code>
 71  
  * Maps the 'poolExhaustedAction' to the 'poolExhaustedActionString' property on the bean being created.
 72  
  * </p></li>
 73  
  *
 74  
  * <li>Value Mappings can be used to map key value pairs from selection lists in the XML schema to property values on the
 75  
  * bean being created. These are a comma-separated list of key=value pairs.
 76  
  *
 77  
  * <p>For example -
 78  
  * <code>addMapping("action", "NONE=0,ALWAYS_BEGIN=1,BEGIN_OR_JOIN=2,JOIN_IF_POSSIBLE=3");</code>
 79  
  * The first argument is the bean name to set, the second argument is the set of possible key=value pairs
 80  
  * </p></li>
 81  
  *
 82  
  * <li>Provides an automatic way of setting the 'init-method' and 'destroy-method' for this object. This will then automatically
 83  
  * wire the bean into the lifecycle of the Application context.</li>
 84  
  *
 85  
  * <li>The 'singleton' property provides a fixed way to make sure the bean is always a singleton or not.</li>
 86  
  *
 87  
  * <li>Collections will be automatically created and extended if the setter matches "property+s".</li>
 88  
  * </ol>
 89  
  *
 90  
  * <p>Note that this class is not multi-thread safe.  The internal state is reset before each "use"
 91  
  * by {@link #preProcess(org.w3c.dom.Element)} which assumes sequential access.</p>
 92  
  *
 93  
  * @see  AbstractBeanDefinitionParser
 94  
  */
 95  
 public abstract class AbstractMuleBeanDefinitionParser extends AbstractBeanDefinitionParser
 96  
     implements MuleDefinitionParser
 97  
 {
 98  
 
 99  
     public static final String ROOT_ELEMENT = "mule";
 100  
     public static final String ATTRIBUTE_ID = "id";
 101  
     public static final String ATTRIBUTE_NAME = "name";
 102  
     public static final String ATTRIBUTE_CLASS = "class";
 103  
     public static final String ATTRIBUTE_REF = "ref";
 104  
     public static final String ATTRIBUTE_REFS = "refs";
 105  
     public static final String ATTRIBUTE_REF_SUFFIX = "-" + ATTRIBUTE_REF;
 106  
     public static final String ATTRIBUTE_REFS_SUFFIX = "-" + ATTRIBUTE_REFS;
 107  
 
 108  
     /**
 109  
      * logger used by this class
 110  
      */
 111  0
     protected transient Log logger = LogFactory.getLog(getClass());
 112  
 
 113  0
     private BeanAssemblerFactory beanAssemblerFactory = new DefaultBeanAssemblerFactory();
 114  0
     protected ReusablePropertyConfiguration beanPropertyConfiguration = new ReusablePropertyConfiguration();
 115  
     private ParserContext parserContext;
 116  
     private BeanDefinitionRegistry registry;
 117  0
     private LinkedList preProcessors = new LinkedList();
 118  0
     private List postProcessors = new LinkedList();
 119  0
     private Set beanAttributes = new HashSet();
 120  
     // By default Mule objects are not singletons
 121  0
     protected boolean singleton = false;
 122  
 
 123  
     /** Allow the bean class to be set explicitly via the "class" attribute. */
 124  0
     private boolean allowClassAttribute = true;
 125  0
     private Class classConstraint = null;
 126  
     
 127  
     private String deprecationWarning;
 128  
 
 129  
     public AbstractMuleBeanDefinitionParser()
 130  0
     {
 131  0
         addIgnored(ATTRIBUTE_ID);
 132  0
         addBeanFlag(MuleHierarchicalBeanDefinitionParserDelegate.MULE_FORCE_RECURSE);
 133  0
     }
 134  
 
 135  
     public MuleDefinitionParserConfiguration addReference(String propertyName)
 136  
     {
 137  0
         beanPropertyConfiguration.addReference(propertyName);
 138  0
         return this;
 139  
     }
 140  
 
 141  
     public MuleDefinitionParserConfiguration addMapping(String propertyName, Map mappings)
 142  
     {
 143  0
         beanPropertyConfiguration.addMapping(propertyName, mappings);
 144  0
         return this;
 145  
     }
 146  
 
 147  
     public MuleDefinitionParserConfiguration addMapping(String propertyName, String mappings)
 148  
     {
 149  0
         beanPropertyConfiguration.addMapping(propertyName, mappings);
 150  0
         return this;
 151  
     }
 152  
 
 153  
     public MuleDefinitionParserConfiguration addMapping(String propertyName, ValueMap mappings)
 154  
     {
 155  0
         beanPropertyConfiguration.addMapping(propertyName, mappings);
 156  0
         return this;
 157  
     }
 158  
 
 159  
     /**
 160  
      * @param alias The attribute name
 161  
      * @param propertyName The bean property name
 162  
      * @return This instance, allowing chaining during use, avoiding subclasses
 163  
      */
 164  
     public MuleDefinitionParserConfiguration addAlias(String alias, String propertyName)
 165  
     {
 166  0
         beanPropertyConfiguration.addAlias(alias, propertyName);
 167  0
         return this;
 168  
     }
 169  
 
 170  
     /**
 171  
      * @param propertyName Property that is a collection
 172  
      * @return This instance, allowing chaining during use, avoiding subclasses
 173  
      */
 174  
     public MuleDefinitionParserConfiguration addCollection(String propertyName)
 175  
     {
 176  0
         beanPropertyConfiguration.addCollection(propertyName);
 177  0
         return this;
 178  
     }
 179  
 
 180  
     /**
 181  
      * @param propertyName Property that is to be ignored
 182  
      * @return This instance, allowing chaining during use, avoiding subclasses
 183  
      */
 184  
     public MuleDefinitionParserConfiguration addIgnored(String propertyName)
 185  
     {
 186  0
         beanPropertyConfiguration.addIgnored(propertyName);
 187  0
         return this;
 188  
     }
 189  
 
 190  
     public MuleDefinitionParserConfiguration removeIgnored(String propertyName)
 191  
     {
 192  0
         beanPropertyConfiguration.removeIgnored(propertyName);
 193  0
         return this;
 194  
     }
 195  
 
 196  
     public MuleDefinitionParserConfiguration setIgnoredDefault(boolean ignoreAll)
 197  
     {
 198  0
         beanPropertyConfiguration.setIgnoredDefault(ignoreAll);
 199  0
         return this;
 200  
     }
 201  
 
 202  
     protected void processProperty(Attr attribute, BeanAssembler assembler)
 203  
     {
 204  0
         assembler.extendBean(attribute);
 205  0
     }
 206  
 
 207  
     /**
 208  
      * Hook method that derived classes can implement to inspect/change a
 209  
      * bean definition after parsing is complete.
 210  
      *
 211  
      * @param assembler the parsed (and probably totally defined) bean definition being built
 212  
      * @param element   the XML element that was the source of the bean definition's metadata
 213  
      */
 214  
     protected void postProcess(ParserContext context, BeanAssembler assembler, Element element)
 215  
     {
 216  0
         element.setAttribute(ATTRIBUTE_NAME, getBeanName(element));
 217  0
         for (Iterator attributes = beanAttributes.iterator(); attributes.hasNext();)
 218  
         {
 219  0
             assembler.setBeanFlag((String) attributes.next());
 220  
         }
 221  0
         for (Iterator processes = postProcessors.iterator(); processes.hasNext();)
 222  
         {
 223  0
             ((PostProcessor) processes.next()).postProcess(context, assembler, element);
 224  
         }
 225  0
     }
 226  
 
 227  
     /**
 228  
      * Hook method that derived classes can implement to modify internal state before processing.
 229  
      *
 230  
      * Here we make sure that the internal property configuration state is reset to the
 231  
      * initial configuration for each element (it may be modified by the BeanAssembler)
 232  
      * and that other mutable instance variables are cleared.
 233  
      */
 234  
     protected void preProcess(Element element)
 235  
     {
 236  0
         parserContext = null;
 237  0
         registry = null;
 238  0
         beanPropertyConfiguration.reset();
 239  0
         Iterator processes = preProcessors.iterator();
 240  0
         while (processes.hasNext())
 241  
         {
 242  0
             ((PreProcessor) processes.next()).preProcess(beanPropertyConfiguration, element);
 243  
         }
 244  0
     }
 245  
 
 246  
     /**
 247  
      * Creates a {@link BeanDefinitionBuilder} instance for the
 248  
      * {@link #getBeanClass bean Class} and passes it to the
 249  
      * {@link #doParse} strategy method.
 250  
      *
 251  
      * @param element       the element that is to be parsed into a single BeanDefinition
 252  
      * @param parserContext the object encapsulating the current state of the parsing process
 253  
      * @return the BeanDefinition resulting from the parsing of the supplied {@link Element}
 254  
      * @throws IllegalStateException if the bean {@link Class} returned from
 255  
      *                               {@link #getBeanClass(org.w3c.dom.Element)} is <code>null</code>
 256  
      * @see #doParse
 257  
      */
 258  
     @Override
 259  
     protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext)
 260  
     {
 261  0
         preProcess(element);
 262  0
         setParserContext(parserContext);
 263  0
         setRegistry(parserContext.getRegistry());
 264  0
         checkElementNameUnique(element);
 265  0
         Class beanClass = getClassInternal(element);
 266  0
         BeanDefinitionBuilder builder = createBeanDefinitionBuilder(element, beanClass);
 267  0
         builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
 268  0
         builder.setScope(isSingleton() ? BeanDefinition.SCOPE_SINGLETON : BeanDefinition.SCOPE_PROTOTYPE);
 269  
 
 270  
         // Marker for MULE-4813
 271  
         // We don't want lifcycle for the following from spring
 272  0
         if (!Component.class.isAssignableFrom(beanClass) && !MessageSource.class.isAssignableFrom(beanClass)
 273  
             && !OutboundRouterCollection.class.isAssignableFrom(beanClass)
 274  
             && !OutboundRouter.class.isAssignableFrom(beanClass)
 275  
             && !AbstractExceptionListener.class.isAssignableFrom(beanClass))
 276  
         {
 277  0
             if (Initialisable.class.isAssignableFrom(beanClass))
 278  
             {
 279  0
                 builder.setInitMethodName(Initialisable.PHASE_NAME);
 280  
             }
 281  
 
 282  0
             if (Disposable.class.isAssignableFrom(beanClass))
 283  
             {
 284  0
                 builder.setDestroyMethodName(Disposable.PHASE_NAME);
 285  
             }
 286  
         }
 287  
 
 288  0
         if (parserContext.isNested())
 289  
         {
 290  
             // Inner bean definition must receive same singleton status as containing bean.
 291  0
             builder.setScope(parserContext.getContainingBeanDefinition().isSingleton() 
 292  
                 ? BeanDefinition.SCOPE_SINGLETON : BeanDefinition.SCOPE_PROTOTYPE);
 293  
         }
 294  
 
 295  0
         doParse(element, parserContext, builder);
 296  0
         return builder.getBeanDefinition();
 297  
     }
 298  
 
 299  
     protected void setRegistry(BeanDefinitionRegistry registry)
 300  
     {
 301  0
         this.registry = registry;
 302  0
     }
 303  
 
 304  
     protected BeanDefinitionRegistry getRegistry()
 305  
     {
 306  0
         if (null == registry)
 307  
         {
 308  0
             throw new IllegalStateException("Set the registry from within doParse");
 309  
         }
 310  0
         return registry;
 311  
     }
 312  
 
 313  
     protected void checkElementNameUnique(Element element)
 314  
     {
 315  0
         if (null != element.getAttributeNode(ATTRIBUTE_NAME))
 316  
         {
 317  0
             String name = element.getAttribute(ATTRIBUTE_NAME);
 318  0
             if (getRegistry().containsBeanDefinition(name))
 319  
             {
 320  0
                 throw new IllegalArgumentException("A service named " + name + " already exists.");
 321  
             }
 322  
         }
 323  0
     }
 324  
 
 325  
     protected BeanDefinitionBuilder createBeanDefinitionBuilder(Element element, Class beanClass)
 326  
     {
 327  0
         BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(beanClass);
 328  
         // If a constructor with a single MuleContext argument is available then use it.
 329  0
         if (ClassUtils.getConstructor(beanClass, new Class[]{MuleContext.class}, true) != null)
 330  
         {
 331  0
             builder.addConstructorArgReference(MuleProperties.OBJECT_MULE_CONTEXT);
 332  
         }
 333  0
         return builder;
 334  
     }
 335  
 
 336  
     protected Class getClassInternal(Element element)
 337  
     {
 338  0
         Class beanClass = null;
 339  0
         if (isAllowClassAttribute())
 340  
         {
 341  0
             beanClass = getBeanClassFromAttribute(element);
 342  
         }
 343  0
         if (beanClass == null)
 344  
         {
 345  0
             beanClass = getBeanClass(element);
 346  
         }
 347  0
         if (null != beanClass && null != classConstraint && !classConstraint.isAssignableFrom(beanClass))
 348  
         {
 349  0
             throw new IllegalStateException(beanClass + " not a subclass of " + classConstraint +
 350  
                     " for " + XMLUtils.elementToString(element));
 351  
         }
 352  0
         if (null == beanClass)
 353  
         {
 354  0
             throw new IllegalStateException("No class for element " + XMLUtils.elementToString(element));
 355  
         }
 356  0
         return beanClass;
 357  
     }
 358  
 
 359  
     /**
 360  
      * Determine the bean class corresponding to the supplied {@link Element} based on an
 361  
      * explicit "class" attribute.
 362  
      *
 363  
      * @param element the <code>Element</code> that is being parsed
 364  
      * @return the {@link Class} of the bean that is being defined via parsing the supplied <code>Element</code>
 365  
      *         (must <b>not</b> be <code>null</code>)
 366  
      * @see #parseInternal(org.w3c.dom.Element,ParserContext)
 367  
      */
 368  
     protected Class<?> getBeanClassFromAttribute(Element element)
 369  
     {
 370  0
         String att = beanPropertyConfiguration.getAttributeAlias(ATTRIBUTE_CLASS);
 371  0
         String className = element.getAttribute(att);
 372  0
         Class<?> clazz = null;
 373  0
         if (StringUtils.isNotBlank(className))
 374  
         {
 375  
             try
 376  
             {
 377  0
                 element.removeAttribute(att);
 378  0
                 clazz = ClassUtils.loadClass(className, getClass());
 379  
             }
 380  0
             catch (ClassNotFoundException e)
 381  
             {
 382  0
                 logger.error("could not load class: " + className, e);
 383  0
             }
 384  
         }
 385  0
         return clazz;
 386  
     }
 387  
 
 388  
     /**
 389  
      * Determine the bean class corresponding to the supplied {@link Element}.
 390  
      *
 391  
      * @param element the <code>Element</code> that is being parsed
 392  
      * @return the {@link Class} of the bean that is being defined via parsing the supplied <code>Element</code>
 393  
      *         (must <b>not</b> be <code>null</code>)
 394  
      * @see #parseInternal(org.w3c.dom.Element,ParserContext)
 395  
      */
 396  
     protected abstract Class<?> getBeanClass(Element element);
 397  
 
 398  
     /**
 399  
      * Parse the supplied {@link Element} and populate the supplied
 400  
      * {@link BeanDefinitionBuilder} as required.
 401  
      * <p>The default implementation delegates to the <code>doParse</code>
 402  
      * version without ParserContext argument.
 403  
      *
 404  
      * @param element       the XML element being parsed
 405  
      * @param parserContext the object encapsulating the current state of the parsing process
 406  
      * @param builder       used to define the <code>BeanDefinition</code>
 407  
      */
 408  
     protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder)
 409  
     {
 410  0
         if (deprecationWarning != null && logger.isWarnEnabled())
 411  
         {
 412  0
             logger.warn("Schema warning: Use of element <" + element.getLocalName() + "> is deprecated.  " + deprecationWarning);
 413  
         }
 414  
         
 415  0
         BeanAssembler assembler = getBeanAssembler(element, builder);
 416  0
         NamedNodeMap attributes = element.getAttributes();
 417  0
         for (int x = 0; x < attributes.getLength(); x++)
 418  
         {
 419  0
             Attr attribute = (Attr) attributes.item(x);
 420  0
             processProperty(attribute, assembler);
 421  
         }
 422  0
         postProcess(getParserContext(), assembler, element);
 423  0
     }
 424  
 
 425  
     @Override
 426  
     protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException
 427  
     {
 428  0
         return getBeanName(element);
 429  
     }
 430  
 
 431  
     protected boolean isSingleton()
 432  
     {
 433  0
         return singleton;
 434  
     }
 435  
 
 436  
     /**
 437  
      * Restricted use - does not include a target.
 438  
      * If possible, use {@link org.mule.config.spring.parsers.AbstractHierarchicalDefinitionParser#getBeanAssembler(org.w3c.dom.Element, org.springframework.beans.factory.support.BeanDefinitionBuilder)}
 439  
      *
 440  
      * @param bean The bean being constructed
 441  
      * @return An assembler that automates Mule-specific logic for bean construction
 442  
      */
 443  
     protected BeanAssembler getBeanAssembler(Element element, BeanDefinitionBuilder bean)
 444  
     {
 445  0
         return getBeanAssemblerFactory().newBeanAssembler(
 446  
                 beanPropertyConfiguration, bean, beanPropertyConfiguration, null);
 447  
     }
 448  
 
 449  
     protected boolean isAllowClassAttribute()
 450  
     {
 451  0
         return allowClassAttribute;
 452  
     }
 453  
 
 454  
     protected void setAllowClassAttribute(boolean allowClassAttribute)
 455  
     {
 456  0
         this.allowClassAttribute = allowClassAttribute;
 457  0
     }
 458  
 
 459  
     protected Class getClassConstraint()
 460  
     {
 461  0
         return classConstraint;
 462  
     }
 463  
 
 464  
     protected void setClassConstraint(Class classConstraint)
 465  
     {
 466  0
         this.classConstraint = classConstraint;
 467  0
     }
 468  
 
 469  
     protected ParserContext getParserContext()
 470  
     {
 471  0
         return parserContext;
 472  
     }
 473  
 
 474  
     protected void setParserContext(ParserContext parserContext)
 475  
     {
 476  0
         this.parserContext = parserContext;
 477  0
     }
 478  
 
 479  
     /**
 480  
      * @param element The element to test
 481  
      * @return true if the element's parent is <mule> or similar
 482  
      */
 483  
     protected boolean isTopLevel(Element element)
 484  
     {
 485  0
         return element.getParentNode().getLocalName().equals(ROOT_ELEMENT);
 486  
     }
 487  
 
 488  
     public AbstractBeanDefinition muleParse(Element element, ParserContext parserContext)
 489  
     {
 490  0
         return parseInternal(element, parserContext);
 491  
     }
 492  
 
 493  
     public MuleDefinitionParserConfiguration registerPreProcessor(PreProcessor preProcessor)
 494  
     {
 495  0
         preProcessors.addFirst(preProcessor);
 496  0
         return this;
 497  
     }
 498  
 
 499  
     public MuleDefinitionParserConfiguration registerPostProcessor(PostProcessor postProcessor)
 500  
     {
 501  0
         postProcessors.add(postProcessor);
 502  0
         return this;
 503  
     }
 504  
 
 505  
     public BeanAssemblerFactory getBeanAssemblerFactory()
 506  
     {
 507  0
         return beanAssemblerFactory;
 508  
     }
 509  
 
 510  
     public void setBeanAssemblerFactory(BeanAssemblerFactory beanAssemblerFactory)
 511  
     {
 512  0
         this.beanAssemblerFactory = beanAssemblerFactory;
 513  0
     }
 514  
 
 515  
     public String getBeanName(Element element)
 516  
     {
 517  0
         return AutoIdUtils.getUniqueName(element, "mule-bean");
 518  
     }
 519  
 
 520  
     public MuleDefinitionParserConfiguration addBeanFlag(String flag)
 521  
     {
 522  0
         beanAttributes.add(flag);
 523  0
         return this;
 524  
     }
 525  
 
 526  
     public void setDeprecationWarning(String deprecationWarning)
 527  
     {
 528  0
         this.deprecationWarning = deprecationWarning;
 529  0
     }
 530  
 }