SAP Integration Suite Groovy script examples: a cheat sheet
Ready-to-use Groovy snippets for SAP Integration Suite (formerly SAP Cloud Platform Integration, CPI) script steps: reading the body, headers and properties, XML and JSON, the Message Processing Log, secure store, partner directory, dates and error handling. Every snippet runs on Groovy 2.4 and Groovy 4, and you can try each one in the GrooveBox online Groovy IDE without a tenant.
All snippets go inside the script function:
import com.sap.gateway.ip.core.customdev.util.Message // Groovy 4 / Script API v2: com.sap.it.script.v2.api.Message
def Message processData(Message message) {
// ... snippet ...
return message
}
Read and write the body
def body = message.getBody(String) // the whole payload as text
def stream = message.getBody(InputStream) // large payloads: process as a stream
message.setBody('<Result>OK</Result>')
Headers and exchange properties
message.setHeader('Content-Type', 'application/json')
message.setProperty('OrderId', '4711')
def sender = message.getHeader('SAP_Sender', String) // null if missing
def headers = message.getHeaders() // all headers as a Map
def maxItems = message.getProperty('MaxItems') ?: 100 // default when missing
Parse XML and read values
// Groovy 4: add import groovy.xml.XmlSlurper
def order = new XmlSlurper().parseText(message.getBody(String))
def id = order.Id.text()
def skus = order.Items.Item.collect { it.Sku.text() }
def total = order.Items.Item.sum { it.Qty.text() as Integer }
Build XML
import groovy.xml.MarkupBuilder
def writer = new StringWriter()
new MarkupBuilder(writer).Result {
OrderId('4711')
Status('OK')
}
message.setBody(writer.toString())
Parse, change and write JSON
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
def json = new JsonSlurper().parseText(message.getBody(String))
json.status = 'processed'
message.setBody(JsonOutput.prettyPrint(JsonOutput.toJson(json)))
Convert XML to JSON
import groovy.json.JsonOutput
// Groovy 4: add import groovy.xml.XmlSlurper
def order = new XmlSlurper().parseText(message.getBody(String))
def result = [
id : order.Id.text(),
items: order.Items.Item.collect { [sku: it.Sku.text(), qty: it.Qty.text() as Integer] }
]
message.setBody(JsonOutput.toJson(result))
message.setHeader('Content-Type', 'application/json')
Write to the Message Processing Log (MPL)
def messageLog = messageLogFactory.getMessageLog(message)
messageLog?.setStringProperty('OrderId', '4711')
messageLog?.addAttachmentAsString('Payload', message.getBody(String), 'text/plain')
Attaching payloads to the MPL is useful while testing, but avoid it for large or sensitive payloads in production.
Value mapping lookup
import com.sap.it.api.ITApiFactory
import com.sap.it.api.mapping.ValueMappingApi
def vm = ITApiFactory.getApi(ValueMappingApi.class, null)
def target = vm.getMappedValue('S4', 'Country', 'IT', 'SF', 'Country') // null if no mapping
More in Value mapping lookups in SAP Integration Suite Groovy scripts.
Credentials from the secure store (Basic authentication header)
import com.sap.it.api.ITApiFactory
import com.sap.it.api.securestore.SecureStoreService
def store = ITApiFactory.getApi(SecureStoreService.class, null)
def credential = store.getUserCredential('MY_ALIAS')
def auth = "${credential.getUsername()}:${new String(credential.getPassword())}".bytes.encodeBase64().toString()
message.setHeader('Authorization', "Basic ${auth}")
Partner directory parameter
import com.sap.it.api.ITApiFactory
import com.sap.it.api.pd.PartnerDirectoryService
def pd = ITApiFactory.getApi(PartnerDirectoryService.class, null)
def endpoint = pd.getParameter('ReceiverURL', 'PARTNER_01', String)
Dates and timestamps
import java.time.ZonedDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
def now = ZonedDateTime.now(ZoneId.of('Europe/Rome'))
message.setProperty('Timestamp', now.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME))
message.setProperty('Day', now.format(DateTimeFormatter.ofPattern('yyyyMMdd')))
Base64
def encoded = message.getBody(String).bytes.encodeBase64().toString()
def decoded = new String(encoded.decodeBase64(), 'UTF-8')
Fail the message on purpose
if (!message.getBody(String)?.trim()) {
throw new IllegalStateException('Empty payload')
}
An exception thrown by the script ends the message processing with an error, which the iFlow's exception subprocess can handle. See common SAP Integration Suite Groovy script errors for the messages you are most likely to meet.
Try the snippets
Open the playground, paste a snippet inside processData, add the body,
headers, properties, value mappings or secure store entries it needs, and press Ctrl+Enter.
Switch between Groovy 2.4 and Groovy 4 to check both runtimes.