Mule scatter-gather router throwing exception - mule

I was exploring Mule scatter-gather for parallel processing of flows in Mule fork and join pattern. My Mule config is as follows:
<flow name="fork" doc:name="fork">
<http:inbound-endpoint host="localhost" port="8090" path="mainPath" exchange-pattern="request-response" doc:name="HTTP"/>
<set-property propertyName="MULE_CORRELATION_GROUP_SIZE" value="2" doc:name="Property"/>
<!-- <all enableCorrelation="IF_NOT_SET" doc:name="All"> -->
<scatter-gather timeout="6000">
<processor-chain>
<async doc:name="Async">
<set-property propertyName="MULE_CORRELATION_SEQUENCE" value="1" doc:name="Property"/>
<flow-ref name="Flow1" doc:name="Flow Reference"/>
</async>
</processor-chain>
<async doc:name="Async">
<set-property propertyName="MULE_CORRELATION_SEQUENCE" value="2" doc:name="Property"/>
<flow-ref name="Flow2" doc:name="Flow Reference"/>
</async>
<!-- </all> -->
</scatter-gather>
<logger message="Main Flow" level="INFO" doc:name="Logger"/>
</flow>
<sub-flow name="Flow1" doc:name="Flow1">
<logger level="INFO" message="Flow1: processing started" doc:name="Logger"/>
<set-payload value="Flow1 Payload" doc:name="Set Payload"/>
<!-- Transformation payload -->
<logger level="INFO" message="Flow1: processing finished" doc:name="Logger"/>
<flow-ref name="Join-Flow" doc:name="Flow Reference"/>
</sub-flow>
<sub-flow name="Flow2" doc:name="Flow2">
<logger level="INFO" message="Flow2: processing started" doc:name="Logger"/>
<set-payload value="Flow2 Payload" doc:name="Set Payload"/>
<scripting:component doc:name="Groovy">
<scripting:script engine="Groovy"><![CDATA[sleep(2000); return message.payload;]]></scripting:script>
</scripting:component>
<!-- Transformation payload -->
<logger level="INFO" message="Flow2: processing finished" doc:name="Logger"/>
<flow-ref name="Join-Flow" doc:name="Flow Reference"/>
</sub-flow>
<sub-flow name="Join-Flow" doc:name="Join-Flow">
<collection-aggregator timeout="6000" failOnTimeout="true" doc:name="Collection Aggregator"/>
<combine-collections-transformer doc:name="Combine Collections"/>
<logger level="INFO" message="Combined Payload: #[message.payload]" doc:name="Logger"/>
<set-payload value="Soap XML Response" doc:name="Set Payload"/>
</sub-flow>
The scatter and gather is throwing following exception though I am getting the aggregated Payload in Logger:
Exception stack is:
1. null (java.lang.UnsupportedOperationException)
org.mule.VoidMuleEvent:50 (null)
2. null (java.lang.UnsupportedOperationException). Message payload is of type: String (org.mule.api.MessagingException)
org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:32 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.lang.UnsupportedOperationException
at org.mule.VoidMuleEvent.getMessage(VoidMuleEvent.java:50)
at org.mule.api.routing.AggregationContext$1.evaluate(AggregationContext.java:41)
at org.apache.commons.collections.CollectionUtils.select(CollectionUtils.java:517)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
INFO 2014-08-17 18:04:52,008 [[try1].fork.2.02] org.mule.api.processor.LoggerMessageProcessor: Flow2: processing started
INFO 2014-08-17 18:04:52,016 [[try1].fork.1.02] org.mule.api.processor.LoggerMessageProcessor: Flow1: processing started
INFO 2014-08-17 18:04:52,017 [[try1].fork.1.02] org.mule.api.processor.LoggerMessageProcessor: Flow1: processing finished
INFO 2014-08-17 18:04:54,309 [[try1].fork.2.02] org.mule.api.processor.LoggerMessageProcessor: Flow2: processing finished
INFO 2014-08-17 18:04:54,347 [[try1].fork.2.02] org.mule.api.processor.LoggerMessageProcessor: Combined Payload: [Flow1 Payload, Flow2 Payload]
One interesting fact is that if I use <all> router instead of scatter-gather, I don't get this exception. but I guess <all> router process the flows sequentially and not in parallel as per Mule documentation. So for that reason I tried to choose scatter-gather over all router. But I am not sure how to handle the above exception thrown by the scatter-gather. Is there any way out?
UPDATED FLOW :-
<flow name="fork" doc:name="fork">
<http:inbound-endpoint host="localhost" port="8090" path="mainPath" exchange-pattern="request-response" doc:name="HTTP"/>
<scatter-gather timeout="6000">
<processor-chain>
<flow-ref name="Flow1" doc:name="Flow Reference"/>
</processor-chain>
<flow-ref name="Flow2" doc:name="Flow Reference"/>
</scatter-gather>
<logger message="Main Flow" level="INFO" doc:name="Logger"/>
</flow>
<sub-flow name="Flow1" doc:name="Flow1">
<logger level="INFO" message="Flow1: processing started" doc:name="Logger"/>
<set-payload value="Flow1 Payload" doc:name="Set Payload"/>
<!-- Transformation payload -->
<logger level="INFO" message="Flow1: processing finished" doc:name="Logger"/>
<flow-ref name="Join-Flow" doc:name="Flow Reference"/>
</sub-flow>
<sub-flow name="Flow2" doc:name="Flow2">
<logger level="INFO" message="Flow2: processing started" doc:name="Logger"/>
<set-payload value="Flow2 Payload" doc:name="Set Payload"/>
<scripting:component doc:name="Groovy">
<scripting:script engine="Groovy"><![CDATA[sleep(2000); return message.payload;]]>
</scripting:script>
</scripting:component>
<!-- Transformation payload -->
<logger level="INFO" message="Flow2: processing finished" doc:name="Logger"/>
<flow-ref name="Join-Flow" doc:name="Flow Reference"/>
</sub-flow>
<sub-flow name="Join-Flow" doc:name="Join-Flow">
<collection-aggregator timeout="6000" failOnTimeout="true" doc:name="Collection Aggregator"/>
<combine-collections-transformer doc:name="Combine Collections"/>
<logger level="INFO" message="Combined Payload: #[message.payload]" doc:name="Logger"/>
<set-payload value="Soap XML Response" doc:name="Set Payload"/>
</sub-flow>
EXCEPTION :-
[try1].ScatterGatherWorkManager.02] org.mule.api.processor.LoggerMessageProcessor: Flow2: processing started
INFO 2014-08-18 13:34:24,361 [[try1].ScatterGatherWorkManager.01] org.mule.api.processor.LoggerMessageProcessor: Flow1: processing started
INFO 2014-08-18 13:34:24,364 [[try1].ScatterGatherWorkManager.01] org.mule.api.processor.LoggerMessageProcessor: Flow1: processing finished
WARN 2014-08-18 13:34:24,366 [[try1].ScatterGatherWorkManager.01] org.mule.routing.correlation.CollectionCorrelatorCallback: Correlation Group Size not set, but correlation aggregator is being used. Message is being forwarded as is
INFO 2014-08-18 13:34:24,401 [[try1].ScatterGatherWorkManager.01] org.mule.api.processor.LoggerMessageProcessor: Combined Payload: [Flow1 Payload]
INFO 2014-08-18 13:34:26,615 [[try1].ScatterGatherWorkManager.02] org.mule.api.processor.LoggerMessageProcessor: Flow2: processing finished
ERROR 2014-08-18 13:34:26,625 [[try1].connector.http.mule.default.receiver.03] org.mule.exception.DefaultMessagingExceptionStrategy:
********************************************************************************
Message : null (java.lang.NullPointerException). Message payload is of type: String
Code : MULE_ERROR--2
--------------------------------------------------------------------------------
Exception stack is:
1. null (java.lang.NullPointerException)
org.mule.api.routing.AggregationContext$1:41 (null)
2. null (java.lang.NullPointerException). Message payload is of type: String (org.mule.api.MessagingException)
org.mule.execution.ExceptionToMessagingExceptionExecutionInterceptor:32 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/MessagingException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.lang.NullPointerException
at org.mule.api.routing.AggregationContext$1.evaluate(AggregationContext.java:41)
at org.apache.commons.collections.CollectionUtils.select(CollectionUtils.java:517)
at org.apache.commons.collections.CollectionUtils.select(CollectionUtils.java:498)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
Now as you can see it's not combining the both payload of both flow after removing the set-property ..... It is getting only payload of first flow :- Combined Payload: [Flow1 Payload] ..

Remove the async scope around the message processors in the scatter-gather, which indeed does the parallelization for you so you don't have to.
EDIT: Also remove the set-property message processors that deal with the MULE_CORRELATION properties. The scatter-gather is supposed to do that for you.
EDIT2: You can remove the processor-chain around the single flow-ref: it's useless.
Also, there seem to be a deep misunderstanding about what scatter-gather does: you forcefully make its sub-flow responses converge to a single Join-Flow where you aggregate stuff, effectively by-passing and re-implementing all what the scatter-gather proposes to do for you.
Remove the flow-refs towards Join-Flow, remove Join-Flow and just put its processing logic (not the aggregator) after the scatter-gather.

So as per David's suggestion the final working solution is :-
<flow name="fork" doc:name="fork">
<http:inbound-endpoint host="localhost" port="8090" path="scattergather" exchange-pattern="request-response" doc:name="HTTP"/>
<scatter-gather timeout="6000">
<!-- Calling Flow1 -->
<flow-ref name="Flow1" doc:name="Flow Reference"/>
<!-- Calling Flow2 -->
<flow-ref name="Flow2" doc:name="Flow Reference"/>
</scatter-gather>
<!-- <collection-aggregator timeout="6000" failOnTimeout="true" doc:name="Collection Aggregator"/>
<combine-collections-transformer doc:name="Combine Collections"/> -->
<logger level="INFO" message="Combined Payload: #[message.payload]" doc:name="Logger"/>
<logger level="INFO" message="Payload1: #[message.payload[0]] and Payload2: #[message.payload[1]] " doc:name="Logger"/>
<set-payload value="Done Merging ...!!!" doc:name="Set Payload"/>
<logger message="Back to Main Flow" level="INFO" doc:name="Logger"/>
</flow>
<sub-flow name="Flow1" doc:name="Flow1">
<logger level="INFO" message="Flow1: processing started" doc:name="Logger"/>
<set-payload value="Flow1 Payload" doc:name="Set Payload"/>
<logger level="INFO" message="Flow1: processing finished" doc:name="Logger"/>
</sub-flow>
<sub-flow name="Flow2" doc:name="Flow2">
<logger level="INFO" message="Flow2: processing started" doc:name="Logger"/>
<!-- Sleep function to delay the flow2 payload -->
<set-payload value="Flow2 Payload" doc:name="Set Payload"/>
<scripting:component doc:name="Groovy">
<scripting:script engine="Groovy"><![CDATA[sleep(3000); return message.payload;]]></scripting:script>
</scripting:component>
<logger level="INFO" message="Flow2: processing finished" doc:name="Logger"/>
</sub-flow>
</mule>

Related

Anypoint mule: CopyOnArraylist in output while writing to file with scatter-gather element

The problem statement is to do multiple things parallely and aggregate the response and store it in a file.
link to the mule flow image as in studio:
image
In this flow, what I was trying to do was to set two constant strings in two branches of scatter and gather and aggregate and store in file. I tried overwriting the payload with a "set payload" with "my response". I am expecting "my response" as the content of the file. But instead the file content is:
¨Ìsr)java.util.concurrent.CopyOnWriteArrayListx]ü’F´ê√xpwtmsg 1tmsg 2x
I did debug and the payload at File endpoint was "my response". How and why is the collection getting written into file.
Can anyone help me to get it working.
Following is the xml:
<flow name="mule-assignFlow21123">
<quartz:inbound-endpoint jobName="dummyflow" repeatInterval="10000" responseTimeout="10000" doc:name="Quartz">
<quartz:event-generator-job/>
</quartz:inbound-endpoint>
<scatter-gather doc:name="Scatter-Gather1" >
<threading-profile maxThreadsActive="1" poolExhaustedAction="RUN"/>
<processor-chain>
<set-payload value="msg 1" doc:name="Set Payload"/>
<logger level="INFO" doc:name="Logger"/>
</processor-chain>
<processor-chain>
<set-payload value="msg 2" doc:name="Set Payload"/>
<logger level="INFO" doc:name="Logger"/>
</processor-chain>
</scatter-gather>
<set-payload value="my response" doc:name="Set Payload"/>
<file:outbound-endpoint path="/Users/premkumar/Desktop" outputPattern="Results.txt" responseTimeout="10000" mimeType="text/plain" doc:name="Save 2 File"/>
</flow>
The flow will automatically determine the processingStrategy from the in-flight event which will be async because of the quartz endpoint, so the file endpoint will fire async also.
Instead explicitly set the flow's processingStrategy to synchronous:
<flow name="mule-assignFlow21123" processingStrategy="synchronous">
<quartz:inbound-endpoint jobName="dummyflow" repeatInterval="10000" responseTimeout="10000" doc:name="Quartz">
<quartz:event-generator-job/>
</quartz:inbound-endpoint>
<scatter-gather doc:name="Scatter-Gather1" >
<threading-profile maxThreadsActive="1" poolExhaustedAction="RUN"/>
<processor-chain>
<set-payload value="msg 1" doc:name="Set Payload"/>
<logger level="INFO" doc:name="Logger"/>
</processor-chain>
<processor-chain>
<set-payload value="msg 2" doc:name="Set Payload"/>
<logger level="INFO" doc:name="Logger"/>
</processor-chain>
</scatter-gather>
<set-payload value="my response" doc:name="Set Payload"/>
<file:outbound-endpoint path="/Users/premkumar/Desktop" outputPattern="Results.txt" responseTimeout="10000" mimeType="text/plain" doc:name="Save 2 File"/>

Mule Flow not able to invoke exception strategy

I have following Code for my Mule FLOW and seems like something is wrong with my code which is not allowing to invoke Catch Exception Strategy, What are the corrections required here ?
<flow name="Mule_Common_FTP_EDI_FilesProcessing_Inbound" doc:name="Mule_Common_FTP_EDI_FilesProcessing_Inbound"
processingStrategy="synchronous">
<quartz:inbound-endpoint cronExpression="${ftp.edi.inbound.cronExpression}" responseTimeout="${ftp.edi.inbound.root.responseTimeout}" jobName="pollingFTPFiles" doc:name="Quartz" connector-ref="pollingFTPFilesConnector">
<quartz:event-generator-job/>
</quartz:inbound-endpoint>
<set-payload value="#[[${ftp.edi.inbound.carriers.path}]]" doc:name="Set Payload"/>
<foreach doc:name="For Each">
<flow-ref name="Initialise-logging-variables" doc:name="Flow Reference"/>
<set-variable value="#[payload]" variableName="processing_folder_path" doc:name="Variable processing_folder_path" />
<mulerequester:request config-ref="FTP_Requester" resource="ftp://${ftp.edi.inbound.root.user}:${ftp.edi.inbound.root.password}#${ftp.edi.inbound.root.host}:${ftp.edi.inbound.root.port}${ftp.edi.inbound.root.path}#[payload]" timeout="${ftp.edi.inbound.root.responseTimeout}" doc:name="Mule Requester"/>
<choice doc:name="Choice">
<when expression="#[message.payload != null]">
<set-variable variableName="careerName" value="#[groovy:String s = flowVars.processing_folder_path; s.substring(0,s.indexOf('-'))]" doc:name="Variable careerName"/>
<set-variable variableName="filename" value="#[variable:careerName]-_#[message.outboundProperties['originalFilename']]" doc:name="Variable filename"/>
<file:file-to-string-transformer doc:name="File to String"/>
<set-variable variableName="InputPayload" value="#[payload:]" doc:name="Variable InputPayload"/>
<choice doc:name="Choice">
<when expression="#[regex(app.registry.configProperties[careerName])]">
<scripting:component doc:name="Script">
<scripting:script engine="Groovy" file="generateWSRequest.groovy"/>
</scripting:component>
<message-properties-transformer doc:name="Message Properties">
<add-message-property key="SOAPAction" value="/ProcessService/PDoc"/>
</message-properties-transformer>
<http:outbound-endpoint exchange-pattern="request-response" host="${http.host}" port="${http.port}" path="yourservices/service.svc" responseTimeout="${http.timeout.sync}" contentType="text/xml" connector-ref="httpConnector" doc:name="HTTP"/>
<byte-array-to-string-transformer doc:name="Byte Array to String"/>
<set-variable value="#[message.payload.toString()]" variableName="OutputPayload" doc:name="Variable"/>
<choice doc:name="Choice">
<when expression="message.getInboundProperty('http.status') == '200'" evaluator="groovy">
<set-payload value="#[variable:InputPayload]" doc:name="Set Payload"/>
<file:outbound-endpoint path="${ftp.edi.outbound.root.success.path}" outputPattern="#[variable:filename]" responseTimeout="10000" doc:name="File"/>
<set-payload value="#[variable:InputPayload]" doc:name="Set Payload"/>
<ftp:outbound-endpoint host="${ftp.edi.inbound.root.host}" port="${ftp.edi.inbound.root.port}" path="${ftp.edi.elementum.copy.path}" user="${ftp.edi.inbound.root.user}" password="${ftp.edi.inbound.root.password}" outputPattern="#[message.outboundProperties['originalFilename']]" mimeType="text/plain" doc:name="FTP"/>
</when>
<otherwise>
<set-payload value="#[variable:InputPayload]" doc:name="Set Payload"/>
<set-variable variableName="original_message" value="#[groovy:message.toString()]" doc:name="original_message" />
<set-attachment attachmentName="#[message.outboundProperties['originalFilename']]" value="#[payload]" contentType="text/xml" doc:name="originalFileAttachment"/>
<set-variable variableName="content" value="${smtp.service.failure.body}, Splunk txId=#[sessionVars.logTxid] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:logErrmsg] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:original_message] #[System.getProperty('line.separator')]" doc:name="EmailBodyContent" />
<set-payload value="#[variable:content]" doc:name="Set Payload"/>
<set-variable variableName="subjectEmail" value="${smtp.service.failure.subject}filename=#[message.outboundProperties['originalFilename']]" doc:name="Variable"/>
<smtp:outbound-endpoint host="${smtp.host}" port="${smtp.port}" to="${smtp.to}" from="${smtp.from}" subject="#[variable:subjectEmail]" responseTimeout="10000" doc:name="HTTP_EMAIL_ALERT" mimeType="text/plain"/>
<set-payload value="#[variable:InputPayload]" doc:name="Set Payload"/>
<file:outbound-endpoint path="${ftp.edi.outbound.root.reprocesspath}" outputPattern="#[variable:filename]" responseTimeout="10000" doc:name="File"/>
<set-payload value="#[variable:InputPayload]" doc:name="Set Payload"/>
<ftp:outbound-endpoint host="${ftp.edi.inbound.root.host}" port="${ftp.edi.inbound.root.port}" path="${ftp.edi.elementum.copy.path}" user="${ftp.edi.inbound.root.user}" password="${ftp.edi.inbound.root.password}" outputPattern="#[message.outboundProperties['originalFilename']]" mimeType="text/plain" doc:name="FTP"/>
</otherwise>
</choice>
</when>
<otherwise>
<set-variable variableName="original_message" value="#[groovy:message.toString()]" doc:name="original_message" />
<set-attachment attachmentName="#[message.outboundProperties['originalFilename']]" value="#[payload]" contentType="text/xml" doc:name="OriginalFileAttachment"/>
<set-variable variableName="content" value="${smtp.file.not.supported.body}, Splunk txId=#[sessionVars.logTxid] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:logErrmsg] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:original_message] #[System.getProperty('line.separator')]" doc:name="EmailBodyContent" />
<set-payload value="#[variable:content]" doc:name="Set Payload"/>
<set-variable variableName="subjectEmail" value="${smtp.file.not.supported.subject}filename=#[message.outboundProperties['originalFilename']]" doc:name="Variable"/>
<smtp:outbound-endpoint host="${smtp.host}" port="${smtp.port}" to="${smtp.to}" from="${smtp.from}" subject="#[variable:subjectEmail]" responseTimeout="10000" doc:name="REGEX_NOT_FOUND_EMAIL_ALERT" mimeType="text/plain"/>
<logger message="{message = Email Sent to ${smtp.to}}" level="ERROR" doc:name="Logger"/>
<file:outbound-endpoint path="${ftp.edi.outbound.root.failedpath}" outputPattern="#[variable:filename]" responseTimeout="10000" doc:name="File"/>
</otherwise>
</choice>
</when>
<otherwise>
<logger message="{InboundPath=#[processing_folder_path], Message= REQUEST NOT PROCESSED NO MATCHING TEXT FOUND}" level="DEBUG" doc:name="Logger"/>
</otherwise>
</choice>
</foreach>
<choice-exception-strategy doc:name="Choice Exception Strategy">
<rollback-exception-strategy when="exception.causedBy(java.net.ConnectException) || exception.causedBy(java.net.SocketTimeoutException) || exception.causedBy(java.net.SocketException) || exception.causedBy(java.lang.Throwable)" maxRedeliveryAttempts="4" doc:name="Rollback Exception Strategy">
<on-redelivery-attempts-exceeded doc:name="Redelivery exhausted">
<set-variable variableName="errorMessage" value="{InboundPath=#[processing_folder_path], Ref= #[message.outboundProperties['originalFilename']], Content= #[groovy:payload.toString().replaceAll('\n', '')], Flow= #[variable:careerName], Message= MAXIMUM RETRIES REACHED}" doc:name="Variable"/>
<logger message="#[variable:errorMessage]" level="ERROR" doc:name="Logger"/>
<set-variable variableName="original_message" value="#[groovy:message.toString()]" doc:name="original_message" />
<set-attachment attachmentName="#[message.outboundProperties['originalFilename']]" value="#[payload]" contentType="text/xml" doc:name="OriginalFileAttachment"/>
<set-variable variableName="content" value="${smtp.rollback.body}, Splunk txId=#[sessionVars.logTxid] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:logErrmsg] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:original_message] #[System.getProperty('line.separator')]" doc:name="EmailBodyContent" />
<set-payload value="#[variable:content]" doc:name="Set Payload"/>
<set-variable variableName="subjectEmail" value="${smtp.rollback.subject}filename=#[message.outboundProperties['originalFilename']]" doc:name="Variable"/>
<smtp:outbound-endpoint host="${smtp.host}" port="${smtp.port}" to="${smtp.to}" from="${smtp.from}" subject="#[variable:subjectEmail]" responseTimeout="10000" doc:name="RETRY_FAILURE_EMAIL_ALERT" mimeType="text/plain"/>
<logger message="{message = Email Sent to ${smtp.to}}" level="ERROR" doc:name="Logger"/>
<file:file-to-string-transformer doc:name="File to String"/>
<file:outbound-endpoint path="${ftp.edi.outbound.root.failedpath}" responseTimeout="10000" outputPattern="#[message.outboundProperties['originalFilename']]" doc:name="File"/>
</on-redelivery-attempts-exceeded>
</rollback-exception-strategy>
<catch-exception-strategy when="exception.causeMatches(java.*)" doc:name="Data Errors Catch Exception Strategy">
<set-variable variableName="errorMessage" value="{InboundPath=#[processing_folder_path], Ref= #[message.outboundProperties['originalFilename']], Content= #[groovy:payload.toString().replaceAll('\n', '')], Flow= #[variable:careerName], Message=Common Exception Occured look at exception stackTrace for more details}" doc:name="Variable"/>
<logger message="#[variable:errorMessage]" level="ERROR" doc:name="Logger"/>
<set-variable variableName="original_message" value="#[groovy:message.toString()]" doc:name="original_message" />
<set-attachment attachmentName="#[message.outboundProperties['originalFilename']]" value="#[payload]" contentType="text/xml" doc:name="OriginalFileAttachment"/>
<set-variable variableName="content" value="${smtp.catch.exception.body}, Splunk txId=#[sessionVars.logTxid] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:logErrmsg] #[System.getProperty('line.separator')] #[System.getProperty('line.separator')] #[variable:original_message] #[System.getProperty('line.separator')]" doc:name="EmailBodyContent" />
<set-payload value="#[variable:content]" doc:name="Set Payload"/>
<set-variable variableName="subjectEmail" value="${smtp.catch.exception.subject}filename=#[message.outboundProperties['originalFilename']]" doc:name="Variable"/>
<smtp:outbound-endpoint host="${smtp.host}" port="${smtp.port}" to="${smtp.to}" from="${smtp.from}" subject="#[variable:subjectEmail]" responseTimeout="10000" doc:name="CATCH_EXCEPTION_EMAIL_ALERT" mimeType="text/plain"/>
<logger message="{message = Email Sent to ${smtp.to}}" level="ERROR" doc:name="Logger"/>
<file:file-to-string-transformer doc:name="File to String"/>
<file:outbound-endpoint path="${ftp.edi.outbound.root.failedpath}" responseTimeout="10000" outputPattern="#[message.outboundProperties['originalFilename']]" doc:name="File"/>
</catch-exception-strategy>
</choice-exception-strategy>
</flow>
I am trying to put invalid WEBSERVICE URL here which is causing this error and i want to catch those kind of errors and send out emails if service is down or configuration is wrong and not able to process the files :
What i need to change here in my code which will allow me to receive email notification about this error ? Can you please advice me what's wrong with Exception Strategy here?
INFO 2015-04-29 11:31:40,105 [scheduler-edi-ftp-file-processing-1.0.0-SNAPSHOT-v20150427-19+32_Worker-1] org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest: Content-Type not set on outgoing request, defaulting to: text/plain
ERROR 2015-04-29 11:31:40,123 [scheduler-edi-ftp-file-processing-1.0.0-SNAPSHOT-v20150427-19+32_Worker-1] org.mule.exception.DefaultSystemExceptionStrategy:
********************************************************************************
Message : Failed to route event via endpoint: DefaultOutboundEndpoint{endpointUri=http://myservice.company.com:80/services/service.svc, connector=HttpConnector
{
name=httpConnector
lifecycle=start
this=4d81bcef
numberOfConcurrentTransactedReceivers=4
createMultipleTransactedReceivers=true
connected=true
supportedProtocols=[http]
serviceOverrides=
session.handler=org.mule.session.NullSessionHandler
}
, name='endpoint.http.myservice.company.com.80.services.service.svc', mep=REQUEST_RESPONSE, properties={Content-Type=text/xml}, transactionConfig=Transaction{factory=null, action=INDIFFERENT, timeout=0}, deleteUnacceptedMessages=false, initialState=started, responseTimeout=120000, endpointEncoding=UTF-8, disableTransportTransformer=false}. Message payload is of type: PostMethod
Code : MULE_ERROR-42999
--------------------------------------------------------------------------------
Exception stack is:
1. myservice.company.com (java.net.UnknownHostException)
java.net.AbstractPlainSocketImpl:175 (null)
2. Failed to route event via endpoint: DefaultOutboundEndpoint{endpointUri=http://myservice.mycompany.com:80/services/service.svc, connector=HttpConnector
{
name=httpConnector
lifecycle=start
this=4d81bcef
numberOfConcurrentTransactedReceivers=4
createMultipleTransactedReceivers=true
connected=true
supportedProtocols=[http]
serviceOverrides=
session.handler=org.mule.session.NullSessionHandler
}
, name='endpoint.http.myservice.company.com.80.services.service.svc', mep=REQUEST_RESPONSE, properties={Content-Type=text/xml}, transactionConfig=Transaction{factory=null, action=INDIFFERENT, timeout=0}, deleteUnacceptedMessages=false, initialState=started, responseTimeout=120000, endpointEncoding=UTF-8, disableTransportTransformer=false}. Message payload is of type: PostMethod (org.mule.api.transport.DispatchException)
org.mule.transport.http.HttpClientMessageDispatcher:155 (http://www.mulesoft.org/docs/site/current3/apidocs/org/mule/api/transport/DispatchException.html)
--------------------------------------------------------------------------------
Root Exception stack trace:
java.net.UnknownHostException: myservice.company.com
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:175)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:384)
at java.net.Socket.connect(Socket.java:546)
+ 3 more (set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
Either one of the following:
Add "|| exception.causedBy(java.net.UnknownHostException)" to your first exception strategy to catch only unknown hosts exception.
Change your second catch exception strategy into exception.causeMatches('java.net.*') to catch all network exceptions (notice the quotes).
Change your second catch exception strategy into exception.causeMatches('java.*') to catch all java exceptions (notice the quotes).

How to use AMQP with Active MQ in Mule

Hi I am working with Mule Any Point Studio. I want to define one queue name and from that queue i want to read the data using AMQP.
Its not polling the data from the Queue which i mentioned.
My Mule Flow:
<amqp:connector name="amqpConnector" doc:name="AMQP Connector" host="localhost" port="5672" username="admin" password="admin" validateConnections="true" ></amqp:connector>
<flow name="mule-ampq" doc:name="mule-ampq">
<amqp:inbound-endpoint exchangeName="AMQP.DEFAULT.EXCHANGE" queueName="newx" queueAutoDelete="true" connector-ref="amqpConnector" doc:name="AMQP" exchangeType="fanout" responseTimeout="10000"/>
<logger message="#[message.payload]" level="INFO" doc:name="Logger"/>
</flow>
I am getting the following Error:
ERROR 2014-10-16 15:54:44,452 [main] org.mule.module.launcher.DefaultArchiveDeployer:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Failed to deploy artifact 'mule-ampq', see below +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
org.mule.module.launcher.DeploymentStartException: EOFException:
at org.mule.module.launcher.application.DefaultMuleApplication.start(DefaultMuleApplication.java:143)
at org.mule.module.launcher.artifact.ArtifactWrapper$4.execute(ArtifactWrapper.java:98)
at org.mule.module.launcher.artifact.ArtifactWrapper.executeWithinArtifactClassLoader(ArtifactWrapper.java:129)
at org.mule.module.launcher.artifact.ArtifactWrapper.start(ArtifactWrapper.java:93)
at org.mule.module.launcher.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:26)
at org.mule.module.launcher.DefaultArchiveDeployer.guardedDeploy(DefaultArchiveDeployer.java:274)
at org.mule.module.launcher.DefaultArchiveDeployer.deployArtifact(DefaultArchiveDeployer.java:294)
at org.mule.module.launcher.DefaultArchiveDeployer.deployExplodedApp(DefaultArchiveDeployer.java:261)
at org.mule.module.launcher.DefaultArchiveDeployer.deployExplodedArtifact(DefaultArchiveDeployer.java:110)
at org.mule.module.launcher.DeploymentDirectoryWatcher.deployExplodedApps(DeploymentDirectoryWatcher.java:287)
at org.mule.module.launcher.DeploymentDirectoryWatcher.start(DeploymentDirectoryWatcher.java:148)
at org.mule.tooling.server.application.ApplicationDeployer.main(ApplicationDeployer.java:130)
Caused by: org.mule.retry.RetryPolicyExhaustedException: null
at org.mule.retry.policies.AbstractPolicyTemplate.execute(AbstractPolicyTemplate.java:101)
at org.mule.transport.AbstractConnector.connect(AbstractConnector.java:1621)
at org.mule.transport.AbstractConnector.start(AbstractConnector.java:424)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.mule.lifecycle.phases.DefaultLifecyclePhase.applyLifecycle(DefaultLifecyclePhase.java:237)
at org.mule.lifecycle.RegistryLifecycleManager$RegistryLifecycleCallback.onTransition(RegistryLifecycleManager.java:273)
at org.mule.lifecycle.RegistryLifecycleManager.invokePhase(RegistryLifecycleManager.java:152)
at org.mule.lifecycle.RegistryLifecycleManager.fireLifecycle(RegistryLifecycleManager.java:123)
at org.mule.registry.AbstractRegistryBroker.fireLifecycle(AbstractRegistryBroker.java:76)
at org.mule.registry.MuleRegistryHelper.fireLifecycle(MuleRegistryHelper.java:136)
at org.mule.lifecycle.MuleContextLifecycleManager$MuleContextLifecycleCallback.onTransition(MuleContextLifecycleManager.java:91)
at org.mule.lifecycle.MuleContextLifecycleManager$MuleContextLifecycleCallback.onTransition(MuleContextLifecycleManager.java:87)
at org.mule.lifecycle.MuleContextLifecycleManager.invokePhase(MuleContextLifecycleManager.java:69)
at org.mule.lifecycle.MuleContextLifecycleManager.fireLifecycle(MuleContextLifecycleManager.java:61)
at org.mule.DefaultMuleContext.start(DefaultMuleContext.java:278)
at org.mule.module.launcher.application.DefaultMuleApplication.start(DefaultMuleApplication.java:123)
... 11 more
Caused by: java.io.IOException
at com.rabbitmq.client.impl.AMQChannel.wrap(AMQChannel.java:107)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:259)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:383)
at com.rabbitmq.client.ConnectionFactory.newConnection(ConnectionFactory.java:403)
at org.mule.transport.amqp.AmqpConnector.connectToFirstResponsiveBroker(AmqpConnector.java:443)
at org.mule.transport.amqp.AmqpConnector.doConnect(AmqpConnector.java:365)
at org.mule.transport.AbstractConnector$5.doWork(AbstractConnector.java:1561)
at org.mule.retry.policies.AbstractPolicyTemplate.execute(AbstractPolicyTemplate.java:63)
... 29 more
Caused by: com.rabbitmq.client.ShutdownSignalException: connection error; reason: java.io.EOFException
at com.rabbitmq.utility.ValueOrException.getValue(ValueOrException.java:67)
at com.rabbitmq.utility.BlockingValueOrException.uninterruptibleGetValue(BlockingValueOrException.java:33)
at com.rabbitmq.client.impl.AMQChannel$BlockingRpcContinuation.getReply(AMQChannel.java:328)
at com.rabbitmq.client.impl.AMQConnection.start(AMQConnection.java:244)
... 35 more
Caused by: java.io.EOFException
at java.io.DataInputStream.readUnsignedByte(DataInputStream.java:290)
at com.rabbitmq.client.impl.Frame.readFrom(Frame.java:104)
at com.rabbitmq.client.impl.SocketFrameHandler.readFrame(SocketFrameHandler.java:141)
at com.rabbitmq.client.impl.AMQConnection.readFrame(AMQConnection.java:402)
at com.rabbitmq.client.impl.AMQConnection$MainLoop.run(AMQConnection.java:430)
INFO 2014-10-16 15:54:44,455 [main] org.mule.module.launcher.DeploymentDirectoryWatcher:
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+ Mule is up and kicking (every 5000ms) +
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Try this example ... It contains different different exchange type used by AMQP .. For Direct Messaging you don't need to create the queue explicitly in the RabitMQ.. it will automatically created :-
<http:connector name="HttpConnector" doc:name="HTTP\HTTPS"/>
<amqp:connector name="amqpConnector" activeDeclarationsOnly="true" ackMode="MULE_AUTO" doc:name="AMQP Connector"/>
<amqp:connector name="amqpConnectorManualAck" prefetchCount="1" ackMode="MANUAL" doc:name="AMQP Connector"/>
<amqp:connector name="mandatoryAmqpConnector" mandatory="true" immediate="true" doc:name="AMQP Connector"/>
<!-- Direct Messaging -->
<amqp:connector name="amqp_config" validateConnections="true" virtualHost="/" username="guest" password="guest" doc:name="AMQP Connector"/>
<amqp:endpoint exchangeName="directEx" queueName="directQ" routingKey="routing.key" exchangeType="direct" queueDurable="true" name="amqp_direct_endpoint" responseTimeout="10000" doc:name="AMQP"/>
<!-- Direct Messaging -->
<jbossts:transaction-manager doc:name="Transaction Manager">
<property key="com.arjuna.ats.arjuna.coordinator.defaultTimeout" value="600"></property>
<property key="com.arjuna.ats.arjuna.coordinator.txReaperTimeout" value="1000000"></property>
</jbossts:transaction-manager>
<flow name="DefaultSender" doc:name="DefaultSender" >
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="1080" path="orders" doc:name="/orders" doc:description="Process HTTP reqests or responses." connector-ref="HttpConnector"/>
<set-payload value="New Message for Flow1" doc:name="Set Payload"/>
<logger message="Sending Message to Queue inhouseOrder .. Payload is #[message.payload]" level="INFO" category="DefaultSender" doc:name="Payload Logger" />
<amqp:outbound-endpoint exchange-pattern="request-response" exchangeName="directEx" exchangeType="direct" queueDurable="true" queueName="inhouseOrder" connector-ref="amqpConnector" doc:name="Dispatch to inhouseOrder" />
<byte-array-to-object-transformer doc:name="Byte Array to Object"/>
</flow>
<flow name="DefaultReceiver" doc:name="inhouseOrder" processingStrategy="synchronous" >
<amqp:inbound-endpoint queueName="inhouseOrder" connector-ref="amqpConnector" exchangeName="directEx" exchangeType="direct" queueDurable="true" doc:name="inhouseOrder" >
<amqp:transaction action="ALWAYS_BEGIN" recoverStrategy="REQUEUE" />
</amqp:inbound-endpoint>
<byte-array-to-object-transformer doc:name="Byte Array to Object"/>
<logger message="Receiving Message to Queue inhouseOrder .. Payload is #[message.payload]" level="INFO" category="DefaultReceiver" doc:name="Payload Logger" />
</flow>
<flow name="FanoutSenderExample2" doc:name="FanoutSenderExample2">
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="1080" path="orders3" doc:name="/orders" doc:description="Process HTTP reqests or responses." connector-ref="HttpConnector"/>
<set-payload value="Fanout Message for Queue accounting" doc:name="Set Payload"/>
<logger message="Sending Payload in FanoutSenderExample2 #[message.payload]" level="INFO" category="FanoutSenderExample2" doc:name="Payload Logger" />
<amqp:outbound-endpoint exchangeName="back-end-processing" exchangeType="fanout" exchangeAutoDelete="false" exchangeDurable="true" queueDurable="true" queueExclusive="false" queueAutoDelete="false" exchange-pattern="one-way" connector-ref="amqpConnector" doc:name="Dispatch to back-end-processing" />
<byte-array-to-object-transformer doc:name="Byte Array to Object"/>
</flow>
<flow name="FanoutReceiverExample2" doc:name="FanoutReceiverExample2">
<amqp:inbound-endpoint exchangeName="back-end-processing" queueName="accounting" exchangeType="fanout" exchangeAutoDelete="false" exchangeDurable="true" queueDurable="true" queueExclusive="false" queueAutoDelete="false" connector-ref="amqpConnector" doc:name="back-end-processing fullfilment queue" />
<byte-array-to-object-transformer doc:name="Byte Array to Object"/>
<logger message="Payload received in FanoutReceiverExample2 is: #[payload]" level="INFO" category="FanoutReceiverExample2" doc:name="Payload Logger" />
</flow>
<!-- Direct Messaging -->
<flow name="Send_Message_Direct" doc:name="Send_Message_Direct">
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="1080" doc:name="HTTP" path="orders5"/>
<set-payload value="#['im a Direct message'.getBytes()]" doc:name="Set payload for amqp message as ByteArray"/>
<amqp:outbound-endpoint responseTimeout="10000" doc:name="Send Direct Message" connector-ref="amqp_config" ref="amqp_direct_endpoint"/>
<set-payload value="#['Message Sended']" doc:name="Set payload as String"/>
<logger message="Direct message sended" level="INFO" doc:name="Logger"/>
</flow>
<flow name="Recive_Message_Direct" doc:name="Recive_Message_Direct">
<amqp:inbound-endpoint responseTimeout="10000" doc:name="Recive Direct Message" connector-ref="amqp_config" ref="amqp_direct_endpoint"/>
<byte-array-to-string-transformer doc:name="Transform bytearray message to String"/>
<logger message="I recived a direct message from AMQP: #[payload]" level="INFO" doc:name="Logger"/>
</flow>
<sub-flow name="defaultErrorHandler" doc:name="defaultErrorHandler">
<logger message="Error occurred: #[payload]" level="INFO" doc:name="Log Error"/>
<smtp:outbound-endpoint host="localhost" responseTimeout="10000" doc:name="Send Email to Operations"/>
</sub-flow>
</mule>
Reference :- Reference :- https://github.com/mulesoft/mule-transport-amqp/blob/master/GUIDE.md#mule-amqp-transport---user-guide

How to reuse "choice exception strategy" in mule

In Mule flow how can I re-use choice-exception-stretegy across several flows?
I tried the following, but it throws error when I run mule application.
<mule ....>
<choice-exception-strategy doc:name="My_exception_strategy">
<catch-exception-strategy when="exception.causedBy(java.net.SocketTimeoutException)" doc:name="Strategy1">
<logger message="message 1" level="INFO" doc:name="Logger"/>
</catch-exception-strategy>
<catch-exception-strategy when="exception.causedBy(java.lang.Throwable)" doc:name="Strategy2">
<logger message="message 2" level="INFO" doc:name="Logger"/>
</catch-exception-strategy>
</choice-exception-strategy>
<flow name="Test1" doc:name="Test1" processingStrategy="synchronous">
<logger message="message 3" level="INFO" doc:name="Logger"/>
<outbound-endpoint ref="myendpoint" doc:name="MyEndPoint"/>
<exception-strategy ref="My_exception_strategy" doc:name="Reference Exception Strategy"/>
<set-variable variableName="somevalue" value="#[something]" doc:name="statusCode"/>
</flow>
</mule>
There are two issues with the config you have posted.
There is a "set-variable" after the exception strategy. No other processors are expected after the "exception-strategy".
The exception strategy is not named. The attribute "name" is missing for the exception strategy.
Try the following flow .
<mule ....>
<choice-exception-strategy name="my_exception_strategy" doc:name="My_exception_strategy">
<catch-exception-strategy when="exception.causedBy(java.net.SocketTimeoutException)" doc:name="Strategy1">
<logger message="message 1" level="INFO" doc:name="Logger"/>
</catch-exception-strategy>
<catch-exception-strategy when="exception.causedBy(java.lang.Throwable)" doc:name="Strategy2">
<logger message="message 2" level="INFO" doc:name="Logger"/>
</catch-exception-strategy>
</choice-exception-strategy>
<flow name="Test1" doc:name="Test1" processingStrategy="synchronous">
<logger message="message 3" level="INFO" doc:name="Logger"/>
<outbound-endpoint ref="myendpoint" doc:name="MyEndPoint"/>
<exception-strategy ref="my_exception_strategy" doc:name="Reference Exception Strategy"/>
</flow>
</mule>
Hope this helps.

How to handle exceptions from using request reply router in mule

I am using the following fork and join pattern in my flow.Parallel processing works just fine. However, I have issues with exception handling. I want to implement an exception strategy for the processing happening on VM response inbound endpoint of the router. However, it seems my nothing happens when I am trying to write to response, from within the catch exception strategy block. When there is an exception, I am able to see the log statement from the catch block, but the response on browser just hangs.
Please suggest.
<flow name="forkAndJoinFlow" doc:name="forkAndJoinFlow">
<http:inbound-endpoint exchange-pattern="request-response" host="localhost" port="81" path="lowestprice" doc:name="HTTP"/>
<not-filter doc:name="Not">
<wildcard-filter pattern="*favicon*" caseSensitive="true"/>
</not-filter>
<request-reply>
<all>
<vm:outbound-endpoint path="shop1"/>
<vm:outbound-endpoint path="shop2"/>
</all>
<vm:inbound-endpoint path="response">
<message-properties-transformer>
<add-message-property key="MULE_CORRELATION_GROUP_SIZE" value="2" />
</message-properties-transformer>
<collection-aggregator />
</vm:inbound-endpoint>
</request-reply>
<expression-transformer evaluator="groovy" expression="java.util.Collections.min(payload)" doc:name="Expression"/>
<object-to-string-transformer doc:name="Object to String"/>
<logger level="WARN" message="#[string:Lowest price: #[payload]]" doc:name="Logger"/>
<catch-exception-strategy doc:name="Catch Exception Strategy">
<logger message="EXCEPTION:#[payload]" level="INFO" doc:name="Logger"></logger>
<!--Nothing happens after this-->
<object-to-string-transformer doc:name="Object to String"></object-to-string-transformer></catch-exception-strategy>
</flow>
<flow name="shop1Flow" doc:name="shop1Flow">
<vm:inbound-endpoint path="shop1" doc:name="VM"/>
<logger level="INFO" message="SHOP1 Flow..." doc:name="Logger"/>
<expression-transformer evaluator="groovy" expression="new java.lang.Double(1000.0 * Math.random()).intValue()" doc:name="Expression"/>
<logger level="WARN" message="#[string:Price from shop 1: #[payload]]" doc:name="Logger"/>
</flow>
<flow name="shop2Flow" doc:name="shop2Flow">
<vm:inbound-endpoint path="shop2" doc:name="VM"/>
<logger level="INFO" message="SHOP2 Flow..." doc:name="Logger"/>
<expression-transformer evaluator="groovy" expression="new java.lang.Double(1000.0 * Math.random()).intValue()" doc:name="Expression"/>
<logger level="WARN" message="#[string:Price from shop 2: #[payload]]" doc:name="Logger"/>`enter code here`
</flow>
</mule>