Nav
You are viewing an older version of this topic. To go to a different version, use the version menu at the upper-right. +

Contributing Functions with Mule SDK

DataWeave is the main expression language in Mule 4, and the Mule SDK is also aligned with that view. This allows you to contribute functions to DataWeave from your module’s code in a similar fashion that you code a Mule Operation. Using custom functions allows you to reuse code in a new way, providing extra functionality in a single Module with very little overhead regarding how they are declared compared to a Mule operation.

Declaring a Function

At Extension level, you can use the @ExpressionFunctions annotation to reference the classes that contain the public methods representing the DataWeave functions. This method’s code is executed directly from DataWeave scripts using it name as identifier:


         
      
1
2
3
4
5
@Extension(name = "Docs")
@ExpressionFunctions(DocsFunction.class)
public class DocsModule {

}

In the DocsFunction class, this example defines the following method:


         
      
1
2
3
4
5
6
7
8
public Object xpath(@Optional(defaultValue = PAYLOAD) InputStream item,
                    String expression){
    try {
      return xPathFactory.newXPath().evaluate(expression, documentBuilder.parse(item));
    } catch (Exception e) {
      return null;
    }
  }

This xpath function can now be used from inside a DataWeave script, referencing it inside our Module’s namespace.

The next example reads XML and sets an XPath filter using the new xpath function:


         
      
1
2
3
4
<flow name="xpathFunctionUsingPayloadAsDefault">
  <file:read path="files/bookstore.xml"/>
  <set-payload value="#[Docs::xpath("/bookstore/book[price>35]/title")]"/>
</flow>

Restrictions: Config-less and Connection-less

By definition, functions are not allowed to depend on or receive a particular Configuration or Connection.

We use cookies to make interactions with our websites and services easy and meaningful, to better understand how they are used and to tailor advertising. You can read more and make your cookie choices here. By continuing to use this site you are giving us your consent to do this.

+