elwis
elwis

Reputation: 1405

Substitute values in payload

I have an XML Message with two parameters in it which I use to call a REST service endpoint. However, if any of them are a certain value I would like to change them before my call, for example

<Interface Server="ABC" Server2="DEF"/>

If any of those have the value "ABC" it should always be replaced with "BC" and in my call to the REST service I would send param1="BC" and param2="DEF" in the above example. I was thinking of a Choice router and check if Server is "ABC" then set a flow-variable param1="BC" but then I realized I would have to do the same again for Server2 if that one is "ABC" ...and that feels like.. it must be an easier way to achieve this? Am I right? Could I use some clever MEL or XPATH3 expression to always substitue the values to "BC" if any of them are "ABC"?

Regards

Upvotes: 1

Views: 887

Answers (1)

sulthony h
sulthony h

Reputation: 1277

You can try the following configuration:

<enricher doc:name="Message Enricher">
    <dw:transform-message doc:name="Transform Message">
    <dw:set-payload><![CDATA[%dw 1.0
%output application/java
%var evaluation = "ABC"
%var substitution = "BC"
%function substitute(serverVal)(
    serverVal when serverVal != evaluation otherwise substitution
)
---
payload.Interface.@ mapObject {
    ($$): substitute($)
}
]]></dw:set-payload>
    </dw:transform-message>
    <enrich source="#[payload.Server]" target="#[variable:param1]"/>
    <enrich source="#[payload.Server2]" target="#[variable:param2]"/>
</enricher>

Regardless how many attribute in your XML source, you just need to add the enricher element accordingly.

For example, you have a new XML source: <Interface Server="ABC" Server2="DEF" Server3="ABC"/>

Then you only need to add: <enrich source="#[payload.Server3]" target="#[variable:param3]"/> to set the new variable.

Notes: DataWeave is one of the EE features. For CE, you can replace it with other transformer, for example: Groovy. In the example below, the payload is in form of String. The original application/xml format is transformed to String using byte-array-to-string-transformer.

<scripting:component doc:name="Groovy">
<scripting:script engine="Groovy"><![CDATA[def attributeMap = new XmlSlurper().parseText(payload).attributes()

attributeMap.each() {
    it.value = it.value == "ABC" ? "BC" : it.value
}

payload = attributeMap]]></scripting:script>
</scripting:component>

Upvotes: 2

Related Questions