0% found this document useful (0 votes)
149 views9 pages

Essential Groovy Scripts & UDFs For SAP Cloud Integration

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
149 views9 pages

Essential Groovy Scripts & UDFs For SAP Cloud Integration

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Sakshi Tekale

Commonly Used Groovy Scripts in SAP CPI​


Uses of Groovy Scripting:​

✅ Custom transformations – Converting payloads (e.g., XML to JSON, CSV to XML)


✅ Dynamic message manipulation – Modifying headers, properties, or body dynamically


✅ Advanced error handling – Custom logging, exception handling, and retry mechanisms
✅ Calling external APIs – Making HTTP requests or working with external services
✅ Working with attachments – Handling multipart messages, decoding files
✅ Enhanced logging and debugging – Custom logs for troubleshooting
1.​ Dynamically manipulate the message body, headers, and properties

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

def Message processData(Message message){


def body=message.getBody(String)
def headers=message.getHeaders();
def properties=message.getProperties();

body="Modifies body: "+ body;


message.setBody(body);
message.setHeader("Header 1", "myHeader")
message.setProperty("Property 1", "myProperty");

return message
})
message.setProperty(key, value)
}
return message
}

import com.sap.gateway.ip.core.customdev.util.Message ​
This Message class is a built-in SAP CPI API that allows you to access and manipulate
message content, headers, and properties in an Integration Flow (IFlow).​

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

✅ What does it enable?


●​ message.getBody(String) → Retrieves the message payload as a string.
●​ message.getHeaders() → Gets all headers as a map.
●​ message.getProperties() → Retrieves all properties as a map.
●​ message.setBody(newBody) → Modifies the payload (message body).
●​ message.setHeader("key", "value") → Sets a new header.
●​ message.setProperty("key", "value") → Sets a new property
.​


import java.util.HashMap​

Not mandatory, it is included because:
Headers and Properties in SAP CPI Message are internally stored as HashMaps.
If you need to create and manipulate a new map structure within your script, HashMap can
be useful.
Useful when needed to create multiple headers and properties.​

2. Dynamically manipulate the message body, headers, and properties using


HashMap​

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

def Message processData(Message message) {


def body = message.getBody(String)
def headers = message.getHeaders()
def properties = message.getProperties()

body = "Modified Body: " + body


message.setBody(body)

def newHeaders = new HashMap<String, String>()


newHeaders.put("Key1", "val1")
newHeaders.put("Key2", "val2")

newHeaders.each { key, value ->


message.setHeader(key, value)
}

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

def newProperties = new HashMap<String, String>()


newProperties.put("NewProp1", "newVal1")
newProperties.put("NewProp2", "newVal2")

newProperties.each { key, value ->


message.setProperty(key, value)
}
return message
}



3. Dynamic JSON to XML Conversion​

import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
import groovy.xml.MarkupBuilder

def Message processData(Message message){


def body=message.getBody(String);

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


def writer=new StringWriter();
def xml=new MarkupBuilder(writer);

xml.root{
json.each{key,value->
"$key"(value)}
}
message.setBody(writer.toString());
return message
}

JsonSlurper is a built-in Groovy class used to parse JSON strings into a Groovy
data structure (usually a Map or List).​
In this script, it converts the JSON body of the message into a Map for easy
traversal.​

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

MarkupBuilder is used to build XML content dynamically in Groovy.​


It helps convert structured data (like Maps) into a well-formatted XML document
without manual string manipulation.​

xml.root { json.each { key, value -> "$key"(value) } }​
This is where the actual XML structure is being generated:​
A root tag is created using xml.root.​
Each key-value pair from the parsed JSON is added as a child element under
<root>.



4. Dynamic XML to JSON Conversion

import com.sap.gateway.ip.core.customdev.util.Message
import groovy.json.JsonSlurper
import groovy.xml.MarkupBuilder

def Message processData(Message message) {


def body = message.getBody(String)
def json = new JsonSlurper().parseText(body)

def writer = new StringWriter()


def xml = new MarkupBuilder(writer)

xml.root {
buildXML(xml, json)
}

message.setBody(writer.toString())
return message
}

// Recursive method to handle nested JSON objects


def buildXML(xml, json) {
json.each { key, value ->
if (value instanceof Map) {
xml."$key" {
buildXML(xml, value)
}
} else if (value instanceof List) {
value.each {
xml."$key" {
buildXML(xml, it)

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

}
}
} else {
xml."$key"(value)
}
}
}

groovy.xml.XmlSlurper
This Groovy class is used to parse XML documents easily and turn them into
traversable data structures (similar to DOM but more lightweight).​

groovy.json.JsonOutput
This class is used to:
●​ Convert Groovy Maps or Lists to JSON
●​ Format JSON strings nicely (pretty print)​

Key methods:
●​ toJson(map) → Converts Map to raw JSON string
●​ prettyPrint(json) → Makes the JSON readable



5. Capture Message Payload Without Enabling Trace

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

def Message processData(Message message)


{
def body = message.getBody(String);
def messageLog = messageLogFactory.getMessageLog(message);​

if(messageLog != null)
{
messageLog.setStringProperty("log1","Printing Payload As
Attachment")
messageLog.addAttachmentAsString("log1",body,"text/plain");
}
return message;
}

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

messageLogFactory.getMessageLog(message)

This is used to create a logging handle (MessageLog) for the current message.

●​ messageLogFactory is a built-in object provided by the runtime.


●​ It allows you to log custom data to Monitor → Message Processing Logs
(MPL).


messageLog.setStringProperty(String key, String value)

●​ Adds a custom property to the log for visibility in Monitor.


●​ This appears in the MPL as a key-value log entry.​

messageLog.addAttachmentAsString(String name, String content, String


mimeType)

●​ Adds the payload (or any string) as an attachment in the message log.
●​ You can view this attachment later from Monitor → MPL → Attachments
tab.

6. Trim Leading and Trailing Whitespace from Body

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

def Message processData(Message message) {

def body = message.getBody(String).trim()

message.setBody(body)

return message


trim() removes whitespace characters from the beginning and end of a string.

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

7. Transform XML Payload to Uppercase​

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

def Message processData(Message message){

def body=message.getBody(String)

body=body.toUpperCase()

message.setBody(body)

return message


toUpperCase()
●​ Standard Java/Groovy method from the String class.
●​ Converts all characters in the string to uppercase​

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

Commonly Used UDFs in SAP CPI


1.​ Replace Null with Default Value​

def String defaultIfNull(String input, String defaultVal) {


return input ? input : defaultVal
}


Use Case: Assign a default value when input is null or empty.


2. Format Date​

import java.text.SimpleDateFormat

def String formatDate(String inputDate, String inputFormat, String


outputFormat) {
def parser = new SimpleDateFormat(inputFormat)
def formatter = new SimpleDateFormat(outputFormat)
def date = parser.parse(inputDate)
return formatter.format(date)
}


Use Case: Convert dates like "2025-04-10" into "10-Apr-2025" or any
format required.

3. Get Current Timestamp​

import java.text.SimpleDateFormat

def String getCurrentTimestamp(String format) {


def sdf = new SimpleDateFormat(format)
return sdf.format(new Date())
}

https://www.linkedin.cin/sakshi-tekale/
Sakshi Tekale

Use Case: Add a timestamp to a payload, file name, or log.

4. Get Current Timestamp in IST​

import com.sap.it.api.mapping.*;
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.ZoneId

def String getIST() {

ZonedDateTime InIST = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"))


String formattedDate =
InIST.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
return formattedDate
}

ZonedDateTime

●​ Java class from java.time package (Java 8+).


●​ Represents a date and time with a timezone (e.g.,
2025-04-10T15:45+05:30[Asia/Kolkata]).​

ZonedDateTime.now(ZoneId.of("Asia/Kolkata")) ​
gets the current date and time in IST.

ZoneId.of("Asia/Kolkata")

●​ Used to specify the IST timezone.


●​ Asia/Kolkata is the canonical timezone ID for Indian Standard Time
(UTC+05:30).

DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")

●​ Used to format the ZonedDateTime object to a readable string.


●​ This pattern outputs a format like: 2025-04-10 16:30:21.

formattedDate

●​ Final string holding the timestamp in IST, formatted according to the


specified pattern.

https://www.linkedin.cin/sakshi-tekale/

You might also like