Call a Java Method from a *.jar file in DataWeave

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.

  1. Open Anypoint Studio 
  2. In the navigation bar, click on the Install Artifact in local repository icon
  3. In the Install file into local repository window
    1. Click on Browse and select the *.jar file that you want to add to the project
    2. Fill in the Group ID (e.g. com.mulesoft)
    3. Fill in the Version (e.g. 1.5)
    4. Click on Install
  1. 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.

  1. In the Package Explorer, open the pom.xml file
  2. Scroll down and find the <dependencies> node.
  3. 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>
  1. 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.

  1. Click on the Transform Message component in the project.
  2. 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:

  1. Next, in the script, you can now call the Java method. Add the following below.
{
	a: "1",
	b: helloWho("Max")
}
  1. 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: