View Javadoc

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