iGlow / Blog / Groovy script examples

How-to

Groovy scripts in SAP CPI: 10 examples you can copy

Short answer: To write a Groovy script in SAP CPI, add a Script step (Message Transformers > Script > Groovy Script) to your iFlow and write a processData(Message message) function. CPI calls it for every message. Read or change the body, headers and properties through message, then return message. Or ask iGlow to write it for you.

Why Groovy scripts in CPI eat your afternoon

The script itself is usually ten lines. The time goes somewhere else.

Below are ten scripts that work, and the errors you will meet. If you would rather not write and debug them yourself, jump to the easy way with iGlow.

The by-hand way: how a Groovy script in SAP CPI works

In the palette, open Message Transformers, add the Script step to the route, choose Groovy Script and click Create. The editor starts you off with a processData function. CPI calls it for every message that reaches the step. If you rename it, type the new name into the Script Function field.

The message object gives you the body, the headers and the properties. Headers travel to the receiver. Properties (exchange properties) stay inside the iFlow. The function must return the message.

There are two script step versions, and they use different Groovy runtimes. SAP's documentation lists Groovy 2.4.21 for script step version 1.1 and Groovy 4.0.29 for version 2.0. The two versions import a different Message class:

Script step versionGroovy runtimeMessage importXML classes
1.12.4.21com.sap.gateway.ip.core.customdev.util.Messagegroovy.util.XmlSlurper, groovy.util.XmlParser
2.04.0.29com.sap.it.script.v2.api.Messagegroovy.xml.XmlSlurper, groovy.xml.XmlParser

The examples are written for version 2.0 (Groovy 4). For version 1.1, change the Message import and the XML imports as in the table. Both runtimes are listed in SAP's Define a Local Script Step.

How these were tested. Every script ran on Java 17 against the real Message interface from SAP's public Script API jars on Maven Central (script.v2.api and script.api), with small stand-ins for the message and the message log, and an assertion on each result. Version 2.0 scripts ran on Groovy 4.0.29, version 1.1 variants on Groovy 2.4.21. They were not run on a live tenant, so test each one in the simulation first.

SAP Integration Suite script editor showing a Groovy script with the processData(Message message) function, opened from a Groovy Script step in an iFlow
SAP's script editor, opened from the Processing tab of a Groovy Script step. The script starts with import com.sap.gateway.ip.core.customdev.util.Message and defines processData.

Read a header and set a property

This script reads a header and a property, falls back to a default value, and writes a new property and a new header.

import com.sap.it.script.v2.api.Message

def Message processData(Message message) {
    // Read a header. The result is null when the header does not exist.
    def orderType = message.getHeader('OrderType', String)

    // Read an exchange property. Also null when it does not exist.
    def country = message.getProperty('country')

    // Fall back to a default value
    if (!orderType) {
        orderType = 'STANDARD'
    }

    // Write a property (stays inside the iFlow) and a header (travels to the receiver)
    message.setProperty('orderTypeUsed', orderType)
    message.setHeader('X-Country', country ?: 'unknown')

    return message
}

getHeader(name, Class) returns null when the header is missing, so the default keeps a missing value from failing a later step.

With iGlow: Describe it in chat: “Read the OrderType header, use STANDARD if it is missing, and save it as a property.” iGlow writes the null check for you.

Log the payload in the message log

This script writes the current body to the message processing log as an attachment, but only when a property called logPayload is true.

import com.sap.it.script.v2.api.Message

def Message processData(Message message) {
    // Only log when the property logPayload is 'true' (set it from an externalized parameter)
    if (message.getProperty('logPayload') == 'true') {
        def body = message.getBody(String)
        def messageLog = messageLogFactory.getMessageLog(message)
        if (messageLog != null) {
            messageLog.addAttachmentAsString('Payload before mapping', body, 'text/plain')
        }
    }
    return message
}

messageLogFactory is available in every script without an import. The attachment appears on the message in Monitor > Message Processing. SAP warns that attachments use the tenant's limited storage, so keep the switch off in production. SAP's version is in Create MPL Attachments in Scripts.

With iGlow: Ask: “Log the body as an attachment, but only when the property logPayload is true.” iGlow adds the script step and the switch.

Parse JSON and read a field

This script reads a field and the number of items from a JSON body and stores them as properties and a header.

import com.sap.it.script.v2.api.Message
import groovy.json.JsonSlurper

def Message processData(Message message) {
    // Stream the body into the parser instead of copying it into a String first
    def json = new JsonSlurper().parse(message.getBody(Reader))

    // Use ?. so a missing "order" object gives null instead of an error
    message.setProperty('orderId', json.order?.id)
    message.setProperty('itemCount', json.order?.items?.size() ?: 0)

    // Take the SKU of the first item, if there is one
    def items = json.order?.items
    message.setHeader('X-First-Sku', items ? items[0].sku : '')

    return message
}

Passing a Reader to parse streams the body instead of copying it into a String, which SAP's general scripting guidelines recommend for large payloads. The ?. operator stops a missing order object from causing a null pointer error.

With iGlow: Paste a sample JSON and say which field you need. iGlow writes the ?. checks so a missing object does not fail the step.

Build a JSON response

This script reads an order, drops lines with a quantity of zero, adds a line total to each remaining line, and replaces the body with a new JSON document.

import com.sap.it.script.v2.api.Message
import groovy.json.JsonOutput
import groovy.json.JsonSlurper

def Message processData(Message message) {
    def input = new JsonSlurper().parse(message.getBody(Reader))

    // Keep only the lines with a quantity and work out each line total
    def lines = input.items.findAll { it.qty > 0 }.collect {
        [sku: it.sku, qty: it.qty, lineTotal: it.qty * it.price]
    }

    def result = [
        orderId: input.id,
        status : 'RECEIVED',
        lines  : lines,
        total  : lines.sum { it.lineTotal } ?: 0
    ]

    message.setBody(JsonOutput.toJson(result))
    message.setHeader('Content-Type', 'application/json')
    return message
}

You build a normal Groovy map and let JsonOutput.toJson turn it into compact JSON. SAP's guidelines prefer compact output over pretty-printed output.

With iGlow: Give iGlow the input and the output you want. It builds the map, the filter and the totals, and you see the script before it is saved.

Read values from an XML payload

This script reads an element, an attribute and a sum of prices from an XML body, even when the body uses a namespace prefix.

import com.sap.it.script.v2.api.Message
import groovy.xml.XmlSlurper

def Message processData(Message message) {
    // XmlSlurper matches element names without the namespace prefix
    def root = new XmlSlurper().parse(message.getBody(Reader))

    message.setProperty('orderId', root.Header.OrderID.text())

    // Add up all item prices
    def total = root.Items.Item.collect { it.Price.text() as BigDecimal }.sum() ?: 0
    message.setProperty('orderTotal', total.toString())

    // Read an attribute
    message.setProperty('currency', root.Header.OrderID.@currency.text())

    return message
}

XmlSlurper matches element names without their namespace prefix, so root.Header.OrderID also works on <ns:Order xmlns:ns="urn:demo">. Use parse with a Reader, not parseText. SAP says parseText(String) needs more memory and does not scale to large payloads.

With iGlow: Say which element you need and whether the body has a namespace. iGlow picks the right import for your script version.

Change or add an XML element

This script changes the text of one element, adds a new element, and writes the XML back to the body.

import com.sap.it.script.v2.api.Message
import groovy.xml.XmlParser
import groovy.xml.XmlUtil

def Message processData(Message message) {
    def root = new XmlParser().parse(message.getBody(Reader))

    // Change the text of an existing element
    root.Header.Status[0].value = 'PROCESSED'

    // Add a new element at the end of Header
    new Node(root.Header[0], 'ProcessedBy', 'CPI')

    // XmlUtil.serialize pretty-prints, so use it on small payloads only
    message.setBody(XmlUtil.serialize(root))
    return message
}

Use XmlParser to change a document and XmlSlurper to read one. XmlUtil.serialize adds an XML declaration and indents the output, so use it on small messages only.

With iGlow: Ask for the change in words, for example “set Status to PROCESSED and add a ProcessedBy element”. You approve the script first.

Add a searchable value to the message monitor

This script saves a business value, such as a purchase order number, as a custom header on the message log, so you can search for the message later.

import com.sap.it.script.v2.api.Message

def Message processData(Message message) {
    def messageLog = messageLogFactory.getMessageLog(message)
    if (messageLog != null) {
        // Shows up in Monitor > Message Processing > More Fields > Custom Header
        def poNumber = message.getProperty('poNumber')
        if (poNumber) {
            messageLog.addCustomHeaderProperty('po_number', poNumber.toString())
        }
        messageLog.setStringProperty('Step', 'Order validated')
    }
    return message
}

In Monitor > Message Processing, choose Use More Fields and type po_number = 12345 into the Custom Header field. SAP documents this pattern in Use Custom Header Properties to Search for Message Processing Logs.

With iGlow: Ask: “Save the PO number as a custom header so I can search for it in the monitor.”

Read URL query parameters

This script splits the query string of an incoming HTTPS request into one property per parameter.

import com.sap.it.script.v2.api.Message

def Message processData(Message message) {
    // For a request like ...?$top=2&$skip=3&name=A%26B the header CamelHttpQuery holds the part after the ?
    String query = message.getHeader('CamelHttpQuery', String)

    if (query) {
        query.tokenize('&').each { pair ->
            def parts = pair.split('=', 2)
            def name = URLDecoder.decode(parts[0], 'UTF-8')
            def value = parts.length > 1 ? URLDecoder.decode(parts[1], 'UTF-8') : ''
            // Keep $ out of property names so you can use them as ${property.top}
            message.setProperty(name.replace('$', ''), value)
        }
    }
    return message
}

The header CamelHttpQuery holds the text after the question mark. For ?$top=2&name=A%26B the script creates the properties top (2) and name (A&B). It splits first and decodes second, so an encoded & inside a value cannot break the split. SAP's sample is in Access URL Get Parameters in Scripts.

With iGlow: Ask iGlow to read the query parameters into properties. iGlow writes the splitting and the decoding.

Handle an HTTP error in an exception subprocess

This script runs inside an Exception Subprocess, reads the caught exception, and turns it into a small JSON error body.

import com.sap.it.script.v2.api.Message
import groovy.json.JsonOutput

// Put this Script step inside an Exception Subprocess
def Message processData(Message message) {
    def ex = message.getProperty('CamelExceptionCaught')
    if (ex != null) {
        def error = [
            type   : ex.getClass().getCanonicalName(),
            message: ex.getMessage()
        ]
        // HTTP errors carry a status code and the response body; other errors do not
        if (ex.metaClass.respondsTo(ex, 'getStatusCode')) {
            error.statusCode = ex.getStatusCode()
        }
        if (ex.metaClass.respondsTo(ex, 'getResponseBody')) {
            error.responseBody = ex.getResponseBody()
        }
        message.setProperty('errorText', ex.getMessage())
        message.setBody(JsonOutput.toJson(error))
        message.setHeader('Content-Type', 'application/json')
    }
    return message
}

When a step fails, CPI stores the exception in the property CamelExceptionCaught. SAP's HTTP example reads the status code and response body from it. The exception class depends on the adapter, so this script uses respondsTo instead of checking one class name. The test used a stand-in exception with those two methods and a plain IllegalStateException. SAP's version is in Script Example for Exception Handling in HTTP Receiver.

With iGlow: Ask iGlow to add an exception subprocess with a script that returns a small JSON error. It can add both steps for you to approve.

Format and convert dates

This script builds a file name from the current date and time, and converts a date from 31.12.2026 to 2026-12-31.

import com.sap.it.script.v2.api.Message
import java.time.LocalDate
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter

def Message processData(Message message) {
    // Today's date in a fixed time zone, for example for a file name
    def now = ZonedDateTime.now(ZoneId.of('Europe/Berlin'))
    message.setHeader('CamelFileName', 'orders_' + now.format(DateTimeFormatter.ofPattern('yyyyMMdd_HHmmss')) + '.xml')

    // Convert 31.12.2026 to 2026-12-31
    def input = message.getProperty('invoiceDate')
    def date = LocalDate.parse(input, DateTimeFormatter.ofPattern('dd.MM.yyyy'))
    message.setProperty('invoiceDateIso', date.toString())

    return message
}

Use java.time for dates. The older shortcut Date.parse('yyyy-MM-dd', text) is not safe on Groovy 4 (see below). Set the time zone yourself, as the example does, and never call TimeZone.setDefault. It changes the time zone of the whole virtual machine.

With iGlow: Tell iGlow the formats, for example “31.12.2026 to 2026-12-31”. It uses java.time, not the old Date.parse.

Common Groovy errors in SAP CPI and what they mean

These error texts were reproduced locally on Groovy 4.0.29, except the first one, which SAP documents. In CPI they appear in the message monitor, often wrapped in a javax.script.ScriptException.

Error textWhat it means and the fix
javax.script.ScriptException: groovy.lang.MissingPropertyException: No such property: message for class: script[xx]__ScriptA name is used where it does not exist, usually message inside a helper function that did not get it as a parameter. Pass it in. Text from SAP KBA 3516516. Locally it read ... for class: Script1.
java.lang.NullPointerException: Cannot invoke method trim() on null objectA header, property or body was null. Check with if (value) or use ?. first.
unable to resolve class groovy.util.XmlSlurperA Groovy 2.4 import in a Groovy 4 script. Use import groovy.xml.XmlSlurper. SAP lists the same fix in Use Import Statements Supported by the Script Runtime.
unable to resolve class XmlSlurperThe import is missing. Groovy 4 does not add it for you.
groovy.lang.MissingMethodException: No signature of method: static java.util.Date.parse() is applicable for argument types: (String, String)Locally this failed until the separate groovy-dateutil jar was added. A community write-up on upgrading to script version 2.0 reports the same failure in CPI. Switch to java.time.
groovy.json.JsonException: Unable to determine the current character, it is not a string, number, array, or objectThe body is empty or is not JSON. Check it before parsing.
org.xml.sax.SAXParseException: Premature end of file.The XML body is empty. Check the step before it.

A script that fails after the move to Java 17 may reach into private members of Java classes. See SAP KBA 3524073.

How do I debug a Groovy script in SAP CPI?

SAP recommends testing a script with the integration flow simulation or an external tool such as IntelliJ IDEA, rather than deploying the iFlow each time. The simulation supports the Script step, but not HTTP calls made inside a script. You can also write values to the message log (examples 2 and 7) or set the log level to Trace to see the message content. Use Trace only on development or test tenants, because it uses many resources and expires after 10 minutes by default.

The easy way: Groovy scripts with iGlow

iGlow is an AI agent for SAP Integration Suite and CPI that runs as a Chrome extension side panel. You say what the script should do. iGlow reads the iFlow around the step, writes the script and checks it for common runtime mistakes, such as the wrong import for the script version or an unchecked null. You read it, then you approve. Nothing is saved before that.

Instead of the edit, save, deploy, send, read-the-error loop, it looks like this:

  1. Open the iFlow in SAP Integration Suite and open the iGlow side panel.
  2. Ask in plain words. For example: Add a Groovy script after the mapping. Read the JSON body, take order.id into a property, and write the body to the message log when logPayload is true.
    iGlow chat in the demo iFlow Orders_Blog_Demo with the request: Change the Groovy script Check orderId so it also rejects the order when customerId is missing, with iGlow thinking
    The request, in the chat. Here it asks for a change to an existing script, which works the same way as asking for a new one.
  3. Read the proposed script. It waits on an approval card. You can approve it, edit it or reject it and say what to change.
    iGlow diff of the proposed change to the script orderIdCheck.groovy: the body is parsed once and a customerId check is added, with the buttons Approve & save, Edit and Reject
    The proposed script, waiting for your click.
  4. Approve. iGlow takes a snapshot of the iFlow first, so you can undo, then saves the script in the iFlow.
    iGlow chat after approval: Change script orderIdCheck.groovy, Saved (snapshot taken first), with the link Open Orders_Blog_Demo in SAP and the proposed diff below
    After you approve, iGlow saves the script, notes that a snapshot was taken first and links to the iFlow in SAP.
  5. Test it. Ask iGlow to run SAP's simulation over the changed steps, or send a real test message from the Test tab. See test an iFlow with simulation.
Short clip in the demo iFlow Orders_Blog_Demo: ask for a change to the script Check orderId, review the diff, click Approve & save. The clip ends with "Saved (snapshot taken first)".

When a script already fails

This is the part that eats the most time by hand. Pick the failed message in iGlow and click Fix. iGlow reads the error, the scripts and the trace of that message, so it can name the real cause, even when it sits in an earlier step. It then proposes a small change as a diff. You approve it, edit it or reject it. Details are in fix failed messages in SAP CPI.

iGlow Fix answer for the demo iFlow Invoice_S4_to_Ariba: why the last message failed (a null amount, line 5 of mapInvoiceToCXML.groovy), the proposed fix marked rejected, and two options
Fix on a failed message: the root cause first.
iGlow card Proposed change for mapInvoiceToCXML.groovy: a one-line guard shown as a diff, with the buttons Approve & save, Edit and Reject
The patch as a diff. Nothing is saved until you click Approve & save.
Short clip: click Fix on a failed message, read the cause, review the patch. Here the patch is rejected, so nothing is changed.

What stays free

The script browser with a diff, and the snapshots, are free and unlimited. They do not use AI. Writing and fixing scripts uses AI requests. The free plan includes about 200 a month. Prices and limits are in the pricing section. iGlow never changes a tenant tagged PRD. Add iGlow to Chrome to try it on your own iFlow, or read create an iFlow with AI.

Questions

How do I write a Groovy script in SAP CPI?

Add a Script step from the Message Transformers group of the palette, choose Groovy Script and click Create. The editor gives you a processData(Message message) function. Put your logic in it and return the message.

How do I read a header or property in a CPI Groovy script?

Use message.getHeader('Name', String) for a header and message.getProperty('name') for a property. Both return null when the value does not exist, so check for null before you use the result. Example 1 shows it.

How do I parse JSON in SAP CPI Groovy?

Import groovy.json.JsonSlurper and call new JsonSlurper().parse(message.getBody(Reader)). You can then read fields like json.order.id. See the JSON example.

How do I log the payload in SAP CPI?

Get the message log with messageLogFactory.getMessageLog(message) and call addAttachmentAsString with the body. The attachment shows on the message in the Message Processing monitor. Use it only while you troubleshoot, because attachments use tenant storage.

How do I debug a Groovy script in SAP CPI?

SAP recommends testing scripts with the integration flow simulation or an external tool such as IntelliJ IDEA instead of deploying each time. You can also write values to the message log, or set the log level to Trace on a development tenant to see the message content.

Can AI write a Groovy script for SAP CPI?

Yes. iGlow, an AI agent in a Chrome side panel, writes the script from your description and shows it for approval before it saves anything. You should still test it with SAP's simulation or a test message.

More from the blog and guides