Overview
Reuse is a major tenant of the MuleSoft Anypoint Platform. Instead of being a black box where developers don’t know what the code is doing under the covers, they can reuse code or leverage their own code within a Mule application.
Sometimes this code can be sitting in a *.jar file and the developer just wants to call some methods from the Mule app. In this post, I’ll show you how to add the *.jar file to a Mule project and reference it from DataWeave directly.
Pre-Requisites
- Anypoint Studio 7.5.1
- Mule EE 4.3.0
Add *.jar File
Install file into local repository
We’re going to start adding the *.jar file to the local Maven repository. If you have one, you can use it, otherwise, you can use a simple example I uploaded here.
- Open Anypoint Studio
- In the navigation bar, click on the Install Artifact in local repository icon
- In the Install file into local repository window
- Click on Browse and select the *.jar file that you want to add to the project
- Fill in the Group ID (e.g. com.mulesoft)
- Fill in the Version (e.g. 1.5)
- Click on Install
- Optionally if you navigate to your local Maven repo, you can check to see if the *.jar file was added correctly
Configure Mule Project
Modify pom.xml file
In your Mule application, we need to add the *.jar file as a dependency. You can use the example project found here, or leverage your own and follow the steps below.
- In the Package Explorer, open the pom.xml file
- Scroll down and find the <dependencies> node.
- Paste the following XML snippet into the section. If you’re using your own *.jar file, be sure to change the values accordingly to match your artifact.
<dependency>
<groupId>com.dejim</groupId>
<artifactId>HelloMule</artifactId>
<version>1.4</version>
</dependency>
- Save and close the pom.xml file
Configure DataWeave script
Lastly, we just need to configure the DataWeave script to import the method we want to call.
- Click on the Transform Message component in the project.
- After the %dw 2.0 line, paste the following code snippet.
import * from java!com::dejim::HelloMule
If you look at the code from the *.jar file. This corresponds to the class:
- Next, in the script, you can now call the Java method. Add the following below.
{
a: "1",
b: helloWho("Max")
}
- If you click on Preview, it should look like the following screenshot.
Alternatively, you can also change the DataWeave script to look like this where the class and function are included in the script: