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

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.

Related

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]

Scatter gather routing error. Message payload is of type: String

I'm new to Mule and while working on a fairly simple Hello World example on Anypoint Studio to test out the Scatter/Gather flow control element, I'm getting the following error, without much else in the way of information:
ERROR 2014-12-19 22:00:30,172 [[unifinesb].connector.http.mule.default.receiver.02] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Exception was found for route(s): 0. Message payload is of type: String
Type : org.mule.routing.CompositeRoutingException
Code : MULE_ERROR--2
JavaDoc : http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/routing/CompositeRoutingException.html
Payload : /Waldo
********************************************************************************
Exception stack is:
1. Exception was found for route(s): 0. Message payload is of type: String (org.mule.routing.CompositeRoutingException)
org.mule.routing.CollectAllAggregationStrategy:51 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/routing/CompositeRoutingException.html)
********************************************************************************
Root Exception stack trace:
org.mule.routing.CompositeRoutingException: Exception was found for route(s): 0. Message payload is of type: String
at org.mule.routing.CollectAllAggregationStrategy.aggregateWithFailedRoutes(CollectAllAggregationStrategy.java:51)
at org.mule.routing.CollectAllAggregationStrategy.aggregate(CollectAllAggregationStrategy.java:38)
at org.mule.routing.ScatterGatherRouter.processResponses(ScatterGatherRouter.java:207)
at org.mule.routing.ScatterGatherRouter.process(ScatterGatherRouter.java:135)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
at org.mule.execution.MessageProcessorNotificationExecutionInterceptor.execute(MessageProcessorNotificationExecutionInterceptor.java:58)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor.execute(ExceptionToMessagingExceptionExecutionInterceptor.java:24)
at org.mule.execution.MessageProcessorExecutionTemplate.execute(MessageProcessorExecutionTemplate.java:44)
at ...
Judging from the top description of the error, I understand the problem to be that Scatter gather does not receive String payloads, even though the current documentation for the component mentions nothing of the sort. Is this correct?
The flow I'm running is fairly simple, receiving a String from an inbound http and trying to route it to a REST service that will use the String to print something (returning text/plain) and to a DB to store the String in a table. Relevant code follows:
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8084" doc:name="HTTP"/>
<expression-filter expression="#[payload != '/favicon.ico']" doc:name="Filter browser icon padding"/>
<logger message="current payload is #[payload]" level="INFO" doc:name="Startup log - to stdout"/>
<scatter-gather doc:name="Scatter-Gather">
<processor-chain>
<logger message="#['Rest branch msg input :' + payload]" level="DEBUG" doc:name="File Logger"/>
<http:outbound-endpoint exchange-pattern="request-response" method="POST" address="http://localhost:8080/application/rest/mensaje?givenName=#[payload]" doc:name="REST Service"/>
<logger message="#['Rest msg output :' + payload]" level="DEBUG" doc:name="File Logger"/>
</processor-chain>
<processor-chain>
<logger message="#['Database msg input :' + payload]" level="DEBUG" doc:name="File Logger"/>
<db:insert config-ref="MySQL_VestaLocal" doc:name="Application Postgress">
<db:parameterized-query><![CDATA[insert into http_user_info (first_name) values ('#[payload]');]]></db:parameterized-query>
</db:insert>
<logger message="#['Database msg output :' + payload]" level="DEBUG" doc:name="File Logger"/>
</processor-chain>
</scatter-gather>
<set-payload value="#['REST DB Success!']" doc:name="Set Payload"/>
Trawling through the net I found this old Mule JIRA issue with an exception similar to what I'm getting, but trying out the suggested solution (workaround?) didn't do anything for me: https://www.mulesoft.org/jira/browse/MULE-7594
Something wrong is happening in your route 0.
You are getting a composite routing exception as per documentation:
The CompositeRoutingException is new to the 3.5.0 Runtime. It extends
the Mule MessagingException to aggregate exceptions from different
routes in the context of a single message router. Exceptions are
correlated to each route through a sequential ID.
This exception exposes two methods which allow you to obtain the IDs
of failed routes and the exceptions returned by each route.
The getExceptions method returns a map where the key is an integer
that identifies the index of the failed route, and the value is the
exception itself. The getExceptionForRouteIndex(int) method returns
the exception of the requested route ID.
As you don't have an execption strategy, the toString is call to that exception and that only prints the route failing (that has nothing to do with the fact that the payload is String)
Please use the following exeption strategy to find out exactly what's wrong:
<catch-exception-strategy doc:name="Catch Exception Strategy">
<logger level="ERROR" message="#[exception.exceptions]"/>
</catch-exception-strategy>

Mule ESB: Object not of Correct Type Error when searching XML using XPATH

David,
Sending you my configuration again, appreciate your inputs in advance:
<flow name="IntegrationFlow" doc:name="IntegrationFlow">
<jdbc-ee:inbound-endpoint queryTimeout="-1" doc:name="Database" connector-ref="jdbcConnector" queryKey="selectAll" pollingFrequency="10000">
<jdbc-ee:transaction action="NONE"/>
</jdbc-ee:inbound-endpoint>
<logger message="************Payload is #[message.payload]*************" level="INFO" doc:name="Logger"/>
<logger message="************Payload is #[message.payload.destination]*************" level="INFO" doc:name="Logger"/>
<logger message="************Payload is #[message.payload.price]*************" level="INFO" doc:name="Logger"/>
<foreach doc:name="Foreach">
<choice doc:name="Choice">
<when expression="#[message.payload.price > 750]">
<!-- <when expression="#[message.payload.price > 750]"> -->
<processor-chain doc:name="Processor Chain">
<jdbc-ee:maps-to-xml-transformer doc:name="Maps to XML"/>
<jms:outbound-endpoint queue="queue1" connector-ref="jmsConnector" doc:name="JMS"/>
</processor-chain>
</when>
<otherwise>
<custom-transformer returnClass="java.util.List" class="org.mule.confluex.java.MapToListTransformer" doc:name="Java"/>
<logger message="Payload is #[message.payload]" level="INFO" doc:name="Logger1"/>
<jdbc-ee:maps-to-csv-transformer mimeType="text/plain" delimiter="," mappingFile="C:\Downloads\Temp\mapping.xml" doc:name="Maps to CSV"/>
<logger message="CSV Payload is #[message.payload]" level="INFO" doc:name="Logger2"/>
<file:outbound-endpoint path="C:\Downloads\toAmazon" responseTimeout="10000" mimeType="text/plain" connector-ref="fileConnector" doc:name="File"/>
<s3:create-object config-ref="Amazon_S3" bucketName="confluexdemo" contentType="text/plain" key="*.*" doc:name="Amazon S3"/>
</otherwise>
</choice>
</foreach>
</flow>
Here is the Run Log:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Started app 'ConfluexDemo' +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
INFO 2013-11-24 19:18:32,563 [[ConfluexDemo].IntegrationFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: ************Payload is {DESTINATION=SFO, PRICE=300, ID=0}*************
INFO 2013-11-24 19:18:32,563 [[ConfluexDemo].IntegrationFlow.stage1.03] org.mule.api.processor.LoggerMessageProcessor: ************Payload is {DESTINATION=MLT, PRICE=1200, ID=1}*************
INFO 2013-11-24 19:18:32,611 [[ConfluexDemo].IntegrationFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: ************Payload is SFO*************
INFO 2013-11-24 19:18:32,611 [[ConfluexDemo].IntegrationFlow.stage1.03] org.mule.api.processor.LoggerMessageProcessor: ************Payload is MLT*************
INFO 2013-11-24 19:18:32,658 [[ConfluexDemo].IntegrationFlow.stage1.03] org.mule.api.processor.LoggerMessageProcessor: ************Payload is 1200*************
INFO 2013-11-24 19:18:32,658 [[ConfluexDemo].IntegrationFlow.stage1.02] org.mule.api.processor.LoggerMessageProcessor: ************Payload is 300*************
ERROR 2013-11-24 19:18:32,704 [[ConfluexDemo].IntegrationFlow.stage1.03] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : Execution of the expression "message.payload.price > 750" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: String
Code : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. [Error: could not access: price; in class: java.lang.String]
[Near : {... message.payload.price > 750 ....}]
^
[Line: 1, Column: 1] (org.mvel2.PropertyAccessException)
org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer:690 (null)
2. Execution of the expression "message.payload.price > 750" failed. (org.mule.api.expression.ExpressionRuntimeException)
org.mule.el.mvel.MVELExpressionLanguage:213 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/expression/ExpressionRuntimeException.html)
3. Execution of the expression "message.payload.price > 750" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: String (org.mule.api.MessagingException)
org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:35 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
[Error: could not access: price; in class: java.lang.String]
[Near : {... message.payload.price > 750 ....}]
^
[Line: 1, Column: 1]
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getBeanProperty(ReflectiveAccessorOptimizer.java:690)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.getBeanPropertyAO(ReflectiveAccessorOptimizer.java:472)
at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.compileGetChain(ReflectiveAccessorOptimizer.java:374)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
From my perspective it looks like it is a Map Payload when I print it out, it seemingly seems to read a string when I hit the 'when expression. Hopefully this should give the complete picture. Please let me know if anything else is needed.
For the sake of completion I am also including the JDBC definition:
<spring:beans>
<spring:bean id="SetupDatabaseNotificationListener" class="org.mule.confluex.database.SetupDatabaseNotificationListener"></spring:bean>
<spring:bean id="jdbcDataSource" class="org.enhydra.jdbc.standard.StandardDataSource" destroy-method="shutdown">
<spring:property name="driverName" value="org.apache.derby.jdbc.EmbeddedDriver"></spring:property>
<spring:property name="url" value="jdbc:derby:memory:muleEmbeddedDB;create=true"></spring:property>
</spring:bean>
</spring:beans>
<notifications>
<notification event="CONTEXT"></notification>
<notification-listener ref="SetupDatabaseNotificationListener"></notification-listener>
</notifications>
<jdbc-ee:connector name="jdbcConnector" pollingFrequency="10000" dataSource-ref="jdbcDataSource" doc:name="Database" queryTimeout="-1" transactionPerMessage="false" validateConnections="true">
<jdbc-ee:query key="selectAll" value="Select * from PriceTickets"></jdbc-ee:query>
</jdbc-ee:connector>
With Regards
S
The error is clear: you are passing a String to the foreach processor instead of something that can be iterated (Iterator, Collection, etc.).

Mule: transform the results of outbound-endpoint

The following flow transforms incoming an JSON payload into a SOAP message which is used in a subflow to make a webservice request. Everything works fine -- i'm able to send a response back for the original (incoming) request, but I want to add a final step to transform the SOAP result into JSON before sending it back to the client.
Here is the flow:
<mule ...>
<data-mapper:config name="json2xml_grf" transformationGraphPath="json2xml.grf" doc:name="DataMapper"/>
<flow name="simpleFlow" doc:name="simpleFlow">
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="8081" doc:name="HTTP"/>
<set-property propertyName="Access-Control-Allow-Origin" value="*" doc:name="Property"/>
<choice doc:name="Choice">
<when expression="#[message.inboundProperties['http.method'] != 'OPTIONS']">
<data-mapper:transform config-ref="json2xml_grf" doc:name="DataMapper"/>
<flow-ref name="invokeCalculatorService" doc:name="invokeCalculator"/>
</when>
<otherwise>
<http:response-builder status="200" doc:name="HTTP Response Builder">
...
</http:response-builder>
</otherwise>
</choice>
</flow>
<flow name="invokeService" doc:name="invokeService">
<cxf:proxy-client payload="body" enableMuleSoapHeaders="true" doc:name="Proxy Client">
</cxf:proxy-client>
<mulexml:xslt-transformer maxIdleTransformers="2" maxActiveTransformers="5" xsl-file="/Users/jsleeuw/MuleStudio/workspace/calc/src/main/resources/transformsoap.xslt" doc:name="XSLT"/>
<http:outbound-endpoint exchange-pattern="request-response" doc:name="CalculatorService" method="POST" host="service-host" port="30001"/>
</flow>
</mule>
Putting a DataMapper at the end of the subflow like this:
...
<flow-ref name="invokeCalculatorService" doc:name="invokeCalculator"/>
<data-mapper:transform config-ref="xml2json_grf" doc:name="DataMapper"/>
...
Results in this error:
********************************************************************************
Message : Error executing graph: ERROR (com.mulesoft.mule.module.datamapper.api.exception.DataMapperExecutionException). Message payload is of type: DepthXMLStreamReader
Code : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. Content is not allowed in prolog. (org.xml.sax.SAXParseException)
org.apache.xerces.util.ErrorHandlerWrapper:-1 (null)
2. org.xml.sax.SAXParseException: Content is not allowed in prolog. (net.sf.saxon.trans.DynamicError)
net.sf.saxon.event.Sender:308 (null)
3. XPath evaluation failed (org.jetel.exception.JetelRuntimeException)
org.jetel.component.tree.reader.xml.XmlXPathEvaluator:81 (null)
4. Error executing graph: ERROR (com.mulesoft.mule.module.datamapper.api.exception.DataMapperExecutionException)
com.mulesoft.mule.module.datamapper.impl.DefaultGraphExecutor:83 (null)
5. Error executing graph: ERROR (com.mulesoft.mule.module.datamapper.api.exception.DataMapperExecutionException). Message payload is of type: DepthXMLStreamReader (com.mulesoft.mule.module.datamapper.processors.DataMapperMessageExecutionException)
com.mulesoft.mule.module.datamapper.processors.DataMapperMessageProcessor:135 (null)
--------------------------------------------------------------------------------
Whereas putting the datamapper at the end of the subflow ends up blocking the response.
How should I go about transforming my response?
From the Content is not allowed in prolog exception it seems that <flow-ref name="invokeCalculatorService" /> doesn't return a payload that is parseable as XML.
This sub-flow returns a org.apache.cxf.staxutils.DepthXMLStreamReader, which is an javax.xml.stream.XMLStreamReader. The only transformer I know of that can deserialize this type to an XML string is: <mulexml:dom-to-xml-transformer />.
Can you add one just before the data-mapper element?