Replacing standard Mule Transformer with a custom implementation

18 Feb

Although there is a lot of documentation about Mule ESB the issue in this post still took me some time to get it right. In this post I give a complete example of how I replaced standard Mule functionality (a transformer in this case) with my own implementation. My issue started with this question which I posted at the Mule Forum without any response so far. This made me look for a solution myself, which is one of the benefits of open source; it offers you the opportunity to do so.
I soon realized that the behavior I want could be quite easily be implemented by a small change in the MessagePropertiesTransformer. The original code (I am using Mule CE version 3.2.1) was like this:

protected void addProperties(MuleMessage message)
{
   ...
   final String key = entry.getKey();

   Object value= entry.getValue();
   Object realValue = value;

   //Enable expression support for property values
   if (muleContext.getExpressionManager().isExpression(value.toString()))
   {
     realValue = muleContext.getExpressionManager().evaluate(value.toString(), message);
   }
   ...

What we see here is a piece of the addProperties method of the MessagePropertiesTransformer. The code checks if the supplied value of an added property is an expression and if so it resolves the expression to the ‘realValue’.
The way I modified it:

protected void addProperties(MuleMessage message)
{
  ...
  final String key = entry.getKey();

  Object value= entry.getValue();
  Object realValue = value;

  // Modified to be able to execute expression in expressions :-)
  while (muleContext.getExpressionManager().isExpression(realValue.toString())){
     realValue = muleContext.getExpressionManager().evaluate(realValue.toString(), message);
  }
  ...             

As you can see I am iterating over the realValue till it is no longer an expression anymore. With this line of code I can get my wanted behavior: Supplying an expression that resolves to an expression that resolves to a real value.

So far for the easy part. Now I wanted to use my modified transformer instead of the standard one if I use a construction like:

<message-properties-transformer scope="invocation">
  <add-message-property key="field1" value="#[xpath:#[header:INVOCATION:my.attribute.1]]"/>
</message-properties-transformer>

The way I solved it was by adding my own namespace in the Mule configuration. Although it is described here I think it is handy to supply a complete example here:

  • Define the schema for your element
  • In my case it was simple since I didn’t change any at this level, so I just copied the existing element in my own schema file which I saved as ‘my-schema.xsd’ in the META-INF directory of my project:

    <?xml version="1.0" encoding="UTF-8"?>
    <xsd:schema xmlns="http://www.pascalalma.net/schema/core" 
                xmlns:xsd="http://www.w3.org/2001/XMLSchema" 
                targetNamespace="http://www.pascalalma.net/schema/core"        
                xmlns:mule="http://www.mulesoft.org/schema/mule/core"                      
                elementFormDefault="qualified" attributeFormDefault="unqualified">
      <xsd:import namespace="http://www.mulesoft.org/schema/mule/core" schemaLocation="http://www.mulesoft.org/schema/mule/core/3.2/mule.xsd"/>
      <xsd:annotation>
        <xsd:documentation>My Mule Extension.</xsd:documentation>
      </xsd:annotation>
      <!-- My Transformer definition -->
      <xsd:element name="message-properties-transformer" type="mule:messagePropertiesTransformerType"
                     substitutionGroup="mule:abstract-transformer">
        <xsd:annotation>
          <xsd:documentation>
            A transformer that can add, delete or rename message properties.
          </xsd:documentation>
        </xsd:annotation>
      </xsd:element>
    </xsd:schema>
    

    Just make sure you prefix the type and substitutionGroup you refer to in your XSD because you will get errors about unknown XML elements otherwise.

  • Write the Namespace Handler
  • In this case it is almost a copy of the existing NamespaceHandler for the transformer:

    package net.pascalalma.mule.config;
    
    import net.pascalalma.mule.config.spring.parsers.specific.MessagePropertiesTransformerDefinitionParser;
    import org.mule.config.spring.handlers.AbstractMuleNamespaceHandler;
    
    /**
     *
     * @author pascal
     */
    public class MyNamespaceHandler extends AbstractMuleNamespaceHandler {
    
        @Override
        public void init() {
            registerBeanDefinitionParser("message-properties-transformer", new MessagePropertiesTransformerDefinitionParser());
        }
    }
    
    
  • Write the Definition Parser
  • It becomes boring but this is also largely a copy of the existing MessagePropertiesTransformerDefinitionParser:

    package net.pascalalma.mule.config.spring.parsers.specific;
    
    import net.pascalalma.mule.transformer.MessagePropertiesTransformer;
    import org.mule.config.spring.parsers.specific.MessageProcessorDefinitionParser;
    
    /**
     *
     * @author pascal
     */
    public class MessagePropertiesTransformerDefinitionParser extends MessageProcessorDefinitionParser
    {
        public MessagePropertiesTransformerDefinitionParser()
        {
            super(MessagePropertiesTransformer.class);
            addAlias("scope", "scopeName");
        }
        
    }
    

    Just make sure you import the correct MessagePropertiesTransformer here!

  • Set the Spring handler mapping
  • Add the file ‘spring.handlers’ to the project in the META-INF directory if it doesn’t exist already. In the file put the following:

    http\://www.pascalalma.net/schema/core=net.pascalalma.mule.config.MyNamespaceHandler
    
  • Set the local schema mapping
  • Add the file ‘spring.schemas’ to the project in the META-INF directory if it doesn’t exist already. In the file put the following:

    http\://www.pascalalma.net/schema/core/1.0/my-schema.xsd=META-INF/my-schema.xsd
    
  • Modify the Mule config to include the custom namespace
  • I added the following parts to my Mule config. First add the schema declaration :

    xmlns:pan="http://www.pascalalma.net/schema/core"
         ...
          xsi:schemaLocation="http://www.pascalalma.net/schema/core http://www.pascalalma.net/schema/core/1.0/my-schema.xsd 	
    

    Next I use this namespace prefix with my transformer like this:

    <pan:message-properties-transformer scope="invocation">
      <add-message-property key="field1" value="#[header:INVOCATION:id.attribute.1]"/>
    </pan:message-properties-transformer>
    

As you can see I changed the content of field1 so it matches my needs. What is happening now is that the expression ‘#[header:INVOCATION:id.attribute.1]‘ resolves to a XPath expression like ‘#[xpath:/msg/header/ID]‘ and this resolves to a real value that I can use in the remainder of the flow.

2 Responses to “Replacing standard Mule Transformer with a custom implementation”

  1. Jason 01/03/2013 at 20:13 #

    The problem is that the MessagePropertiesTransformer uses the evaluate method of ExpressionManager instead of the parse method. As you found out, the evaluate method will only handle a single expression, whereas parse handles multiples. You may have been able to simplify your code by calling parse.

    I ran into this problem myself recently and the easiest solution was simply to wrap my expressions in #[string:]. In your case that would be:

    #[string:#[xpath:#[header:INVOCATION:my.attribute.1]]]

    That’s what worked in my case anyway. I appreciate the nice writeup on registering your own elements. That will be useful to me real soon.

    Of course both the evaluate and parse methods that take a MuleMessage are now deprecated, which is causing me other problems. They want us to use MuleEvents instead of MuleMessages, which isn’t exactly compatible with overriding any of their abstract transformers in the expected manner. And while they deprecated those methods, MessagePropertiesTransformer still uses a deprecated form of evaluate of course.

    • Pascal Alma 02/03/2013 at 12:20 #

      Hi Jason,

      Thanks for pointing out the parse() method. I didn’t realize this did exactly what I wanted to achieve. And I think you are right about the #[string:...] solution. I realized when I was writing the post that there made be simpler solution for this specific issue but I thought it might be handy anyway to show the way to implement your own tags and functionality.

Comments are closed.

Follow

Get every new post delivered to your Inbox.

Join 94 other followers

%d bloggers like this: