Mule 4 introduces DataWeave 2.0 as the default expression language replacing Mule Expression Language (MEL). DataWeave 2.0 is tightly integrated with the Mule 4 runtime engine, which runs the scripts and expressions in your Mule application.
Since Dataweave 2.0 is default expression language for Mule 4, Dataweave can use almost all place within your Mule application. So, In some use-case Dataweave needs to call java method or instantiate java class to execute java complex business logic.
In my previous blog I explained usage of java within Mulesoft flow. In this blog I am explaining usage of java within Dataweave 2.0.
There are 2 ways we can use java within Dataweave code
- Calling java method
- Instantiate Java class
Here is Dataweave code
In dataweave this method can use multiple way
Import only method instead of the whole class:
%dw 2.0
import java!com::vanrish::AppUtils:: encode
output application/json
---
{
encode:encode("mystring" as String)
}
import and call it in a single line:
%dw 2.0
output application/json
---
{
encode: java!com::vanrish::AppUtils:: encode ("mystring" as String)
}
2. Instantiate Java class – Dataweave allows to instantiate a new object of any java class but you can’t call its instance method through dataweave. You can refer it as variables.
%dw 2.0
import java!com::vanrish::AppUtils
output application/json
---
{
value: AppUtils::new().data
}
AppUtils.java
package com.vanrish;
import sun.misc.BASE64Encoder;
/**
* @author rajnish
*/
public class AppUtils{
public static final BASE64Encoder encoder = new BASE64Encoder();
private String data;
/**
* @param plainString
* @return
*/
public static String encode(String plainString)
{
String encodedString = encoder.encodeBuffer(plainString.getBytes());
return encodedString;
}
/**
* @param dataStr
* @return
*/
public String getData(String dataStr)
{
data = dataStr+" : test";
return data;
}
}
Rajnish Kumar is CTO of Vanrish Technology with Over 25 years experience in different industries and technology. He is very passionate about innovation and latest technology like APIs, IOT (Internet Of Things), Artificial Intelligence (AI) ecosystem and Cybersecurity. He present his idea in different platforms and help customer to their digital transformation journey.