cancel
Showing results for 
Search instead for 
Did you mean: 
Read only

Groovy Script in CPI Split a String on Payload

roberto_cardoso4
Discoverer
0 Likes
2,427

Dear Experts

I need help with groovy script wich receives json format as below:

I need to take a string inside the payload.

For example, there is my response on Json format.

I need to take the string between "code=" and "&". On this example i need to take

the string "ed53334e-2242-4560-af97-60a43532af63"

Any help ?

Thanks in Advance
Best Regards

Roberto

Accepted Solutions (1)

Accepted Solutions (1)

MortenWittrock
SAP Mentor
SAP Mentor

Hi Roberto

You need to do two things:

1) Parse the JSON object and extract the value of the "redirectUri" field.

2) Do some string processing to extract the code from the string you got in 1).

Number 1 can be solved with Groovy's JsonSlurper class. Number 2 can be solved with a regular expression.

Here is a bit of code that extracts the code and stores it in a property:

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

def Message processData(Message message) {
// Get the JSON payload.
def json = message.getBody(String)
// Parse the JSON object.
def jsonObject = new JsonSlurper().parseText(json)
// Extract the value of the "redirectUri" field.
def redirectUri = jsonObject.redirectUri
// Use a regular expression to match the code.
def matcher = redirectUri =~/code=([^&]+)/
// The result depends on whether or not the code is there.
def result = matcher.find() ? matcher.group(1) : "No code present"
// Store the result in a property.
message.setProperty("ExtractedCode", result)
// All done.
return message
}

The comments explain what's happening in each line.

If you know the code is always present, you can update the code to, for instance, fail the message, if the code is absent. You can experiment with it from here.

Have fun with CPI!

Regards,

Morten

roberto_cardoso4
Discoverer

Hi Morten

Thank so much for your help

Your code is very clear and the comments explain well

I implemented the code on Groovy Script and workd very well, so i can capture value in a properties

Thank you again, you save my weekend

I'm having a lot of fun with CPI... rss

Best Regards

Roberto

Ps: I have your book. Thanks a lot.

MortenWittrock
SAP Mentor
SAP Mentor
0 Likes

Hi roberto.cardoso4

I'm happy to hear that I could help save your weekend 🙂

All the best,

Morten

Answers (0)