Here I am just explaining the Importance of Groovy script in the Real time scenarios when we are dealing with Cloud Integration.

Groovy scripting is an integral and important feature of SAP Cloud Platform Integration (CPI). The goals of this repository are: Providing templates when you are implementing a new script. Easily finding Groovy functions related to the CPI topic at hand. Minimizing search engine time for common tasks.

 

Case 1:

Business Requirement:

Create an Integration Scenario to log the Incoming Payload

Solution: The below Groovy Script will help you to capture the Incoming payload whenever you want in the E2E Execution process.

Code:

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(“Logging#1”, “Printing Payload As Attachment”)

messageLog.addAttachmentAsString(“Payload”, body, “text/plain”);

}

return message;

}

 

Case 2:

Business Requirement:

Create an Integration Scenario to record logs or capture the Incoming Payload only if there is an Exception.

Solution: The below Groovy Script will help you to capture the Record logs or capture the Incoming Payload only if there is an exception occurs during E2E Execution process.

Groovy Functions used: getMessage() & getMessageLog(message)

Code:

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;

}

 

Case 3:

Business Requirement:

Create an Integration Scenario to remove XML tags from your Payload.

Solution: The below Groovy Script will help you to remove XML tags from your Incoming payload.

Groovy Function Involved: replace().

Code:

 

Case 4:

Business Requirement:

Create an Integration Scenario, which will return all the Headers and Exchange Properties

Solution: The below Groovy script will help you to capture or fetch all the Headers and Exchange properties that you are created in your Integration Process.

Groovy Functions Involved: getHeaders() & getProperties()

Code:

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

import java.util.HashMap;
def Message processData(Message message) {
    //Body
    def body = message.getBody();
    //Get Headers
    def map = message.getHeaders();
    def value = map.get(“FNAME”);
    //Get Properties
    map = message.getProperties();
    value = map.get(“Company”);
    return message;
}

 

 

Case 5:

Business Requirement:

Create an Integration Scenario to capture a property in the content modifier using XPATH, use single IF condition, create and update a new Property.

Solution: The below Groovy script will help you to update the value of custom Header or Exchange Property based on some condition. In below Code we are creating a Custom Header ‘Result’ with the value either True or False based on condition on existing Exchange Property ‘ID’.

Case 1: if (ID== Blank) then Result ‘false’

Code:

 

Case 2: if (ID!= Blank) then Result ‘true’

Case 6:

Business Requirement:

Create an Integration Scenario to remove special characters from the Incoming Payload

Solution: The below Groovy Script will help you to remove unwanted special characters in the Incoming Payload during E2E Execution process.

Groovy Functions Involved: replace()

 

Code:

 

Case 7:

Business Requirement:

Create an Integration Scenario to make your IFLOW sleep or stop or pause for some time.

Solution: The below Groovy Script will help you to stop or Pause your entire IFLOW execution for some time, so that the message will deliver to target system with some delay.

Groovy Functions Involved: sleep()

Code:

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

import java.util.HashMap;

def Message processData(Message message) {

def body = message.getBody();

sleep(60000);  [60000 represents Milli seconds]

message.setBody(body);

return message;

}

 

Case 8:

Business Requirement:

Create an Integration Scenario to Concat two fields.

Solution: The below Groovy Script will help you to concat 2 fields.

Code:

 

 

Case 9:

Business Requirement:

Create an Integration Scenario to count the total number of attachments from an Email Message

Solution: The below Groovy Script will help you to count the Number of attachments which are attached to the message.

For example, if there is an Email message which is having multiple attachments and where we need to count the number of attachments, the count value has to be populated to the Target System.

Groovy Functions Involved: getAttachments() & attachments.size()

Code:

import com.sap.gateway.ip.core.customdev.util.Message

import java.util.Map

import java.util.Iterator

import javax.activation.DataHandler

def Message processData(Message message)

{

// get attachments

Map<String, DataHandler> attachments = message.getAttachments();

if (attachments.isEmpty()) {

// in case of no attachment

message.setBody(‘<warning>Attachment is missing</warning>’);

} else {

// get overall number of attachments

message.setHeader(‘NumberOfAttachments’, attachments.size());

}

return message

}

From Sender:

We are sending 2 attachments.

 

IFLOW Created:

 

From Message log:

 

Case 10:

Business Requirement:

Create an Integration Scenario to raise an exception when there are no attachments found from an Email Message.

Solution: The below Groovy Script will help you to throw a custom exception when there are no attachments to the email message.

Code:

import com.sap.gateway.ip.core.customdev.util.Message

import java.util.Map

import java.util.Iterator

import javax.activation.DataHandler

def Message processData(Message message) {

Map<String, DataHandler> attachments = message.getAttachments();

    if (attachments.isEmpty()) {

      throw new Exception (“No Attachment found”);

} else {

//Handling of available attachments

attachments.values().each { attachment ->

if(attachment.getName().contains(“book1”)) {

message.setBody(attachment.getContent());

}

}

return message;

}

 

 

Case 11:

Business Requirement:

Create an Integration Scenario to create custom Header and Exchange Properties

Solution: The below Groovy script will help you to know how to create a Custom Exchange Property. In this case, we are dealing with IDOC Payload where IDOC Number is an unique identifier for the Message. To capture the IDOC Number we are creating a custom Property.

The IDOC Number will be appear in the Message logs.

Code:

 

Case 12:

Business Requirement:

Create an Integration Scenario to perform the JSON to XML conversion.

Solution: The below Groovy script will help you to understand, how to convert JSON to XML.

Groovy Function Involved:  JsonSlurper().

Code:

import com.sap.gateway.ip.core.customdev.util.*;

import groovy.xml.*;

import groovy.json.*;

def Message processData(Message message)

{

//Body

def body = message.getBody(String)

def json = new JsonSlurper().parseText(body)

def writer = new StringWriter()

def builder = new MarkupBuilder(writer)

builder

{

“employees”

{

firstName (json.employees.firstName )

lastName (json.employees.lastName )

}

}

message.setBody(writer.toString())

return message;

}

Input of JSON:

{“employees”:[   { “firstName”:”Jhansi”, “lastName”:”rani” },   { “firstName”:”Samiksha”, “lastName”:”raut” },   { “firstName”:”bala”, “lastName”:”chandra” } ]}

Output: 

<call>   <employees>     <firstName>[Jhansi, Samiksha, bala]</firstName>     <lastName>[rani, raut, chandra]</lastName>   </employees> </call>

 

 

 

Case 13:

Business Requirement:

Create an Integration Scenario to read the IDOC Number extracted in Content Modifier and set it as a Custom Header.

Solution: The below Groovy Script will help you to Read IDOC Number from Header and setting up the same IDOC number as a Custom Header.

 Code:

import com.sap.gateway.ip.core.customdev.util.*;

def Message processData(Message message)

{

def messageLog = messageLogFactory.getMessageLog(message);

if(messageLog != null)

{

//Read IDoc number from Header

def IDOCNUM = message.getHeaders().get(“SAP_ApplicationID“);

//Set IDoc number as Custom Header

if(IDOCNUM!=null)

messageLog.addCustomHeaderProperty(“IDOCNUM”, IDOCNUM);

def SERIAL = message.getHeaders().get(“SAP_MessageType“);

//Set IDoc number as Custom Header

if(SERIAL!=null)

messageLog.addCustomHeaderProperty(“SERIAL”, SERIAL);

}

return message;

}

Groovy script for set Body:

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

import java.util.HashMap;

import java.lang.*;

def Message processData(Message message)

{

map = message.getHeaders();

message.setBody(map);

return message;

}

 

 

 

Case 14:

Business Requirement:

Create an Integration Scenario for a Custom message whenever there is an exception raised by CPI

For Example: if any message fails either due to data issue or connection issue, we will capture the Error log details. Here in this case, From the Payload we want to show Title & Price details for the failed message in the Error log.

Solution: The below Groovy Script will help you to show the Title and Price details in Error Message logs. Whichever source fields that you want to show in the Message error log those details can be highlighted using below Script.

Code: 

import com.sap.gateway.ip.core.customdev.util.*;

import java.util.HashMap;

def Message processData(Message message)

{

def cus_properties = message.getProperties();

def error_message = cus_properties.get(“exception_msg”);

def error_stacktrace = cus_properties.get(“exception_stacktrace”);

def price = cus_properties.get(“price”);

def title = cus_properties.get(“title”);

def messageLog = messageLogFactory.getMessageLog(message);

if (messageLog != null)

{

messageLog.addAttachmentAsString(“Error Stacktrace”,error_stacktrace,”text/plain”);

}

String exceptionBody = “Message processing failed for Title : “+title+” of price: “+price+” with error message: “+error_message;

throw new Exception(exceptionBody);

return message;

}

 

 

Case 15:

Create an Integration Scenario which removes duplicate records Create an Integration Scenario which describes all Data Store Operations using Groovy Scrip Perform all Data Store Operations ( Get, Write ) using Groovy Script.

Solution:

Groovy Script for Data store Write operation:

import com.sap.gateway.ip.core.customdev.util.Message

//Imports for DataStoreService-class

import com.sap.it.api.asdk.datastore.*

import com.sap.it.api.asdk.runtime.*

Message processData(Message message)

{

//Data to be stored in datatore

def map = message.getHeaders();

//def idoc = map.get(“COND_A04”);

def payload = map.get(“idoc”);

//Get service instance

def service = new Factory(DataStoreService.class).getService()

//Check if valid service instance was retrieved

if( service != null)

{

def dBean = new DataBean()

dBean.setDataAsArray(payload.getBytes(“UTF-8”))

//Class model offers headers, but for me it didn’t work out

//Map<String, Object> headers = [“headerName1″:”me”, “anotherHeader”: false]

//dBean.setHeaders(headers)

//Define datatore name and entry id

def dConfig = new DataConfig()

dConfig.setStoreName(“Data”)

dConfig.setId(“1”)

dConfig.setOverwrite(true)

//Write to data store

result = service.put(dBean,dConfig)

}

return message

}

Groovy Script for Data store Get operation:

import com.sap.gateway.ip.core.customdev.util.Message

//Imports for DataStoreService-class

import com.sap.it.api.asdk.datastore.*

import com.sap.it.api.asdk.runtime.*

Message processData(Message message)

{

//Get service instance

def service = new Factory(DataStoreService.class).getService()

//Check if valid service instance was retrieved

if( service != null)

{

//Read data store entry via id

def dsEntry = service.get(“Data”,”1″)

def result = new String(dsEntry.getDataAsArray())

message.setBody(result)

}

return message

}

 

Case 16:

Business Requirement:

Create an Integration scenario to extract text data only from PDF file.

Code:  

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

import java.util.HashMap;

import org.apache.pdfbox.pdmodel.PDDocument;

import org.apache.pdfbox.util.PDFTextStripper;

def Message processData(Message message)

{

def body = message.getBody();

InputStream IS = body;

String res = readFromPDF(IS)

message.setBody(res);

return message;

}

public static String readFromPDF(InputStream input)

{

PDDocument pd;

try {

pd = PDDocument.load(input);

PDFTextStripper stripper = new PDFTextStripper();

stripper.setStartPage(1); // Start Page

String text = stripper.getText(pd);

if (pd != null) {

pd.close();

}

return text.toString()

} catch (Exception e) {

e.printStackTrace();

}

return null

}

Input:

Please find the below table which we are used in the PDF file

 

Output:

Content extracted from PDF:

First name Last name location Date of birth

Raviteja Satuluri mysore 06/09/1990

samiksha raut mumbai 09/7/1999

Bala tirumani Andhra pradesh 06/04/1998

jhansi rani hyderabad 09/08/1999

 

Case 17:

Business Requirement:

Create an Integration Scenario to picks up only PDF files from the list of attachments from the Email Message.

Solution: The below groovy script will help you to filter the attachments.

Code:

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.Map
import java.util.Iterator
import javax.activation.DataHandler
def Message processData(Message message)
{
//message.getContent();
//message.setBody(message.getContent());
Map<String, DataHandler> attachments = message.getAttachments();
if (attachments.isEmpty()) {
throw new Exception(“No Attachments !!”); // Handling of missing attachment goes here
} else {
//Handling of available attachments
attachments.values().each{ attachment ->
if(attachment.getContentType().contains(“pdf”)){
message.getAttachments();
}
}
}
return message;
}

 

Case 18:

Business Requirement:

Create an Integration scenario to convert JSON String UserID to Integer using groovy script.

Solution: The below groovy script will help you to convert string to Integer.

Code:

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

import java.util.HashMap;

import groovy.json.*;

def Message processData(Message message) {

//Body

def body = message.getBody(String.class);

def jsonSlurper = new JsonSlurper()

def list = jsonSlurper.parseText(body)

list.EmployeeData.Record.each

{

it.PersonID.toString()

if ( it.UserID != “”)

{

it.UserID=Integer.parseInt(it.get(“UserID”).toString());

}

else

{

it.UserID=it.UserID

}

it.EmployementID.toString()

}

def jsonOP = JsonOutput.toJson(list)

message.setBody(jsonOP)

return message;

}

 

 

Case 19:

Business Requirement:

Write a Groovy Script and execute a Return Message Processing ID (MPL ID) and use it in a Mapping Expression.

Code: 

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

 

Case 20:

Business Requirement:

Write a Groovy Script and execute to Return null for a field in Message Mapping’s Mapping Expression.

Code: 

import com.sap.it.api.mapping.*;

def String custom_Func(String arg1) {

return null;

}

 

Case 21:

Business Requirement:

Create an Integration Scenario to read a mail message, which is having an attachment from Inbox folder. Send the Mail CSV attachment only to the target system.

Code:

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.Map
import java.util.Iterator
import javax.activation.DataHandler
def Message processData(Message message) {
Map<String, DataHandler> attachments = message.getAttachments();
if (attachments.isEmpty()) {
// Handling of missing attachment goes here
} else {
//Handling of available attachments
attachments.values().each{ attachment ->
if(attachment.getContentType().contains(“CSV”)){
message.setBody(attachment.getContent());
}
}

Case 22:

Business Requirement:

Create an Integration Scenario to read a mail message, which is having an attachment from Inbox folder. Send the Mail XML attachment only to the target system.

Code:

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.Map
import java.util.Iterator
import javax.activation.DataHandler
def Message processData(Message message) {
Map<String, DataHandler> attachments = message.getAttachments();
if (attachments.isEmpty()) {
// Handling of missing attachment goes here
} else {
//Handling of available attachments
attachments.values().each{ attachment ->
if(attachment.getContentType().contains(“XML”))
{
message.setBody(attachment.getContent());
}
}

 

Case 23:

Business Requirement:

Create an Integration Scenario to read a mail body and populate mail body message to Target System.

Code:

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.Map
import java.util.Iterator
import javax.activation.DataHandler
def Message processData(Message message) {
Map<String, DataHandler> attachments = message.getAttachments();
if (attachments.isEmpty()) {
// Handling of missing attachment goes here
} else {
//Handling of available attachments
attachments.values().each{ attachment ->
if(attachment.getContentType().contains(“text/plain”))
{
message.setBody(attachment.getContent());
}
}

 

Case 24:

Business Requirement:

Create an Integration Scenario to read an JSON attachment from Email Inbox.

Code:

import com.sap.gateway.ip.core.customdev.util.Message
import java.util.Map
import java.util.Iterator
import javax.activation.DataHandler
def Message processData(Message message) {
    Map<String, DataHandler> attachments = message.getAttachments();
    if (attachments.isEmpty()) {
        // Handling of missing attachment goes here
    } else {
        //Handling of available attachments
        attachments.values().each{ attachment ->
            if(attachment.getContentType().contains(“json”)){
                message.setBody(attachment.getContent());
            }
        }
    }
    return message;
}

 

Case 25:

Business Requirement:

Create an Integration Scenario to remove duplicate records.

Input: 

<?xml version=”1.0″ encoding=”UTF-8″?>
<header>
<Record>
<id>”bk101″</id>
<author>Gambardella, Matthew</author>
<title>XML Developer’s Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</Record>
<Record>
<id>”bk101″</id>
<author>Gambardella, Matthew</author>
<title>XML Developer’s Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</Record>
</header>

XSLT Code: 

<xsl:stylesheet version=”2.0″
xmlns:xsl=”http://www.w3.org/1999/XSL/Transform”>
<xsl:output method=”xml” indent=”yes”/>
<xsl:template match=”node()|@*”>
<xsl:copy>
<xsl:apply-templates select=”node()|@*”/>
</xsl:copy>
</xsl:template>
<xsl:template match=”header”>
<header>
<xsl:for-each-group select=”Record”
group-by=”id”>
<xsl:apply-templates select=”.”/>
</xsl:for-each-group>
</header>
</xsl:template>
</xsl:stylesheet>

Output:

<?xml version=”1.0″ encoding=”UTF-8″?>
<header>
<Record>
<id>”bk101″</id>
<author>Gambardella, Matthew</author>
<title>XML Developer’s Guide</title>
<genre>Computer</genre>
<price>44.95</price>
<publish_date>2000-10-01</publish_date>
<description>An in-depth look at creating applications
with XML.</description>
</Record>
</header>

 

Case 26:

Business Requirement:

Fetch the data which is in the Body section for SOAP Envelope.

Input:

<s:Envelope xmlns:s=”http://schemas.xmlsoap.org/soap/envelope/”>
<s:Header>
<Action xmlns=”http://schemas.microsoft.com/ws/2005/05/addressing/none” s:mustUnderstand=”1″>http://sap.com/xi/WebService/soap1.1</Action>
</s:Header>
<s:Body xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”>
<_BAPI_PO_GETDETAILS xmlns=”urn:sap-com:document:sap:rfc:functions”>
<PO xmlns=””/>
</_BAPI_PO_GETDETAILS>
</s:Body>
</s:Envelope>

Expected Output:

<_BAPI_PO_GETDETAILS xmlns=”urn:sap-com:document:sap:rfc:functions”>
<PO xmlns=””/>
</_BAPI_PO_GETDETAILS>

 

Code:

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(“http://sap.com/xi/WebService/soap1.1″,””);
    removal=removal.replace(“xmlns:s=”http://schemas.xmlsoap.org/soap/envelope/””,””);
  removal=removal.replace(“xmlns=”http://schemas.microsoft.com/ws/2005/05/addressing/none””,””);
    removal=removal.replace(“xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance””,””);
    removal=removal.replace(“xmlns:xsd=”http://www.w3.org/2001/XMLSchema””,””);
    removal=removal.replace(“s:mustUnderstand=”1″”,””);
    removal=removal.replace(“<s:Envelope >”,””);
    removal=removal.replace(“<s:Header>”,””);
    removal=removal.replace(“</s:Header>”,””);
    removal=removal.replace(“<s:Body  >”,””);
    removal=removal.replace(“<Action  ></Action>”,””);
    removal=removal.replace(“</s:Body>”,””);
    removal=removal.replace(“</s:Envelope>”,””);
    message.setBody(removal);
    return message;
}

 

 

Sara Sampaio

Sara Sampaio

Author Since: March 10, 2022

5 1 vote
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x