How to invoke Java methods in Mule 4 – step by step tutorial

Overview

Sometimes the operations and tools available in Anypoint Platform are not enough for your objectives and you have the need to write custom code in Java.
This tutorial will show how you can invoke Java methods on mule 4.

The Java module in mule 4 has four available operations:

  • New – create a new instance of a class
  • Invoke – invoke methods on a class
  • Invoke Static – invoke static methods on a class
  • Validate Type – validate the type of an object

Having that in mind we’ve decided to divide it in two parts:

  1. On the first part we will demonstrate how to use the New and Invoke Java operations.
  2. On the second part we will display the Invoke Static and Validate Type Java operations.

Dependencies:

  • Anypoint Studio with version 7.4.2
  • Runtime Mule Server 4.2.2 EE.

First part – New and Invoke Java operations

Steps

1 – To test these operations we will start by creating a new mule project

  • Project Name – Java-Test

2 – Add a new java class to our project. For this tutorial we used a simple class with 2 methods

  • Package – com.toldone.api
  • Name – Plus5

2.1 – This class has:

  • an int field called initValue
  • a default constructor without parameters
  • two public methods
    • sum
    • setInitValue.

3 – Add a HTTP Listener to our canvas to create a new flow

  • Path – /test1

4 – Add a new instance of Class Plus5. For that we type java on the mule palette.

Then we drag the new operation to our flow in front of the HTTP Listener.

  • Display Name – Plus5
  • Class – com.toldone.api.Plus5
  • Constructor – Plus5()

For the Class we set fully qualified path name

We don’t set any Args since we are using the default constructor.

For the constructor we set the default constructor.

4.1 – Go to Advanced and set the Target Variable to plus5

5 – Add a Logger to the flow in front of the New operation.

Message – New instance of Plus5 is: #[vars.plus5]

6 – Now we want to set the value of field initValue. We will use the java invoke operation with the setInitValue method for that.

Type java on the mule palette. Drag an Invoke operation from the Mule Palette and put in front of the Logger.

  • Display Name – setInitValue
  • Instance – #[vars.plus5]
  • Args  – #[{value:1}]
  • Class – com.toldone.api.Plus5
  • Method – setInitValue(int)

In Instance field we set the variable where is saved the instance of the class.

For Args we set the value for our arguments. We want to set initValue as 1 so we set – #[{value:1}].

For the class we set fully qualified path name.

In Method we set the method we are invoking and the input type(s).

7 – On this step we want to invoke the method sum to add the value 5 to our init value.

Drag an Invoke operation and put it in front of the Invoke setInitValue operation

  • Display Name – sum
  • Instance – #[vars.plus5]
  • Class – com.toldone.api.Plus5
  • Method- sum()

7.1 – Go to Advanced and set the target variable – result

8 – Add a new Logger in front of the sum invoke operation.

  • Message – The result of sum was: #[vars.result]

9 – Maven compiler plugin must be configured in the pom.xml to compile Java classes with the -parameters flag:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <compilerArgs>
            <arg>-parameters</arg>
        </compilerArgs>
    </configuration>
</plugin>

Add this plugin to pom.xml if it’s not already configured (The version could be different from this one).

10 – Run the project and invoke it with a rest client(Postman/Advanced Rest Client/other)

  • GET request to – http://localhost:8081/test1
  • Validate in the logs if you have no errors, and 2 messages similar to the following:
    • INFO 2020-05-20 18:13:02,653 [[MuleRuntime].cpuLight.01: [java-test].java-testFlow.CPU_LITE @66bf842e] [event: 275d64f0-9abd-11ea-afb8-26ee9abecb9d] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: New instance of Plus5 is: com.toldone.api.Plus5@2e8d4c42
    • INFO 2020-05-20 18:13:02,700 [[MuleRuntime].io.06: [java-test].java-testFlow.BLOCKING @b22aec5] [event: 275d64f0-9abd-11ea-afb8-26ee9abecb9d] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: The result of sum was: 6

Second part – Invoke Static and Validate Type Java operations

Steps

1 – Create a new class with static methods. We created a simple Class with only one static method.

  • create the new class inside the same package as before – com.toldone.api
  • Name – Utils

  • This class has a single static method called concatName that joins the first and last name on a single String.

2 – Add a new mule configuration file called java-test2. Add a HTTP Listener to create a new flow..

  • Path – /test2

3 – Type java on the mule palette. Drag an Invoke static operation to the flow in front of the listener

  • Display Name – concatName
  • Args – #[{ firstName:”John”, lastName:”Doe”}]
  • Class – com.toldone.api.Utils
  • Method – concatName(String, String)

For the Args we want to set the values for the first and last name.

For the class we set the fully qualified name for our class.

3.1 – On Advanced set the value of Target Variable – fullName

4 – Add a Logger in front of the concatName Invoke static operation

  • Message – Full name is: #[vars.fullName]

5 – Run the project and invoke it with a rest client

  • GET request to – http://localhost:8081/test2
  • Validate in the logs if you have no errors, and a message similar to the following:
    • INFO 2020-05-20 20:41:36,091 [[MuleRuntime].io.06: [java-test].java-test2Flow.BLOCKING @67350700] [event: ea62d751-9ad1-11ea-a82b-26ee9abecb9d] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Full name is: John Doe

6 – Create two simple java classes. One should extend the other.

  • create class MobilePhone
  • create class Iphone that should extend Mobile Phone

7 – Add a new HTTP Listener to the canvas to create a new flow

  • Path – /test3

8 – Then we add a new instance of MobilePhone. Type java on the mule palette.

Drag the New operation to our canvas in front of the HTTP Listener

  • Display Name – MobilePhone
  • Class – com.toldone.api.MobilePhone
  • Constructor – MobilePhone()

We don’t set any Args since we are using the default constructor

For the constructor we set the default constructor

8.1 – Go to advanced and set the Target Variable – mobilePhone

9 – We now want to validate if our instance is of type MobilePhone. Type java on the mule palette.

Drag a Validate type operation to our flow in front of the MobilePhone New Operation

  • Display Name – MobilePhone
  • Class – com.toldone.api.MobilePhone
  • Instance – vars.mobilePhone

10 – Add a logger in front of the Validate type operation

  • Message – Type is MobilePhone

11 – Run the project and invoke it with a rest client

  • GET request to – http://localhost:8081/test3
  • Validate in the logs if you have no errors, and a message similar to the following:
    • INFO 2020-05-20 21:13:27,285 [[MuleRuntime].cpuLight.02: [java-test].java-test2Flow1.CPU_LITE @4100475] [event: 5b1b0e00-9ad6-11ea-9358-26ee9abecb9d] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Type is MobilePhone

12 – Change the New Operation to point to the Iphone class

  • Display Name – Iphone
  • Class: com.toldone.api.Iphone
  • Constructor:Iphone()

13 – Run the project and invoke it with a rest client.

  • GET request to – http://localhost:8081/test3
  • Validate in the logs if you have no errors, and a message similar to the following:
    • INFO 2020-05-20 21:13:27,285 [[MuleRuntime].cpuLight.02: [java-test].java-test2Flow1.CPU_LITE @4100475] [event: 5b1b0e00-9ad6-11ea-9358-26ee9abecb9d] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: Type is MobilePhone

14 –  Change the Accept subtypes to false in Validate Type operation

15 – Run the project and invoke it with a rest client(Postman/Advanced Rest Client/other)

  • GET request to – http://localhost:8081/test3
  • Validate you got an error similar to the following:
    • ERROR 2020-05-20 22:08:55,226 [[MuleRuntime].cpuLight.16: [java-test].java-test2Flow1.CPU_LITE @2e3ff0d2] [event: 1a159260-9ade-11ea-88cd-26ee9abecb9d] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler:
      ********************************************************************************
      Message : Expected an instance of type [com.toldone.api.MobilePhone] but was [com.toldone.api.Iphone].
      Error type : JAVA:WRONG_INSTANCE_CLASS

15.1 – Notice that ValidateType with AcceptSubtypes field as true accepts instances of the class and classes that extend it (subclasses). If AcceptSubTypes field is false, ValidateType only accepts the class and not the sublclasses.

Leave a Reply

Your email address will not be published. Required fields are marked *