Mule4 when expression failing for json array "contains" check - anypoint-studio

Working on Mule 3.9 to Mule 4.x migration work, API recieve json input payload as shown below, I am trying to check whether I have DFU string value existing in this array payload.sec_entities. Observed that in log statement condition check is working perfectly fine, see the log statement showing debug-8, debug-9, debug-10 below in Error logs. Question is it's not working same statement in when expression Can anyone suggest what is the issue with when expresion??
Tried with this, when expression fails:
<when expression="#[payload.sec_entities != null and payload.sec_entities contains 'DFU']">
Tried with this, even this when expression fails:
<when expression="#[%dw 2.0 output application/java --- payload.sec_entities != null and payload.sec_entities contains 'DFU' as String]">
Input payload:
{
"primary_entities": [
"DMDUNIT",
"LOC"
],
"sec_entities": [
"DFU",
"STOCK"
]
}
Code:
<flow name="Orchestrator-DFU-Flow">
<logger message="debug-8 expression check: payload.sec_entities: #[payload.sec_entities]"/>
<logger message="debug-9 expression check: payload.sec_entities not null check: #[payload.sec_entities != null]"/>
<logger message="debug-10 expression check: payload.sec_entities contains: #[payload.sec_entities contains 'DFU']"/>
<choice doc:name="Choice">
<when expression="#[%dw 2.0 output application/java --- payload.sec_entities != null and payload.sec_entities contains 'DFU' as String]">
<set-payload value="DFU" doc:name="Set Payload" />
<set-variable variableName="filterJson" value="#[%dw 2.0
import java!com::jda::cd::util::StringUtil
output application/json
---
StringUtil::getFilterExpression(vars.modifiedJsonInPayload, payload)]" doc:name="Set dfuFilterJson Session Variable" doc:id="8f20824e-b4eb-431c-a2e3-bdaf155f3367"/>
<set-variable variableName="entityMapForBatch" value='#[{"sec_entities":[payload]}]' doc:name="Variable - entityMapForBatch" doc:id="928fa7d9-b620-4e9f-9a30-caea11dd5d04"/>
<logger message="#['Posting Filter $(payload)']" level="INFO" doc:name="Log_DFU_Filter" />
<flow-ref name="Create_Batch" doc:name="Create_Batch" />
<flow-ref name="post_masterdata_to_messaging_system" doc:name="post_masterdata_to_messaging_system" />
</when>
<otherwise>
<logger level="INFO" doc:name="Logger" message="DFU flows will not be triggered." />
</otherwise>
</choice>
<error-handler ref="Global_Errorflow_Choice_Exception_Strategy" doc:name="Reference Exception Strategy" />
</flow>
Error logs:
INFO 2019-04-03 18:47:20,113 [[MuleRuntime].cpuLight.11: [jda-demand-adapter].Orchestrator-DFU-Flow.CPU_LITE #5011b8c6] [event: 0-cd4e4691-5612-11e9-ae40-0a0027000005] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: debug-8 expression check: payload.sec_entities: ["DFU","STOCK"]
INFO 2019-04-03 18:53:30,181 [[MuleRuntime].cpuLight.09: [jda-demand-adapter].Orchestrator-DFU-Flow.CPU_LITE #36218376] [event: 0-aaaca7c1-5613-11e9-ae40-0a0027000005] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: debug-9 expression check: payload.sec_entities not null check: true
INFO 2019-04-03 18:53:30,183 [[MuleRuntime].cpuLight.09: [jda-demand-adapter].Orchestrator-DFU-Flow.CPU_LITE #36218376] [event: 0-aaaca7c1-5613-11e9-ae40-0a0027000005] org.mule.runtime.core.internal.processor.LoggerMessageProcessor: debug-10 expression check: payload.sec_entities contains: true
ERROR 2019-04-03 18:53:30,187 [[MuleRuntime].cpuLight.09: [jda-demand-adapter].Orchestrator-DFU-Flow.CPU_LITE #36218376] [event: 0-aaaca7c1-5613-11e9-ae40-0a0027000005] org.mule.runtime.core.internal.exception.OnErrorContinueHandler:
********************************************************************************
Message : "Cannot coerce Array (["DFU", "STOCK"]) to Boolean
Trace:
at main (line: 1, column: 91)" evaluating expression: "%dw 2.0 output application/java --- payload.sec_entities != null and payload.sec_entities contains 'DFU' as String".
Error type : MULE:EXPRESSION
Element : Orchestrator-DFU-Flow/processors/3 # jda-demand-adapter:orchestrator-flow.xml:125 (Choice)
Element XML : <choice doc:name="Choice">
<when expression="#[%dw 2.0 output application/java --- payload.sec_entities != null and payload.sec_entities contains 'DFU' as String]">

Found the solution for above issue:
<when expression="#[output application/json
---
((payload.sec_entities != null) and (payload.sec_entities contains 'DFU'))]">

Related

How to retrieve elements in foreach loop in Mule4?

I have defined a variable to keep application/json collection.
My original payload contain following json block;
"amendments": {
"amendmentId": ["8a9a84b76b5a5a59016b687bae35012e",
"8a9a84b76b5a5a59016b6888e90e0144"]
}
<set-variable value="#[payload..amendmentId[1]]" doc:name="AmendmentIds" doc:id="03b6c46a-fc7b-43d4-b23a-502146ef0b13" variableName="amendmentids"/>
<logger level="INFO" doc:name="Logger" doc:id="6a1ad892-65f9-4dd2-9891-bdf3ad64c908" message="#[vars.amendmentids]" />
It prints as;
[
"8a9a84b76b5a5a59016b687bae35012e",
"8a9a84b76b5a5a59016b6888e90e0144"
]
Then I use ForEach loop to define few process logic for each Id,
Within foreach loop how I can get, each above id?
I used,vars.amendmentids[vars.counter]], but getting following error[1]
<foreach doc:name="For Each" doc:id="7b741315-aa28-4704-82f0-629c21d93853" collection="#[vars.amendmentids]">
<logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[vars.amendmentids[vars.counter]]"/>
</foreach>
[1]
Message : "Internal execution exception while executing the script, this is most probably a bug, file an issue with the script and the input data.
Caused by:
java.lang.RuntimeException: Unable to infer a output media type as more than one is being used: application/json,application/java please specify using: output <your mime-type> --- <expr>
at org.mule.weave.v2.el.MuleDataWeaveHelper$.inferImplicitOutput(MuleDataWeaveHelper.scala:69)
.............
" evaluating expression: "vars.amendmentids[vars.counter]".
Error type : MULE:EXPRESSION
I fixed it by defining output mime type like;
<logger level="INFO" doc:name="Logger" doc:id="049c3137-2f92-4077-8e3f-b26516cc5528" message="#[output application/java --- vars.amendmentids[vars.counter - 1]]"/>

Mule if flowVar used in Dataweave Transformer payload converted to Map

I have an issue with a Mule Dataweave Transformer getting an error, this only occurs if :-
An enricher is present wrapping a json:json-to-object-transformer
<enricher target="#[flowVars.myVar]" doc:name="Message Enricher">
<json:json-to-object-transformer returnClass="java.util.HashMap" doc:name="JSON to Object"/>
</enricher>
A flowVar is involved in the Dataweave Transformer
The exception occurs on the 2nd dataweave :-
ERROR 2017-08-15 09:09:52,239 [amqpReceiver.02] org.mule.exception.RollbackMessagingExceptionStrategy:
********************************************************************************
Message : Exception while executing:
{bar=1, foo=0}
^
Unexpected character 'b' at index 1 (line 1, position 2), expected '"'
Payload : com.mulesoft.weave.reader.ByteArraySeekableStream#39e7a0d3
Element : /subscribe-to-changeFlow4/processors/4 # voa-009-mule-authorisation-search-api:test3.xml:58 (Transform Message)
Element XML : <dw:transform-message doc:name="Transform Message">
<dw:input-payload mimeType="application/json"></dw:input-payload>
<dw:set-payload>%dw 1.0%output application/json---{field1: payload.foo,field2: payload.bar,field3: flowVars.myFlowVar}</dw:set-payload>
</dw:transform-message>
--------------------------------------------------------------------------------
Root Exception stack trace:
com.mulesoft.weave.reader.json.JsonReaderException: Unexpected character 'b' at index 1 (line 1, position 2), expected '"'
at com.mulesoft.weave.reader.json.JsonTokenizer.fail(JsonTokenizer.scala:193)
at com.mulesoft.weave.reader.json.JsonTokenizer.require(JsonTokenizer.scala:190)
at com.mulesoft.weave.reader.json.JsonTokenizer.readString(JsonTokenizer.scala:74)
at com.mulesoft.weave.reader.json.JsonTokenizer.readObjectMembers(JsonTokenizer.scala:146)
at com.mulesoft.weave.reader.json.JsonTokenizer.com$mulesoft$weave$reader$json$JsonTokenizer$$readObject(JsonTokenizer.scala:140)
at com.mulesoft.weave.reader.json.JsonTokenizer$$anonfun$readValue$1.apply$mcV$sp(JsonTokenizer.scala:37)
What happens is as soon as a flowVar is added into the 2nd data weave, then the payload seems to show as a Map rather than JSON.
The enricher with nested json-to-object-transformer is required to take a payload and allow the JSON to be accessed. If the enricher is removed it works fine
The seek(0) is required to reset the stream after the json-to-object-transformer as Answered in my last question
if the flowVar is removed from the 2nd dataweave it works fine
Test Case
<flow name="subscribe-to-changeFlow4" processingStrategy="synchronous">
<amqp:inbound-endpoint numberOfChannels="1" ref="authorisationChangeQueueDef4" responseTimeout="10000" doc:name="authorisation-change-consumer" />
<dw:transform-message doc:name="Transform Message">
<dw:set-payload>
<![CDATA[%dw 1.0
%output application/json
---
{
foo:0,
bar:1
}]]>
</dw:set-payload>
</dw:transform-message>
<enricher target="#[flowVars.myVar]" doc:name="Message Enricher">
<json:json-to-object-transformer returnClass="java.util.HashMap" doc:name="JSON to Object"/>
</enricher>
<expression-component doc:name="Expression">
<![CDATA[payload.seek(0);]]>
</expression-component>
<set-variable variableName="myFlowVar" value="1234" doc:name="Variable" />
<dw:transform-message doc:name="Transform Message">
<dw:input-payload mimeType="application/json"/>
<dw:set-payload>
<![CDATA[%dw 1.0
%output application/json
---
{
field1: payload.foo,
field2: payload.bar,
field3: flowVars.myFlowVar
}
]]>
</dw:set-payload>
</dw:transform-message>
<logger level="INFO" message="#[message.payloadAs(java.lang.String)]" doc:name="Logger all "/>
</flow>
This is probably a bug in Mule and you can raise it in Mule jira
Which Mule runtime version are you using?
I tested locally and found this issue with Mule runtime 3.8.0 and Mule runtime 3.8.1:
but worked fine with Mule runtime 3.8.2 and Mule 3.8.5
Also tested with Mule 3.7.3 locally and it worked fine as below:-
I had similar problem, the DW processor messes up the payload. So I added an Object-to-String before DW transformer and that worked fine.

Mule message.payload and payload

I have a Mule Expression Language expression:
<set-payload value="#[message.payload.hasNext() ? message.payload.next(): null]" doc:name="Set Payload"/>
<choice doc:name="Choice">
<when expression="#[message.payload != null]">
I am trying to iterate over a ConsumerIterator and am getting the error
Execution of the expression "message.payload.hasNext() ? message.payload.next(): null" failed. (org.mule.api.expression.ExpressionRuntimeException)
org.mule.el.mvel.MVELExpressionLanguage:202 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/expression/ExpressionRuntimeException.html)
6. Execution of the expression "message.payload.hasNext() ? message.payload.next(): null" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: ConsumerIterator (org.mule.api.transformer.TransformerMessagingException)
org.mule.transformer.AbstractTransformer:135 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerMessagingException.html)
My solution to this is to rewrite the code without the message. prefix:
<set-payload value="#[payload.hasNext() ? payload.next(): null]" doc:name="Set Payload"/>
<choice doc:name="Choice">
<when expression="#[payload is NullPayload]">
What is the difference between #[message.payload] and #[payload]?
If payload is an instance of NullPayload why doesn't payload.hasNext() throw an Exception?
From what I've read the best practice is to use #[message.payload] instead of #[payload].
I am using Mule 3.6.2.
There is no difference between message.payload and payload. Payload is a shortcut left there just for compatibility with Mule 2.
From time to time there is an issue here and there about a difference between one and the other, just small nuisances but in this case I believe you should try message.payload is NullPayload.
I solved the problem by assigning set-payload to false or an empty String instead of null:
<set-payload value="#[message.payload.hasNext() ? message.payload.next(): 'none']" doc:name="Set Payload"/>
Even assigning null is not valid in batch-steps process, it is better to assign some other String. Now I am able to use #[message.payload]:
<logger message="Query: #[message.payload]" level="INFO" doc:name="Logger"/>

Json to object and Mule expression

I have a json file which the link is https://gist.githubusercontent.com/Rajeun/b550fe17181610f5c0f0/raw/7ba82c6c1135d474e0bedc8b203d3cf16e196038/file.json
i want to do a test on the boolean "sent". there is my xml file.
<http:request-config name="HTTP_Request_Configuration"
host="gist.githubusercontent.com" port="443" protocol="HTTPS"
doc:name="HTTP Request Configuration" />
<flow name="testFlow">
<poll doc:name="Poll">
<http:request config-ref="HTTP_Request_Configuration"
path="Rajeun/b550fe17181610f5c0f0/raw/7ba82c6c1135d474e0bedc8b203d3cf16e196038/file.json"
method="GET" doc:name="HTTP" />
</poll>
<json:json-to-object-transformer
returnClass="java.lang.Object" doc:name="JSON to Object" />
<choice doc:name="Choice">
<when expression="#[payload.sent] == true )">
<logger message="its ok" level="INFO" doc:name="Logger"/>
</when>
<otherwise>
<logger message="Error" level="INFO" doc:name="Logger"/>
</otherwise>
</choice>
</flow>
errors:
ERROR 2015-03-25 16:29:59,871 [[push1].testFlow.stage1.02] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Failed to transform from "json" to "java.lang.Object"
Code : MULE_ERROR-109
--------------------------------------------------------------------------------
Exception stack is:
1. Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries
at [Source: java.io.InputStreamReader#1a09a5b; line: 5, column: 4] (org.codehaus.jackson.JsonParseException)
org.codehaus.jackson.JsonParser:1433 (null)
2. Failed to transform from "json" to "java.lang.Object" (org.mule.api.transformer.TransformerException)
org.mule.module.json.transformers.JsonToObject:132 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transformer/TransformerException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
org.codehaus.jackson.JsonParseException: Unexpected character ('"' (code 34)): was expecting comma to separate OBJECT entries
at [Source: java.io.InputStreamReader#1a09a5b; line: 5, column: 4]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1433)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:521)
at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:442)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
i don't know what is the problem please any help !!
The expression should be <when expression="#[payload.sent == true ]"> and this is working for me ..
also as afelisatti mentioned, there should be a comma after email attribute in JSON payload
There's is no comma after the "email" in that JSON file so the transformation fails, that's what the error message is saying. I believe the correct format would be
{
"token" : 123,
"tel" : 456,
"email" : "Rm9vYmFyIQ==",
"sent" : true
}
Remove
<json:json-to-object-transformer returnClass="java.lang.Object" doc:name="JSON to Object" />
and use an json based mule expression #[json:sent]

Mule ESB: Evaluating <choice-when> in mule using Expressions

I have the following expressiong in mule is this valid:
<choice doc:name="Choice">
<when expression="#[message.payload[0]['destination'] == 'SFO']">
<processor-chain doc:name="Processor Chain">
<request-reply timeout="5000">
<jms:outbound-endpoint connector-ref="jmsConnector" queue="Queue1"></jms:outbound-endpoint>
<jms:inbound-endpoint connector-ref="jmsConnector" queue="Queue2"></jms:inbound-endpoint>
</request-reply>
</processor-chain>
When I run this code I get the following error:
ERROR 2013-11-23 10:11:04,010 [[ConfluexDemo].ExpreFlow2.stage1.03] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Execution of the expression "message.payload[0]['destination'] == 'SFO'" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: CaseInsensitiveHashMap
Code : MULE_ERROR--2
--------------------------------------------------------------------------------
I am getting the input through the when by doing a Select all on a database table in derby.
With Regards
S
From the error message it seems that your payload is already a map and not an array.
You should use the expression
#[message.payload['destination'] == 'SFO']
directly.