7

Learning Groovy Script for Cloud Integration – Part 5

 1 year ago
source link: https://blogs.sap.com/2023/02/08/learning-groovy-script-for-cloud-integration-part-5/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
February 8, 2023 7 minute read

Learning Groovy Script for Cloud Integration – Part 5

Introduction

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(“ResponsePayload:”, 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.

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 tag from your Payload

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

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(/<?xml version=”1.0″ encoding=”UTF-8″?>/,””);

message.setBody(removal);

return message;

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;

import java.lang.*;

def Message processData(Message message) {

map = message.getHeaders();

map = message.getProperties();

message.setBody(map);

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 understand & to create a custom Header or Exchange Property based on some condition. Creation of custom Header or Exchange Property based on a condition on existing Header or Exchange Property. 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’.

Code:

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;

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: replaceAll()

Code:

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

import java.util.HashMap;

def Message processData(Message message) {

def content= message.getBody(java.lang.String);

def newcontent=content.replaceAll(‘”‘,”).replaceAll(‘&’,’;’);

message.setBody(newcontent);

return message;

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

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.

For Example, Firstname = ‘Raviteja’ & Lastname = ‘Satuluri’

FULLNAME = ‘Raviteja Satuluri’

Groovy Functions Involved: Concat ()

Code:

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(“EmployeeFirstname”);

def ZF2    = map.get(“EmployeeLastname”);

String ZConcat = ZF1.concat(ZF2);

message.setProperty(“FULLNAME”,ZConcat);

return message;

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 populate 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

Case 10:

Business Requirement:

Create an Integration Scenario to send an alert email or 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()) {

        message.setBody(“<warning>Attachment is missing</warning>”)

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

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

def Message processData(Message message) {

def messageLog = messageLogFactory.getMessageLog(message);

if(messageLog != null) {

//Read IDoc number from Header

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

//Set IDoc number as Custom Header

if(IDOCNUM!=null)

messageLog.addCustomHeaderProperty(“IDOCNUM”, IDOCNUM);

return message;

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;

Case 13:

Business Requirement:

Create an Integration Scenario to use the groovy script 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.

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;

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

Conclusion –

Hope this document will help to beginners to understand CPI concept of Groovy Script.

Happy Learning 🙂

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK