How can I overwrite the payload in mule - mule

I've a Soap request coming into mule flow. Am tasked with getting information out of payload and depending on outcome, push the original request to different jms queues.
To get the desired information out of payload, I'm using XSLT tranformer (not XPath, because I need to get IDREF attribute from an element, based on IDREF, get the element and then a child element out of the IDREF object).
Based on the outcome of the of XSLT tranformation, I use choice element to push original payload. Am storing original payload in a Session (can do it in Inbound as well). After XSLT tansformation, apply choice router to find out appropriate queue, and then want to push the original payload into queue(original payload in stored in a session variable). I am using <expression-component> element. Below is the snippet of mule-flow:
<flow name="ProcessXML121Order">
<jms:inbound-endpoint queue="mviq.121.order" exchange-pattern="one-way" />
<logger message="121 order payload is #[payload]" level="INFO" />
<message-properties-transformer scope="session">
<add-message-property key="mviPayload" value="#[payload]"/>
</message-properties-transformer>
<xm:xslt-transformer xsl-file="chooseVendor.xslt" />
<logger message="After xsl file payload is #[payload]" level="INFO" />
<choice>
<when expression="'EMSI'">
<logger message="Vendor is EMSI" level="INFO" />
<expression-component>payload=#[header:SESSION:mviPayload]</expression-component>
<jms:outbound-endpoint queue="mviq.121.order.emsi" />
</when>
<when expression="'PRMD'">
<logger message="Vendor is PRMD" level="INFO" />
<jms:outbound-endpoint queue="mviq.121.order.prmd" />
</when>
<when expression="'RSA'">
<logger message="Vendor is RSA" level="INFO" />
<logger message="RSA payload is #[payload]" level="INFO" />
<jms:outbound-endpoint queue="mviq.121.order.rsa" />
</when>
<otherwise>
<logger message="Vendor is Error" level="INFO" />
<logger message="Vendor error payload is #[payload]" level="INFO" />
<jms:outbound-endpoint queue="mviq.error" />
</otherwise>
</choice>
</flow>
Following exception is thrown when evaluating payload=#[header:SESSION:mviPayload]
[ProcessXML121Order.stage1.02] exception.AbstractExceptionListener (AbstractExceptionListener.java:296) -
********************************************************************************
Message : Execution of the expression "payload=#[header:SESSION:mviPayload]" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: byte[]
Code : MULE_ERROR-29999
--------------------------------------------------------------------------------
Exception stack is:
1. [Error: illegal use of operator: +]
[Near : {... Unknown ....}]
^
[Line: 1, Column: 0] (org.mvel2.CompileException)
org.mvel2.ast.OperatorNode:46 (null)
2. Execution of the expression "payload=#[header:SESSION:mviPayload]" failed. (org.mule.api.expression.ExpressionRuntimeException)
org.mule.el.mvel.MVELExpressionLanguage:211 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/expression/ExpressionRuntimeException.html)
3. Execution of the expression "payload=#[header:SESSION:mviPayload]" failed. (org.mule.api.expression.ExpressionRuntimeException). Message payload is of type: byte[] (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: illegal use of operator: +]
[Near : {... Unknown ....}]
^
[Line: 1, Column: 0]
at org.mvel2.ast.OperatorNode.getReducedValueAccelerated(OperatorNode.java:46)
at org.mvel2.MVELRuntime.execute(MVELRuntime.java:85)
at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:105)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
I've 2 questions:
How can I overwrite the original payload? (Not saying this is the best way to go)
What is the better approach in this scenario? Is it advisable to keep original payload intact (in this case) and store XSLT output in other variable? How can I do that? What is the path (mule component) I can use to achieve that? I'm very new to Mule and seek community advice.
Thanks for your time looking into this.

Before answering your questions, let's rewrite this broken expression:
<expression-component>payload=#[header:SESSION:mviPayload]</expression-component>
as:
<set-payload value="#[sessionVars.mviPayload]" />
The following would work too but would be more complex for no good reason:
<expression-component>payload=sessionVars.mviPayload</expression-component>
Also this:
<message-properties-transformer scope="session">
<add-message-property key="mviPayload" value="#[payload]"/>
</message-properties-transformer>
would be better written:
<set-session-variable variableName="mviPayload" value="#[message.payload]" />
Now to your questions:
Use set-payload
What you are doing is the best: transformers, like XSL-T, applies naturally to the current message payload so saving the original in a property then transforming the main payload is OK. Just one thing: prefer a flow variable instead of a session variable. Indeed, in your case, I don't think you need the original payload outside this flow, so storing in session is overkill.
So I suggest you use:
<set-variable variableName="mviPayload" value="#[message.payload]" />
to store the original payload and the following to re-establish it:
<set-payload value="#[mviPayload]" />

Use Set-Payload and provide the data to be overwritten.

You could do this with lot of ways.
Use set-payload
Use expression, #[payload='']
Use an transformer/component

You can keep the payload intact and store the value of the xslt transformation in a variable using message enricher. Use the variable inside choice to determine which queue to go to. Below is a code snippet
<enricher doc:name="Message Enricher" target="#[flowVars.transformResultVar]">
<!--perform transformation logic here-->
</enricher>
Reference: https://dzone.com/articles/content-enrichment-using-mule-message-enricher-com

Related

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>

I want to Scatter the requests but not Gather results into single payload unlike how scatter-gather does in Mule

I have a flow like:
<flow name="Flow1">
<set-payload value="Important Message" />
<scatter-gather>
<choice doc:name="A">
<when expression="true">
//TODO
</when>
<otherwise>
//TODO
</otherwise>
</choice>
<flow-ref name="B" />
</scatter-gather>
<logger message="from flow-ref B: #[payload]" level="INFO" doc:name="response from B only"/>
</flow>
Right now the payload that comes out is an array of Payload;But I need only payload from response of B. I don't want to append java class to iterate over the payload to find B response.
I don't want the response from choice component but only from flow-ref B.
How to achieve this? Is this possible in an easy way using only mule components?
If I understand correctly, you want the payload "Important Message" to reach the flow-ref to B, and you also want the choice to occur?
Try getting rid of the scatter-gather and wrapping the choice router in an Async Scope instead.

How to capture an exception using the regex-filter filter in Mule ESB

Currently I have a flow that exposes a REST service with a string as input parameter . I am using a regex -filter to ensure the format parameter as follows :
<http:inbound-endpoint doc:name="HTTP"
connector-ref="ciuServiceHTTPConnector" ref="ciuServiceHTTPEndpoint"
exchange-pattern="request-response" />
<logger level="INFO" doc:name="Logger" message="epale1 #[payload]"/>
<regex-filter pattern="^/api/person/(V|E)[0-9]{8}$"
doc:name="Regex" />
<logger message="epale2 #[payload]" level="INFO" doc:name="Logger"/>
<jersey:resources doc:name="REST" >
<component class="...resource.CiudadanoResource"/>
</jersey:resources>
I need to send the customer a message "Invalid or missing parameter" . For this I use a choice-exception-strategy and catch-exception-strategy and then call a Subflow and perform http:response-builder.
How can I throw an exception(type) when the regex-filter do not match?. It is possible to incorporate this behavior or should I change my flow?
Thanks for your help;
Wrap it in a message-filter, like this:
<message-filter throwOnUnaccepted="true">
<regex-filter pattern="^/api/person/(V|E)[0-9]{8}$"
doc:name="Regex" />
</message-filter>
See the official documentation for further details:
Check the Throw On Unaccepted box to throw an exception if a message
or event is not handled. The default when not checked is to not throw
an exception.

Mule ESB problems with interceptor-stack

I'm new to Mule and having trouble with using interceptor-stack elements.
The following seems like it is taken right out of their documentation here: http://www.mulesoft.org/documentation/display/33X/Using+Interceptors
<interceptor-stack name="default">
<logging-interceptor/>
<timer-interceptor/>
</interceptor-stack>
<flow name="MyFlowFlow1" doc:name="MyFlowFlow1">
<interceptor-stack ref="default"/> <!--this is line 15 -->
<logger level="INFO" message="Got here"/>
</flow>
but I get an exception saying it's invalid.
Can someone tell me what I'm doing wrong?
org.xml.sax.SAXParseException; lineNumber: 15; columnNumber: 43; cvc-complex-type.2.4.a: Invalid content was found starting with element 'interceptor-stack'. One of '{"http://www.mulesoft.org/schema/mule/core":annotations, "http://www.mulesoft.org/schema/mule/core":description, "http://www.mulesoft.org/schema/mule/core":abstract-message-source, "http://www.mulesoft.org/schema/mule/core":abstract-inbound-endpoint, "http://www.mulesoft.org/schema/mule/core":abstract-message-processor, "http://www.mulesoft.org/schema/mule/core":abstract-outbound-endpoint, "http://www.mulesoft.org/schema/mule/core":abstract-mixed-content-message-processor, "http://www.mulesoft.org/schema/mule/core":response}' is expected.
at org.apache.xerces.util.ErrorHandlerWrapper.createSAXParseException(Unknown Source)
...etc...
EDIT - This is to address the responses below.
This first private flow works perfectly when invoked from another flow via flow-ref. I see the "got here" message and the timing.
<flow name="test2Flow1" doc:name="test2Flow1">
<timer-interceptor/>
<logger level="INFO" message="got here" doc:name="Logger"/>
</flow>
However, this second private flow does not work when invoked from another flow...in fact, it won't even parse. The only difference is that the explicit use of the timer-interceptor is changed to be a reference to an interceptor-stack containing the timer-interceptor.
<interceptor-stack name="default">
<timer-interceptor/>
</interceptor-stack>
<flow name="test2Flow1" doc:name="test2Flow1">
<interceptor-stack ref="default"/>
<logger level="INFO" message="got here" doc:name="Logger"/>
</flow>
I think your flow is invalid because it doesnt have a message processor.
Take a look on the anatomy of a flow.
http://www.mulesoft.org/documentation/display/current/Using+Flows+for+Service+Orchestration#UsingFlowsforServiceOrchestration-TheAnatomyofaFlow
Your message processor must be the first item in the flow
Interceptors are meant to be used within components.
This configuration should work:
<interceptor-stack name="default">
<logging-interceptor/>
<timer-interceptor/>
</interceptor-stack>
<flow name="test2Flow1" doc:name="test2Flow1">
<pooled-component class="com.MyComponent">
<interceptor-stack ref="default"/> <!--this is line 15 -->
</pooled-component>
<logger level="INFO" message="Got here"/>
</flow>

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?