Skip to Content
Technical Articles
Author's profile photo Sookriti Mishra

SAP Cloud Integration (CPI/HCI) || Writing Groovy Scripts _ With Basic Examples

Hi Readers,

So here is a confession. 🤭 I am not very good at writing Groovy Scripts. Yes, and I am still standing strong as a Cloud Integration consultant, and that’s because of a few tricks, and that I will share with you in my blog.
So, I thought, why not curate a blog, mention scripts or examples I have needed so far in an iflow, so that, you reuse the code I wrote and that makes us a big, happy and confident CPI Family. HAHAHA!
Alright! Not sure about the big, happy, and confident thing, but sure will save you a lot of time, and will help you. 👍

Groovy, for none-IT-background-guys, it involves coding. Me? I used to be very good at coding, but now I am just super lazy, and like every other person, I google, and I re-use from my old iflows.

See, the reason I re-use, is because, the scenarios keep repeating, so believe, you could re-use them too.

 

BEFORE WE START, If you are scared of Groovy Scripts, trust me, it’s easy, and if you have reached this blog, then I can assure you will end up walking out with a little bit of confidence than before.

Aaaand, this website here https://groovyide.com/cpi is a blessing. 🙌🙏
Write your code, execute the script, fix errors if any, and put your code in your iflow, and you are good to go.

So, let’s get started. Click here to read my introductory blog on Groovy.

First I will share a few scripts, which you can use as it is in your iflow, if your scenario matches.

1. To record logs so that you can capture the payload even if the IFlow is not on trace.
It is not advisable to use this very often, until and unless it is a very critical scenario.

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;

def Message processData(Message message)
{   
    def body = message.getBody(java.lang.String) as String;
    def messageLog = messageLogFactory.getMessageLog(message);
    if(messageLog != null)
    {
        messageLog.setStringProperty("log1","Printing Payload As Attachment")
        messageLog.addAttachmentAsString("log1",body,"text/plain");
    }
    return message;
}

2. To record logs or capture the incoming payload, only if there is an exception.

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message)
{
       def map  = message.getProperties();
       def ex   = map.get("CamelExceptionCaught");
       if (ex != null)
       {
           exceptionText    = ex.getMessage();
           def messageLog   = messageLogFactory.getMessageLog(message);
           messageLog.addAttachmentAsString("Exception", exceptionText,"application/text");
       }
       return message;
}

For this, all thanks to openSAP course on CPI.

3.  Make your IFlow sleep or stop or pause for some time.
I already have a blog for this, click here to see that one.

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message)
{
       def body = message.getBody();
       sleep(40000);
       message.setBody(body);
       return message;
}


4. Remove something from your payload, for example, “<?xml version=”1.0″ encoding=”UTF-8″?>

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message)
{
    def removal=message.getBody(java.lang.String) as String;
    removal=removal.replace(/<?xml version="1.0" encoding="UTF-8"?>/,"");
    message.setBody(removal);
    return message;
}

 


Now, a couple of basics, and scenarios aaaand, sample codes.

5. getProperties
Click here to compile the code online.

COMPILE
This will return all the properties, Header and Properties.

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import java.lang.*;
def Message processData(Message message)
{
    map = message.getProperties();
    return message;
}

Result:

But this, you aren’t gonna get a scenario like this. 😂 Let’s work with an actual scenario.

6. Capture a property in the content modifier using XPATH, use single IF condition, create and update a new Property which can be used later in a Router or Mapping Expression maybe.
In the example below, we are returning the result in a Property called, “Result”, which you could use in a router/ call it using ${property.Result} if required anywhere.
Click here to compile the code online.

COMPILE

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
def Message processData(Message message) {
    map = message.getProperties();
    def zID = map.get("ID");
    def indicator;
    if(zID == '')
    {
        indicator = 'false';
    }
    else
    {
        indicator = 'true';
    }
    message.setProperty("Result", indicator);
    return message;
}

Result:

7. Let’s say, you want to concatenate a couple of fields.
Click here to compile the code online.

COMPILE

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import java.lang.*;
def Message processData(Message message)
{
    map = message.getProperties();
    def ZF1    = map.get("F1");
    def ZF2    = map.get("F2");
    def ZF3    = map.get("F3");
    String ZConcat = ZF1.concat(ZF2).concat(ZF3);
    message.setProperty("ConcatenatedResult",ZConcat);
    return message;
}

Result:

8. Add days to a Date.
Lets say, you have a requirement to add 30 days to current date.

Click here to compile the code online.

COMPILE

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import java.lang.*;
import com.sap.it.api.mapping.*;
def Message processData(Message message)
{
    Date zcurDate = new Date();
    Date zNewDate = zcurDate + 30;
    message.setProperty("Current_Date",zcurDate);
    message.setProperty("New_Date",zNewDate);
    return message;
}

9. Another way of writing this is:

Click here to compile the code online.

COMPILE

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import java.lang.*;
import com.sap.it.api.mapping.*;
def Message processData(Message message)
{
    def zNewDate = new Date().plus(30)
    message.setProperty("New_Date",zNewDate);
    return message;
}

10. Add days to a Date.
If it’s a message mapping where you are to write a custom function, then, this is what you could write. This will also format your date.

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import com.sap.it.api.mapping.*;
def String datePlus30(String header,MappingContext context){
    Date zcurDate = new Date();
    Date znewDate = zcurDate + 30;
    return znewDate.format("yyyyMMdd");
}

11. Return null for a field in Message Mapping’s Mapping Expression.

import com.sap.it.api.mapping.*;
def String customFunc(String arg1){
	return null
}

12. Return Message Processing ID (MPL ID) and use it in a Mapping Expression.

This is a scenarios, that I have seen mostly in Inbound SAP scenarios, where the Target System would want you to send the MPL ID in one of the fields in the target structure so that you can refer back to it later. So, this is a custom function that you could write:

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import com.sap.it.api.mapping.*;

def String getMessageProcessingLogID(String header,MappingContext context)
{
        String mplId = context.getHeader("SAP_MessageProcessingLogID").toString();
        return mplId;
}

 


That’s it for now. These are pretty basic examples, which if you know how and where to use, will help you cover almost all commonly appearing scenarios. I assure to keep updating this blog here so that you can basically RE-USE the code. 😝🤭😂

Okay, then. 🥳🙋‍♀️
Hope you had a good read.

If you wish to know more, or have any queries on this blog, then please feel free to drop a comment.

Follow me on linked in by clicking here.

 

Thanks & Regards,

Sookriti Mishra

Assigned tags

      6 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Sanjana Satyan
      Sanjana Satyan

      Thank you for making Groovy Script easy😊

      Author's profile photo T Tarun
      T Tarun

      Thanks for sharing, very helpful indeed just like your previous blogs as well.

       

      Author's profile photo Frank Li
      Frank Li

      Thanks for your sharing.

      Author's profile photo Biswajit sahoo
      Biswajit sahoo

      Thank you . It's very useful .

      Author's profile photo Souymodip Chakraborty
      Souymodip Chakraborty

      Thanks for sharing.

      Author's profile photo Hybris Developers1
      Hybris Developers1

      Thank you for the BLOG