Groovy Script
import groovy.xml.XmlSlurper
import groovy.xml.XmlUtil
import groovy.xml.StreamingMarkupBuilder
try {
def namespacePrefix = 'sch'
def namespaceUri = 'http://kurum.com/ws/some-func-ws/schemas'
def userName = request_usernameOrKey
// Parse XML using XmlSlurper and define namespaces
def rootNode = new XmlSlurper(false, true).parseText(requestBodyTextFromClient).declareNamespace(
'soapenv': 'http://schemas.xmlsoap.org/soap/envelope/',
'sch': 'http://kurum.com/ws/some-func-ws/schemas'
)
// Check if Header section exists, create if not
def headerNode = rootNode.'soapenv:Header'
if (!headerNode) {
headerNode = rootNode.appendNode { 'soapenv:Header' {} }
}
// Create and add userId element
def userIdNode = new XmlSlurper(false, true).parseText("<${namespacePrefix}:userId xmlns:${namespacePrefix}='${namespaceUri}'>${userName}</${namespacePrefix}:userId>")
headerNode.appendNode { mkp.yield userIdNode }
// Serialize updated XML as string
def outputXml = XmlUtil.serialize(new StreamingMarkupBuilder().bind {
mkp.declareNamespace('soapenv': 'http://schemas.xmlsoap.org/soap/envelope/', 'sch': 'http://kurum.com/ws/some-func-ws/schemas')
mkp.yield rootNode
})
requestBodyTextToTargetAPI = outputXml
} catch (Exception e) {
e.printStackTrace()
}
Explanation
This script performs the following operations:
- XML Parse: XML data coming from request body is parsed
- Header Check: Checks if SOAP Header field exists, creates if not
- Username Retrieval: Username information from authentication is retrieved
- Adding to Header: Username information is added to Header field
- Sending to Backend: Updated XML is sent to backend
This script should be run on the request line (Request Policy) because it uses the requestBodyTextFromClient and requestBodyTextToTargetAPI variables.