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

The Future of Enterprise Integration: Learn how organizations are re-architecting their integration strategy with data-driven app integration for true digital transformation.

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)
      }

Make your mark on the industry’s leading annual report. Fill out the State of API Integration 2019 Survey and receive $25 to the Cloud Elements store.

Topics:
mulesoft ,integration ,groovy ,dataweave ,tutorial

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}