Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Use of a Java/Groovy Expression in a DataWeave Script in MuleSoft

DZone's Guide to

Use of a Java/Groovy Expression in a DataWeave Script in MuleSoft

It doesn't have to be difficult to call complicated classes in a DataWeave script.

· Integration Zone ·
Free Resource
CRM integration has become the cornerstone to meeting initiatives across organizations. Explore the top 6 value-driven Salesforce CRM integrations ebook.  

Suppose that we have a class named FetchValue.java under a package named utils.mypackage whose function named fetchD(String A, String B, String C) with return type as String needs to be called in the DataWeave script.

Make an entry in the Mule global configuration as:

<configuration doc:name="Configuration">
     <expression-language>
        <import class="utils.mypackage.FetchValue"/>
             <global-functions>
                def getKeyValue(A,B,C) {
                 return new utils.mypackage.FetchValue().fetchD(A,B,C);          
                }
             </global-functions>
      </expression-language>
</configuration>


We can also externalize the functions inside the global functions:

 <configuration doc:name="Configuration">
    <expression-language autoResolveVariables="true">
           <global-functions file = "globalfunc.mvel">
           </global-functions>
    </expression-language>
 </configuration>

Now, create a file under src/main/resources as globalfunc.mvel and write the java/groovy functions inside them

 def getValue(collatedKey,value) {
      if(flowVars.ilFileMap.get(collatedKey) != null) {
         flowVars.newIlFileMap.put(collatedKey,value);
      }
      return flowVars.ilFileMap.get(collatedKey);
   }
   
 def putKeyValue(key,value) { 
     flowVars.ilFileMap.put(key,value); 
   }
  
 def getNewValue(collatedKey) {
   return flowVars.newIlFileMap.get(collatedKey);
 }


Access them in DataWeave script as: 

%dw 1.0
%output application/json 
---
results: {
      OP: getKeyValue(payload.A, payload.B, payload.C)
      }

Sync, automate, and notify lead to customer changes across marketing, CRM, and messaging apps in real-time with the Cloud Elements eventing framework. Learn more.

Topics:
mulesoft ,integration ,groovy ,dataweave ,tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}