0% found this document useful (0 votes)
2 views

Modifier with Realtime examples

The document explains the use of the Content Modifier in SAP CPI for modifying message content, headers, and properties within integration flows. It provides real-time examples, including adding custom headers, extracting properties, and transforming message bodies, along with a hands-on exercise for practical application. Additionally, it outlines deployment and testing steps for integration flows using tools like Postman and CURL.

Uploaded by

jaydata2018
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Modifier with Realtime examples

The document explains the use of the Content Modifier in SAP CPI for modifying message content, headers, and properties within integration flows. It provides real-time examples, including adding custom headers, extracting properties, and transforming message bodies, along with a hands-on exercise for practical application. Additionally, it outlines deployment and testing steps for integration flows using tools like Postman and CURL.

Uploaded by

jaydata2018
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

SAP CPI Content Modifier with Realtime Examples

The Content Modifier in SAP CPI is a processing step used to modify the message content,
headers, and properties within an integration flow. It allows you to:

 Add or update Message Headers


 Add or update Message Properties
 Modify the Message Body

1. Message Header Example


Use Case: Pass a custom HTTP header in a request

Scenario:
A third-party system requires an API call with a specific header (API-Key).

Integration Steps

1. Use Content Modifier to add a new header (API-Key).


2. Use an HTTP Receiver Adapter to send the request.

Configuration in Content Modifier

 Headers Tab
o Name: API-Key
o Type: Constant
o Value: 123456789-ABCDE

This adds the API-Key header to the message before sending it.

2. Message Property Example


Use Case: Store dynamic values for further processing

Scenario:
You need to store the order ID from an incoming XML payload and use it later in the flow.

Example XML Payload


xml
CopyEdit
<Order>
<ID>56789</ID>
<Amount>150.00</Amount>
</Order>

Configuration in Content Modifier

 Properties Tab
o Name: OrderID
o Type: XPath
o Value: /Order/ID

This extracts 56789 and stores it in the OrderID property. You can use this in later steps (e.g.,
logging or mapping).

3. Modify Message Body Example


Use Case: Transform the payload format

Scenario:
A source system sends an XML, but the target system expects JSON.

Content Modifier Configuration (Body Tab)

 Body Type: Expression


 Value:

json
CopyEdit
{
"OrderID": "${property.OrderID}",
"Status": "Processing"
}

This replaces the existing body with JSON, dynamically using the OrderID property.

4. Full Realtime Scenario


Use Case: Pass Order Data with Custom Headers

Scenario:
1. A source system sends an XML payload with order details.
2. You extract OrderID using a Content Modifier (Property).
3. You set a custom header (Transaction-ID).
4. You modify the message body to match the API request format.
5. You send the request to an external REST API.

Content Modifier Steps

 Property: Extract OrderID


 Header: Add Transaction-ID
 Body: Convert to JSON

Final Message Sent to API


json
CopyEdit
{
"OrderID": "56789",
"Amount": "150.00",
"Status": "Processing"
}

Conclusion
Content Modifier is essential in SAP CPI for message transformation and metadata handling.
Whether modifying headers for authentication, extracting properties for routing, or transforming
payloads, it plays a crucial role in real-world integration scenarios.

Would you like me to provide a hands-on exercise for practice? 🚀

You said:

yes
ChatGPT said:

Hands-on Exercise: Using Content Modifier in SAP CPI 🚀

This exercise will guide you through modifying message headers, properties, and body using
Content Modifier in SAP CPI.
💡 Scenario: Order Processing API Integration
You need to process incoming order data, extract the Order ID, set a custom Transaction ID
header, and format the message to JSON before sending it to a REST API.

🛠️Step-by-Step Implementation
🔹 Step 1: Create an Integration Flow

1. Open SAP Integration Suite (SAP CPI).


2. Navigate to Design -> Create Integration Flow.
3. Name the integration OrderProcessing_IFLOW.
4. Add a Sender (HTTP Adapter).
5. Add a Content Modifier step after the sender.
6. Add a Receiver (HTTP Adapter) for an external API.

🔹 Step 2: Configure Content Modifier

(A) Extract Order ID using Message Property

 Go to "Properties" tab
 Click Add Property
o Name: OrderID
o Type: XPath
o Value: /Order/ID

📝 This extracts the <ID> value from the incoming XML.

(B) Add a Custom Header for Transaction ID

 Go to "Headers" tab
 Click Add Header
o Name: Transaction-ID
o Type: Expression
o Value: ${date:now:yyyyMMddHHmmss}-${property.OrderID}

📝 This generates a unique transaction ID based on the timestamp and extracted Order ID.
(C) Modify the Message Body to JSON Format

 Go to "Body" tab
 Select Expression
 Enter the following JSON structure:

json
CopyEdit
{
"OrderID": "${property.OrderID}",
"Status": "Processing"
}

📝 This replaces the XML payload with JSON format.

🔹 Step 3: Configure Receiver HTTP Adapter

1. Select HTTP Receiver Adapter


2. Enter API URL (e.g., https://api.example.com/processOrder)
3. Set Method: POST
4. Enable Authentication if required
5. Use Content-Type: application/json

🔹 Step 4: Test the Integration Flow

🔸 Send Sample Input Payload (XML)

Use Postman or any API testing tool to send a request to your CPI IFlow endpoint:

xml
CopyEdit
<Order>
<ID>12345</ID>
<Amount>200.00</Amount>
</Order>

🔹 Step 5: Expected Output (Sent to API)


json
CopyEdit
{
"OrderID": "12345",
"Status": "Processing"
}

Headers Sent to API:

pgsql
CopyEdit
Transaction-ID: 20250205123045-12345
Content-Type: application/json

🎯 Key Learnings
✅ Extracting values using XPath in Message Properties
✅ Creating custom headers using Expressions
✅ Transforming XML to JSON using Content Modifier

🚀 Bonus Task
Modify the integration to include Amount in the JSON body dynamically. Try using ${in.body}
or another property!

Would you like me to generate a Groovy script alternative for this? 😊

You said:

yes
ChatGPT said:

Groovy Script Alternative for Content Modifier in SAP CPI 🚀

Instead of using a Content Modifier, we can achieve the same functionality using a Groovy
script in SAP CPI.

💡 Scenario Recap
1. Extract Order ID from the XML payload.
2. Generate a Transaction ID dynamically.
3. Convert the XML payload to JSON format.
4. Set the required headers before sending to the receiver.

🔹 Groovy Script Implementation


Add a Groovy Script step after the sender in your IFlow and use the following code:

groovy
CopyEdit
import com.sap.gateway.ip.core.customdev.util.Message
import java.text.SimpleDateFormat

def Message processData(Message message) {

// Get message body (XML payload)


def body = message.getBody(String)

// Extract Order ID using regex


def orderIdMatch = body =~ /<ID>(.*?)<\/ID>/
def orderId = orderIdMatch ? orderIdMatch[0][1] : "Unknown"

// Extract Amount using regex


def amountMatch = body =~ /<Amount>(.*?)<\/Amount>/
def amount = amountMatch ? amountMatch[0][1] : "0.00"

// Generate Transaction ID (current timestamp + Order ID)


def timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
def transactionId = "${timestamp}-${orderId}"

// Create JSON output


def jsonOutput = """
{
"OrderID": "${orderId}",
"Amount": "${amount}",
"Status": "Processing"
}
"""

// Set the JSON as the new message body


message.setBody(jsonOutput)

// Set headers
def headers = message.getHeaders()
headers.put("Transaction-ID", transactionId)
headers.put("Content-Type", "application/json")

return message
}
🔹 How This Works
✔ Extracts Order ID and Amount from XML using regex
✔ Generates a Transaction-ID using a timestamp and Order ID
✔ Converts XML to JSON format
✔ Sets custom headers before sending the message

🔹 Expected Output
✅ JSON Message Sent to Receiver

json
CopyEdit
{
"OrderID": "12345",
"Amount": "200.00",
"Status": "Processing"
}

✅ Headers Sent

pgsql
CopyEdit
Transaction-ID: 20250205123045-12345
Content-Type: application/json

🚀 Next Steps
Try modifying the script to:
✅ Include an additional field like OrderDate
✅ Use XPath instead of regex for XML extraction
✅ Handle missing values gracefully

Would you like an XPath-based version of this Groovy script? 😊

You said:

yes
ChatGPT said:
Groovy Script Alternative using XPath for XML Extraction 🚀

This version of the Groovy script extracts values using XPath, which is more reliable than regex
for structured XML data.

🔹 Groovy Script Using XPath


groovy
CopyEdit
import com.sap.gateway.ip.core.customdev.util.Message
import javax.xml.parsers.DocumentBuilderFactory
import java.text.SimpleDateFormat

def Message processData(Message message) {

// Get XML body as String


def xmlBody = message.getBody(String)

// Parse XML
def factory = DocumentBuilderFactory.newInstance()
factory.setNamespaceAware(true)
def builder = factory.newDocumentBuilder()
def inputStream = new ByteArrayInputStream(xmlBody.getBytes("UTF-8"))
def document = builder.parse(inputStream)

// Extract Order ID using XPath


def orderId = getXPathValue(document, "/Order/ID")
def amount = getXPathValue(document, "/Order/Amount")

// Generate Transaction ID (Timestamp + Order ID)


def timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
def transactionId = "${timestamp}-${orderId}"

// Create JSON Output


def jsonOutput = """
{
"OrderID": "${orderId}",
"Amount": "${amount}",
"Status": "Processing"
}
"""

// Set JSON as message body


message.setBody(jsonOutput)
// Set headers
def headers = message.getHeaders()
headers.put("Transaction-ID", transactionId)
headers.put("Content-Type", "application/json")

return message
}

// Function to extract values using XPath


def String getXPathValue(def document, String xpathExpression) {
def xpath = javax.xml.xpath.XPathFactory.newInstance().newXPath()
def value = xpath.evaluate(xpathExpression, document).trim()
return value ?: "N/A" // Default value if missing
}

🔹 How This Works


✔ Parses XML properly using DocumentBuilderFactory
✔ Uses XPath expressions (/Order/ID, /Order/Amount) to extract values
✔ Generates Transaction-ID dynamically
✔ Converts XML to JSON format
✔ Sets headers (Transaction-ID, Content-Type)

🔹 Expected Output
✅ JSON Message Sent to Receiver

json
CopyEdit
{
"OrderID": "12345",
"Amount": "200.00",
"Status": "Processing"
}

✅ Headers Sent

pgsql
CopyEdit
Transaction-ID: 20250205123045-12345
Content-Type: application/json

🚀 Next Steps
✅ Modify XPath to extract more fields like CustomerName
✅ Handle missing XML elements gracefully
✅ Log extracted values for debugging

Would you like me to extend this with error handling and logging? 😊

You said:

1
ChatGPT said:

Could you please clarify what you mean by "1"? Are you asking for:

✅ Error handling and logging in the Groovy script?


✅ More real-time scenarios using Content Modifier?
✅ Help with deploying and testing this in SAP CPI?

Let me know how I can assist you! 😊🚀

You said:

2
ChatGPT said:

More Real-Time Scenarios Using Content Modifier in SAP CPI 🚀

The Content Modifier in SAP CPI is widely used for handling headers, properties, and body
transformations. Below are three real-time scenarios demonstrating its practical applications.

🔹 Scenario 1: Adding Authentication Headers for API Calls


Use Case:
A REST API requires an OAuth token in the header before accepting requests.

Steps in CPI:

1. Fetch OAuth Token using a Request-Reply step.


2. Store the Token in a Message Property.
3. Use a Content Modifier to set the Authorization header dynamically.
4. Send the request to the target API.

Content Modifier Configuration:

 Properties Tab
o Name: AuthToken
o Type: Expression
o Value: ${property.OAuthResponse.token}
 Headers Tab
o Name: Authorization
o Type: Expression
o Value: Bearer ${property.AuthToken}

Expected API Call Header


makefile
CopyEdit
Authorization: Bearer eyJhbGciOiJIUzI1...

📌 Why? This ensures secure authentication for API requests.

🔹 Scenario 2: Enriching Messages with Additional Metadata


Use Case:

An order system sends raw XML without tracking information. The target system requires a
Tracking-ID.

Steps in CPI:

1. Extract Order ID using XPath.


2. Generate a Tracking ID (Timestamp + Order ID).
3. Modify the payload to include the Tracking-ID.

Content Modifier Configuration:


 Properties Tab
o Name: TrackingID
o Type: Expression
o Value: ${date:now:yyyyMMddHHmmss}-${property.OrderID}
 Body Tab (Modify Payload)

json
CopyEdit
{
"OrderID": "${property.OrderID}",
"Amount": "${property.Amount}",
"TrackingID": "${property.TrackingID}",
"Status": "Pending"
}

Expected Output
json
CopyEdit
{
"OrderID": "56789",
"Amount": "150.00",
"TrackingID": "20250205143030-56789",
"Status": "Pending"
}

📌 Why? This helps in tracking transactions for auditing.

🔹 Scenario 3: Dynamic Routing Based on Message


Properties
Use Case:

A company routes invoices to different ERP systems based on region (US, EU, Asia).

Steps in CPI:

1. Extract Country Code from payload (/Invoice/Country).


2. Store it in a Message Property.
3. Use a Router Step to direct invoices to the correct ERP system.

Content Modifier Configuration:

 Properties Tab
o Name: Region
o Type: XPath
o Value: /Invoice/Country

Router Configuration:

 If Region = 'US' → Route to ERP_US


 If Region = 'EU' → Route to ERP_EU
 If Region = 'Asia' → Route to ERP_Asia

📌 Why? This ensures invoices are sent to the correct backend ERP.

🚀 Summary of Learnings

✔ Scenario 1: Authentication Headers → Secure API calls


✔ Scenario 2: Metadata Enrichment → Adds tracking information
✔ Scenario 3: Dynamic Routing → Smart message processing

Would you like a Groovy script alternative for any of these scenarios? 😊

You said:

Help with deploying and testing this in SAP CPI?


ChatGPT said:

🚀 Deploying and Testing an SAP CPI Integration Flow with Content Modifier

This guide will help you deploy and test an SAP CPI integration flow that uses the Content
Modifier to modify headers, properties, and body.

🔹 Step 1: Deploying the Integration Flow


1️⃣ Open SAP Integration Suite (SAP CPI)

1. Log in to SAP Integration Suite:


🔗 SAP BTP Cockpit → Integration Suite
2. Navigate to Design → Integration Flows.
3. Select the integration flow (e.g., OrderProcessing_IFLOW).

2️⃣ Deploy the IFlow

1. Click Deploy.
2. Wait for the Status to change to Started.
3. Go to Monitor → Manage Integration Content and confirm that the IFlow is running.

🔹 Step 2: Testing the Integration Flow


1️⃣ Get the Endpoint URL

1. Navigate to Monitor → Manage Integration Content.


2. Search for your deployed IFlow.
3. Click on the IFlow and find the Endpoints section.
4. Copy the HTTPS endpoint URL (e.g., https://<your CPI
tenant>/http/orderProcessing).

2️⃣ Test Using Postman or CURL

You can test the integration flow using Postman or CURL.

✅ Test Using Postman

1. Open Postman.
2. Set the method to POST.
3. Paste the Endpoint URL.
4. Go to Headers → Add:

pgsql
CopyEdit
Content-Type: application/xml

5. Go to Body → Choose raw → Paste XML:

xml
CopyEdit
<Order>
<ID>12345</ID>
<Amount>250.00</Amount>
</Order>
6. Click Send.

✅ Test Using CURL (Command Line)

bash
CopyEdit
curl -X POST "https://<your CPI tenant>/http/orderProcessing" \
-H "Content-Type: application/xml" \
-d '<Order><ID>12345</ID><Amount>250.00</Amount></Order>'

🔹 Step 3: Verify the Response


Expected Response (Modified JSON Output)
json
CopyEdit
{
"OrderID": "12345",
"Amount": "250.00",
"TrackingID": "20250205153045-12345",
"Status": "Processing"
}

Expected Headers (If Set in Content Modifier)


pgsql
CopyEdit
Transaction-ID: 20250205153045-12345
Content-Type: application/json

🔹 Step 4: Monitor Logs and Messages


1. Go to Monitor → Integration Message Monitoring
2. Look for your IFlow in Completed Messages.
3. Click on the message and check:
o Payload before/after Content Modifier
o Headers and Properties
o Errors (if any)

🔹 Debugging & Troubleshooting


Issue Possible Solution
No response or 404 error Check if IFlow is deployed and running
Wrong data in response Verify XPath or Expressions in Content Modifier
API rejects request Ensure headers are correctly set
Message stuck in Failed Check Error Logs in CPI Monitor

🚀 Next Steps

✅ Deploy another IFlow using different authentication mechanisms (OAuth, Basic Auth)
✅ Implement a Retry Mechanism using Exception Subprocess
✅ Automate testing with Postman collections

Would you like me to guide you through error handling or logging setup? 😊

You said:

yes
ChatGPT said:

🚀 Error Handling & Logging Setup in SAP CPI

Handling errors effectively in SAP CPI is crucial for troubleshooting and ensuring smooth
integrations. Below, we will cover:

✅ 1. Exception Handling in SAP CPI


✅ 2. Logging Errors with Groovy Script
✅ 3. Resending Failed Messages (Retry Mechanism)

🔹 1️⃣ Exception Handling in SAP CPI (Using Exception


Subprocess)
SAP CPI allows error handling using Exception Subprocesses. This ensures that any failure in
the main process is caught and handled separately.

📌 Steps to Add Exception Handling in Your IFlow


1️⃣ Open your Integration Flow (IFlow) in SAP CPI.
2️⃣ Click on Exception Subprocess from the Palette.
3️⃣ Connect the Exception Subprocess to the main flow.
4️⃣Inside the Exception Subprocess, add:

 Message Logger (to log error messages)


 Groovy Script (to capture error details)
 Error End Event (to terminate the process)

🔹 2️⃣ Logging Errors Using Groovy Script

You can use a Groovy script to capture error details and log them for debugging.

📌 Groovy Script to Log Errors

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

def Message processData(Message message) {


def headers = message.getHeaders()
def properties = message.getProperties()

// Capture Error Message


def errorText = properties.get("SAP_ErrorText") ?: "Unknown error"
def errorCategory = properties.get("SAP_ErrorCategory") ?: "General"
def errorCode = properties.get("SAP_ErrorCode") ?: "NoCode"

// Log Error Details


def logMessage = """
ERROR OCCURRED:
-----------------
Error Code: ${errorCode}
Error Category: ${errorCategory}
Error Text: ${errorText}
"""

// Print log (SAP CPI will capture this in Monitoring)


message.setBody(logMessage)
return message
}

📌 How to Use This Script in CPI?

1️⃣ Add a Groovy Script step inside the Exception Subprocess.


2️⃣ Copy & Paste the script above.
3️⃣Deploy the IFlow.
📌 What This Does:

 Captures SAP CPI error properties (ErrorText, ErrorCode, Category).


 Logs them in CPI Monitor under Message Processing Logs.

🔹 3️⃣ Retry Mechanism: Resending Failed Messages

If a message fails due to a temporary issue (e.g., API downtime), you can automatically retry
before failing completely.

📌 Steps to Implement Retry Mechanism

1. Add a General Exception Handler


o Use an Exception Subprocess in the IFlow.
2. Use a Timer to Wait Before Retrying
o Add a Timer step (e.g., Wait 5 seconds before retrying).
3. Use a Loop (Parallel Multicast) to Retry X Times
o Route the message back to the HTTP request after a delay.
4. If Max Retries Exceeded, Log the Error
o Use the Groovy script above to log the failure.

📌 Tip: You can also store the error message in a Data Store and manually reprocess it later.

🔹 How to Monitor & Debug Errors in SAP CPI?


1️⃣ Go to Monitor → Integration Message Monitoring
2️⃣ Check the Failed Messages tab
3️⃣ Click on a failed message to see:

 Error Details
 Payload Before Failure
 Exception Stack Trace
4️⃣ Use Resend Feature to manually retry a failed message.

🚀 Next Steps

✅ Enhance Logging → Store logs in an external system (e.g., SAP BTP, Cloud Storage).
✅ Alert Mechanisms → Send email alerts when critical errors occur.
✅ Retry Logic → Implement an Exponential Backoff retry strategy.
Would you like help with email notifications for error alerts? 😊

You said:

Would you like a Groovy script alternative for any of these scenarios?
ChatGPT said:

🚀 Groovy Script Alternatives for SAP CPI Scenarios

Below are Groovy script alternatives for common Content Modifier use cases in SAP CPI.

1️⃣ Alternative for Setting Headers (OAuth Token


Authentication)
Instead of using a Content Modifier, use a Groovy script to set headers dynamically for
authentication.

📌 Scenario: Setting an OAuth Bearer Token in Headers


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

def Message processData(Message message) {


// Simulate fetching OAuth Token (normally retrieved from an API response)
def authToken = "eyJhbGciOiJIUzI1NiIsInR5cCI..."

// Set the Authorization header


message.setHeader("Authorization", "Bearer " + authToken)

// Set Content-Type header


message.setHeader("Content-Type", "application/json")

return message
}

📌 Why Use This?


✔ Useful when you retrieve the OAuth token dynamically.
✔ Ensures API authentication without Content Modifier.
2️⃣ Alternative for Message Enrichment (Adding a Tracking
ID)
Instead of using a Content Modifier, a Groovy script can dynamically extract values and
generate tracking IDs.

📌 Scenario: Extract Order ID & Add Tracking ID


groovy
CopyEdit
import com.sap.gateway.ip.core.customdev.util.Message
import java.text.SimpleDateFormat

def Message processData(Message message) {


// Get message body (XML Payload)
def body = message.getBody(String)

// Extract Order ID using regex


def orderIdMatch = body =~ /<ID>(.*?)<\/ID>/
def orderId = orderIdMatch ? orderIdMatch[0][1] : "Unknown"

// Generate Tracking ID (Timestamp + Order ID)


def timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())
def trackingId = "${timestamp}-${orderId}"

// Log tracking ID for debugging


message.setProperty("TrackingID", trackingId)
message.setHeader("Tracking-ID", trackingId)

return message
}

📌 Why Use This?


✔ Dynamically generates a unique tracking ID based on timestamp + Order ID.
✔ Stores the value as both a Message Property and Header.

3️⃣ Alternative for Dynamic Routing (Based on Country


Code)
Instead of using a Content Modifier + Router, a Groovy script can determine the target ERP
system dynamically.

📌 Scenario: Route Messages Based on Country Code


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

def Message processData(Message message) {


// Get the XML body
def body = message.getBody(String)

// Extract Country Code


def countryMatch = body =~ /<Country>(.*?)<\/Country>/
def countryCode = countryMatch ? countryMatch[0][1] : "Unknown"

// Determine target ERP system


def targetSystem = ""
switch (countryCode) {
case "US":
targetSystem = "ERP_US"
break
case "EU":
targetSystem = "ERP_EU"
break
case "Asia":
targetSystem = "ERP_Asia"
break
default:
targetSystem = "ERP_Default"
}

// Set target system as property


message.setProperty("TargetSystem", targetSystem)

return message
}

📌 Why Use This?


✔ Faster routing than a standard CPI Router.
✔ Easily expandable for new regions or conditions.

🚀 Summary: When to Use Groovy Instead of Content


Modifier?
Use Content
Scenario Use Groovy Script?
Modifier?
Static Headers (e.g., API Key) ✅ Yes ❌ No
Dynamic Headers (e.g., OAuth
❌ No ✅ Yes
Token)
Static Message Body Changes ✅ Yes ❌ No
Dynamic Payload Transformations ❌ No ✅ Yes
Use Content
Scenario Use Groovy Script?
Modifier?
XPath-Based Data Extraction ✅ Yes ✅ Yes (Groovy for complex logic)
Dynamic Routing ❌ No ✅ Yes

🚀 Next Steps

✅ Want a script for error handling and logging?


✅ Need a retry mechanism in case of failures?

Let me know how I can assist further! 😊🚀

You said:

Need a retry mechanism in case of failures?


ChatGPT said:

🚀 Implementing a Retry Mechanism in SAP


CPI
In SAP CPI, a retry mechanism ensures that messages automatically reattempt delivery when
a temporary failure occurs (e.g., API downtime, network issues). Below are three different
approaches:

✅ 1. Retry Using Exception Subprocess (No Code Required)


✅ 2. Retry Using Groovy Script (Custom Logic)
✅ 3. Retry Using JMS Queue (Best for Large Volumes)

🔹 1️⃣ Retry Using Exception Subprocess (No Code Required)


This method is ideal for simple retry logic where an external system fails temporarily.

📌 Steps to Implement:
1️⃣ Add an Exception Subprocess inside your Integration Flow (IFlow).
2️⃣ Inside the Exception Subprocess, add:

 Timer (Delay Before Retry) → Configure Retry Delay (e.g., 10 seconds)


 Reprocess Message (Send to Target Again)
 End Event (If Maximum Retries Exceeded, Stop Processing)

🔹 2️⃣ Retry Using Groovy Script (Custom Logic)


This method provides more control over retries using a Groovy script.

📌 Groovy Script for Retrying API Calls


groovy
CopyEdit
import com.sap.gateway.ip.core.customdev.util.Message
import java.net.HttpURLConnection
import java.net.URL

def Message processData(Message message) {


def maxRetries = 3 // Maximum retry attempts
def retryDelay = 5000 // Delay in milliseconds (5 seconds)

def apiUrl = "https://api.example.com/processOrder"


def payload = message.getBody(String)
def responseCode = 500 // Assume failure initially
def attempt = 0

while (attempt < maxRetries && responseCode >= 400) {


attempt++
try {
def url = new URL(apiUrl)
def connection = (HttpURLConnection) url.openConnection()
connection.setRequestMethod("POST")
connection.setRequestProperty("Content-Type", "application/json")
connection.setDoOutput(true)
connection.getOutputStream().write(payload.getBytes("UTF-8"))
connection.connect()

responseCode = connection.getResponseCode()

if (responseCode < 400) {


message.setBody("Success: Message processed on attempt $
{attempt}")
return message
}
} catch (Exception e) {
message.setProperty("RetryError", "Attempt ${attempt} failed: $
{e.message}")
}
if (attempt < maxRetries) {
Thread.sleep(retryDelay) // Wait before retrying
}
}

message.setBody("Error: Max retry attempts (${maxRetries}) reached. Last


response code: ${responseCode}")
return message
}

📌 How This Works

✔ Retries up to 3 times if the API returns an error.


✔ Waits 5 seconds before retrying (configurable).
✔ Stops retrying once the API responds successfully.

📌 When to Use?
✅ If you need dynamic retry attempts.
✅ If your retry logic depends on API response codes.

🔹 3️⃣ Retry Using JMS Queue (Best for Large Volumes)


For asynchronous processing, use a JMS queue to store messages temporarily and retry them
later.

📌 Steps to Implement:

1️⃣ Add a JMS Queue Adapter in the Exception Subprocess.


2️⃣ Set a Retry Interval (e.g., retry every 10 minutes).
3️⃣ Use another IFlow to process messages from the queue and resend them.

📌 When to Use?
✅ Best for high-volume messages that need guaranteed delivery.
✅ Ideal for longer retry intervals (e.g., retry after 30 minutes).

🚀 Which Retry Method Should You Choose?


Scenario Recommended Method
Short retry (1-2 attempts, < 10 sec) ✅ Exception Subprocess
Custom retry logic (based on response) ✅ Groovy Script
Large volumes, long retry delays ✅ JMS Queue
🚀 Next Steps

✅ Need help implementing a JMS Queue in SAP CPI?


✅ Want a retry mechanism for a specific use case?

You might also like