Invoke Mulesoft flow from Java
I had a scenario where, I had to synchronously + recursively collect paged data from a REST API.
To get data as per the requirement, I had to do a loop in JAVA and call Mulesoft flow to collect data using the REST API. The following is the approach I chose to get the paged data in synchronous process.
Mulesoft flow code
<flow name=”common-codeFlow”>
……………… flow code goes here to get data from REST API…
</flow>
Java code to call the above “common-codeFlow” recursively to collect the data.
This class in consumed in the flow using a JAVA component.
The following GetNextURIPagedData class implements Callable, FlowConstructAware, MuleContextAware to invoke the Mulesoft flow.
Java code in GetNextURIPagedData.java
public class GetNextURIPagedData implements Callable, FlowConstructAware, MuleContextAware {
MuleContext mContext;
FlowConstruct flowConstruct;
@Override
public void setMuleContext(MuleContext context) {
this.mContext = context;
}
@Override
public void setFlowConstruct(FlowConstruct flowConstruct) {
this.flowConstruct = flowConstruct;
}
@Override
public Object onCall(MuleEventContext eventContext) throws Exception {
String strPayload = eventContext.getMessage().getPayload().toString();
try {
MessageProcessor muleFlow = mContext.getRegistry().lookupObject(“common-codeFlow”);
MuleMessage muleMessage = new DefaultMuleMessage(eventContext.getMessage(), mContext);
System.out.println(“In Java Class : Getting data for URL : “ + muleMessage.getPayloadAsString());
MuleEvent inputEvent = new DefaultMuleEvent(muleMessage, MessageExchangePattern.REQUEST_RESPONSE,
mContext.getRegistry().lookupFlowConstruct(“common-codeFlow”) ,new DefaultMuleSession() );
//Code to invoke the
MuleEvent result = muleFlow.process(inputEvent);
System.out.println(result.getMessage().getInboundProperty(“Links”).toString());
} catch (Exception e) {
System.out.println(e.getMessage());
}
return “”;
}
}
Thank you for reading! If you enjoyed it, please clap 👏 for it.
-Naveen