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

Modernize your application architectures with microservices and APIs with best practices from this free virtual summit series. Brought to you in partnership with CA Technologies.

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

The Integration Zone is proudly sponsored by CA Technologies. Learn from expert microservices and API presentations at the Modernizing Application Architectures Virtual Summit Series.

Topics:
mulesoft ,integration ,groovy ,dataweave ,tutorial

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}