synchronizing a database insert and select behind a web service - mule

I'm struggling to figure out how to solve this problem in mule using the studio and thought that perhaps reaching out to the good users of SO may be of some help.
I have a simple webservice that takes a request from a client. this request will preform an insert into a database table, effectively using this database as a message queue. A separate process periodically polls this table, performs additional processing on the message, and then writes results to an output table. the database insert and subsequent select will be linked by a a correlationId that I can pass along to ensure I get the result for the message that was sent. Unfortunately, the software this will integrate with requires this pattern to work correctly.
Here's the workflow that is needed:
HttpRequest -> insert record into a table -> wait(or poll/retry/etc?) until a record is written to another table by a separate process(with the same correlationId) -> return data from this other table back to the httpRequest
here's a sample flow that is as close as i've been able to get with this. Oddly enough, this flow does actually return a payload, however it seems to always be "1". i can't quite see how to make this flow retry the database query until a row exists and then return the resulting row.
How should i be synchronizing 2 database calls? is this possible within mule perhaps with a different combination of components?
Thanks.
<flow name="mainFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="hello" doc:name="HTTP"/>
<cxf:jaxws-service doc:name="CXF" configuration-ref="CXF_Configuration" serviceClass="kansas.MuleTestServiceImpl"/>
<db:insert config-ref="Oracle_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[insert into tblRequest (id, correlationId) values(#[payload], #[message.correlationId])]]></db:parameterized-query>
</db:insert>
<until-successful objectStore-ref="MyObjectStore" maxRetries="5" millisBetweenRetries="2000" doc:name="Until Successful" > <!-- failureExpression="???" -->
<db:select config-ref="Oracle_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[select correlationId,msgResponse from tblResponse where correlationId = #[message.correlationId]]]></db:parameterized-query>
</db:select>
</until-successful>
<logger level="INFO" doc:name="Logger" message="#[payload]"/> <!-- why is payload always = 1? -->
</flow>

Mule is great tool but it makes your life too easy. Sometime so easy that you forget simple things.
In your case you forgot that payload is one object which is result of last component. Think about flow as rails with just one cart. Whatever you load on last station is delivered to the next one. And then process repeats. What was originally delivered to the station does not matter. Matters what you load.
In your case first database component has original payload from CXF and stores something in the database. It returns result of the INSERT statement which is 1 - one row is inserted. So our payload keeps deliver new cargo - 1.
But you need original payload from CXF. Where it is? It is gone - we have only one flow, one pair of trails, one cart.
What to do in this situation? Keep required information not in the cart but somewhere else. For example in flow variables. Store original payload in some variable and then restore it when it required again. Like this
<flow name="mainFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="hello" doc:name="HTTP"/>
<cxf:jaxws-service doc:name="CXF" configuration-ref="CXF_Configuration" serviceClass="kansas.MuleTestServiceImpl"/>
<set-variable variableName="storedPaylod" value="#[payload]" doc:name="Store original payload"/>
<db:insert config-ref="Oracle_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[insert into tblRequest (id, correlationId) values(#[payload], #[message.correlationId])]]></db:parameterized-query>
</db:insert>
<set-payload value="#[flowVars.storedPaylod]" doc:name="Restore Payload"/>
<until-successful objectStore-ref="MyObjectStore" maxRetries="5" millisBetweenRetries="2000" doc:name="Until Successful" > <!-- failureExpression="???" -->
<db:select config-ref="Oracle_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[select correlationId,msgResponse from tblResponse where correlationId = #[message.correlationId]]]></db:parameterized-query>
</db:select>
</until-successful>
<logger level="INFO" doc:name="Logger" message="#[payload]"/> <!-- why is payload always = 1? -->
</flow>
Good idea will be to check that first database component really returns 1 - record is inserted. Do this, produce alerts on the error, and then restore original payload and continue your flow.

The best solution to avoid killing the actual value of your payload after the database insert is to make use of the Message Enricher processor.
try this code below:
<flow name="mainFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="hello" doc:name="HTTP"/>
<cxf:jaxws-service configuration-ref="CXF_Configuration" serviceClass="kansas.MuleTestServiceImpl" doc:name="CXF"/>
<enricher source="#[payload]" target="#[flowVars.insertResponse]" doc:name="Message Enricher">
<db:insert config-ref="Oracle_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[insert into tblRequest (id, correlationId) values(#[payload], #[message.correlationId])]]></db:parameterized-query>
</db:insert>
</enricher>
<flow-ref name="dbSelectSubFlow" doc:name="dbSelectSubFlow"/>
<logger message="#[payload]" level="INFO" doc:name="Logger"/>
</flow>
<sub-flow name="dbSelectSubFlow">
<until-successful objectStore-ref="MyObjectStore" maxRetries="5" millisBetweenRetries="2000" doc:name="Until Successful">
<db:select config-ref="Oracle_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[select correlationId,msgResponse from tblResponse where correlationId = #[message.correlationId]]]></db:parameterized-query>
</db:select>
</until-successful>
</sub-flow>

Related

how to insert multiple rows in mule database connector?

I want to insert multiple rows in mule database connector at a time. Could anyone kindly please help me on this?.
I can successfully insert the below message as a post request to a mule flow.
{
"patient_todo_id" : "2",
"comment_date" : "2017-09-20 14:41:16",
"comment_text" : "send me the steps to check the Pulse rate"
}
How to insert the below post message into a database in a mule flow?
[{
"patient_todo_id" : "2",
"comment_date" : "2017-09-20 14:41:16",
"comment_text" : "send me the steps to check the Pulse rate"
},
{
"patient_todo_id" : "2",
"comment_date" : "2017-09-20 14:41:16",
"comment_text" : "send me the steps to check the Pulse rate"
}]
Please find the below mule flow configuration file which has been configured to insert a single row at a time.
<flow name="carrotcube-patient-todo-commentFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="${http.path.mrs.todo.comment}" doc:name="HTTP"/>
<set-variable variableName="variable" value="#[payload]" mimeType="application/json" doc:name="Variable"/>
<json:json-to-object-transformer returnClass="java.lang.Object" doc:name="JSON to Object"/>
<logger message="#[payload.comment_text]" level="INFO" doc:name="Logger"/>
<db:insert config-ref="MySQL_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[insert into patient_todo_detail(patient_todo_id,comment_date,comment_text) values (#[payload.patient_todo_id],#[payload.comment_date],#[payload.comment_text])]]></db:parameterized-query>
</db:insert>
</flow>
Use the Bulk update mode and pass your connector a collection of object to insert. In Studio, simply check "Bulk mode" in the Basic Settings section of the database connector. The example array you provide in your question is just fine, you can then do something like:
<db:insert config-ref="MySQL_Configuration" bulkMode="true" doc:name="Database">
<db:parameterized-query><![CDATA[
INSERT INTO mytable(id, name)
VALUES (#[payload.id], #[payload.name]);]]>
</db:parameterized-query>
</db:insert>
Each element of your list will then become the payload in the connector and will be inserted. You do not need to use a for-each or any loop mechanism. Make sure to pass an iterable object though.
See the related docs:
https://docs.mulesoft.com/mule-user-guide/v/3.8/database-connector#setting-up-database-connector-operation
This is super easy, you can do it by 2 ways:
solution1 using splitter:
<flow name="testFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
<json:json-to-object-transformer returnClass="java.lang.Object" doc:name="JSON to Object"/>
<collection-splitter doc:name="Collection Splitter"/>
<logger message="insert into patient_todo_detail(patient_todo_id,comment_date,comment_text) values (#[payload.patient_todo_id],#[payload.comment_date],#[payload.comment_text])" level="INFO" doc:name="Logger"/>
<collection-aggregator failOnTimeout="true" doc:name="Collection Aggregator"/>
<json:object-to-json-transformer doc:name="Object to JSON"/>
</flow>
solution2 using foreach:
<flow name="testFlow">
<http:listener config-ref="HTTP_Listener_Configuration" path="/test" doc:name="HTTP"/>
<json:json-to-object-transformer returnClass="java.lang.Object" doc:name="JSON to Object"/>
<foreach doc:name="For Each" collection="#[payload]">
<logger message="insert into patient_todo_detail(patient_todo_id,comment_date,comment_text) values (#[payload.patient_todo_id],#[payload.comment_date],#[payload.comment_text])" level="INFO" doc:name="Logger"/>
</foreach>
<json:object-to-json-transformer doc:name="Object to JSON"/>
</flow>
In both the cases, you can see your logger is getting the correct values in your SQL statement you are using :
<logger message="insert into patient_todo_detail(patient_todo_id,comment_date,comment_text) values (#[payload.patient_todo_id],#[payload.comment_date],#[payload.comment_text])" level="INFO" doc:name="Logger"/>
Now you can replace the logger with your DB component
UPDATE based on the comment:
<set-variable variableName="myMap" value="#[new java.util.HashMap()]" doc:name="Variable"/>
<foreach doc:name="For Each" collection="#[payload]">
<db:insert config-ref="MySQL_Configuration" doc:name="Database">
<db:parameterized-query><![CDATA[insert into patient_todo_detail(patient_todo_id,comment_date,comment_text) values (#[payload.patient_todo_id],#[payload.comment_date],#[payload.comment_text])]]></db:parameterized-query>
</db:insert>
<expression-component doc:name="Expression"><![CDATA[flowVars.myMap.put('row'+flowVars.counter,payload)]]></expression-component>
</foreach>
<logger message="Final status #[flowVars.myMap.toString()]" level="INFO" doc:name="Logger"/>
Here at the end you will get in logger the status of each row inserted which is 1 means successful
To get a particular row details ouside foreach:
<logger message="#[flowVars.myMap.get('row1').toString()]" level="INFO" doc:name="Logger"/>
So, based on the status you can further display your custom status messages
Ashok, I just crossed this hurdle, so you got really lucky here as I had to struggle through this for a while. Very surprising that such a common scenario was not to be found on the Internet. The steps are listed below ,and the flow is below too.
1) Use transform to convert the post payload to java list (application/java) – the output should just have payload (remove the curly braces and just put payload). This payload should come from the body.
2) Use for each scope and put the database insert statement there
3) In the database insert statement use [payload[‘username’]] kind of syntax to refer to the value of username in the current record (or whatever field names you have). I am using a stored prod to insert, but you get the idea.
I am not able to post the flow here .. it's cutting it off and showing it weird. I'll try to send you through email if you can share.
Now all I have to figure out is how to send a nice message back with the insert status. Anybody who already has done that.. appreciate your inputs!
Ashok, replying to your comment on aggregating the response from the for each here, as I can't add comments yet. Check out the following link, which offer s a few options.
https://forums.mulesoft.com/questions/60273/save-of-for-each-database-query-response-to-a-new.html

Facing error in Batch Processing mule esb

I am facing problem in batch processing mule esb. If I set any payload in process record face and try to get that payload in oncomplete face then not getting that payload. same problem with variable and property.
If I set any property in process record phase and try to get in on complete phase then always get null value.
how to get those value in oncomplete phase?
below is flow..
<batch:job name="TestBatch" max-failed-records="-1">
<batch:input>
<component class="com.test.RecordTest"
doc:name="Java" />
<json:object-to-json-transformer
doc:name="Object to JSON" />
<custom-transformer class="com.test.CustomTr"
doc:name="Java" />
</batch:input>
<batch:process-records>
<batch:step name="Batch_Step1" accept-policy="ALL">
<batch:commit size="5" doc:name="Batch Commit">
<!-- Insert record in Salesforce -->
</batch:commit>
</batch:step>
<batch:step name="Batch_Step2" accept-policy="ONLY_FAILURES">
<logger message="STEPP #[getStepExceptions()]" level="INFO" doc:name="Logger"/>
<set-property propertyName="error" value="STEPP #[getStepExceptions()]" doc:name="Property"/>
<set-payload value="#[getStepExceptions()]" doc:name="Set Payload"/>
</batch:step>
</batch:process-records>
<batch:on-complete>
<logger level="INFO" doc:name="Logger" message="--> #[payload.failedRecords] --> #[message.payload] "/>
<logger message="error--- #[message.outboundProperties['error']] " level="INFO" doc:name="Logger"/>
</batch:on-complete>
</batch:job>
I got null in property logger
How can I solve this?
I got some bad news from you :-).
Batch processing by design will not old any of the value you may try to set in steps, especially payload.
When I started working with it I was also expecting to have session variable on complete phase in a correct status but this is not the case, they are completely wiped at each step.
Now I don't think this is a bug, but it is really a design feature that I can understend even if I don't really love it.
I solved the same problem by using the object store connector.
It will allow you to access the mule Object Store API via nice XML configuration block, in this way you can store in memory variables that you can recover after in your on-complete without them being affected by flow logic.
Hope this helps

Insert Arraylist in Database in Mule

I am trying to insert the contents of an ArrayList to a SQL Server database using Mule ESB. The ArrayList looks like
[
{Id=a1o90000001muvWAAQ, Billing_Number__c=1000005, type=Call_Log__c},
{Id=a1o90000001muvXAAQ, Billing_Number__c=1000006, type=Call_Log__c}
]
How should I insert this into the database in an optimized way?
My mule flow is as below.
<sfdc:query config-ref="Salesforce__Basic_authentication" query="#[flowVars.query]"
doc:name="Salesforce"/>
<set-variable variableName="result" value="#[new java.util.ArrayList()]"
doc:name="Variable"/>
<foreach doc:name="For Each">
<set-variable variableName="itrresult" value="#result.add(message.payload)]"
doc:name="Variable"/>
</foreach>
<splitter expression="#[flowVars.result]" doc:name="Splitter"/>
<logger message="#[payload['Id']]" level="INFO" doc:name="Logger"/>
#[payload['Id']] gives me the Id LoggerMessageProcessor: a1o90000001mzgzAAA in log.
I am not sure what i am doing is the right way though. I am just on the beginning of the learning curve in Mule.
You don't need a Splitter or the Foreach scope. The Database connector has a bulk mode that makes the connector accept a collection as payload.
Enable to submit collections of data with one query, [...]. Enabling bulk mode improves the performance of your applications as it reduces the number of individual query executions. Bulk mode requires a parameterized query with at least one parameter.
Enable it with bulkMode="true" in an insert, update or delete operation.
EDIT: Use this right after your Salesforce Query component:
<sfdc:query config-ref="" query="#[flowVars.query]" doc:name="Salesforce"/>
<db:insert config-ref="" bulkMode="true" doc:name="Database">
<db:parameterized-query>
<![CDATA[INSERT INTO TABLE (ID, BILLING_NUMBER__C, TYPE)
VALUES (#[payload.Id], #[payload.Billing_Number__c], #[payload.type]);]]>
</db:parameterized-query>
</db:insert>
The payload returned by the Database Insert component is an array with the number of rows changed for each query executed. In your case, an array of one's with the size of how many items the Salesforce Query component returned, like [1, 1, 1, ...].
If you still need to log, do this:
<sfdc:query config-ref="" query="#[flowVars.query]" doc:name="Salesforce"/>
<foreach doc:name="For Each">
<logger message="#[payload.Id]" level="INFO" doc:name="Logger"/>
</foreach>
<db:insert config-ref="" bulkMode="true" doc:name="Database">
<db:parameterized-query><!-- the query --></db:parameterized-query>
</db:insert>
Or this:
<sfdc:query config-ref="" query="#[flowVars.query]" doc:name="Salesforce"/>
<foreach doc:name="For Each">
<logger message="#[payload.Id]" level="INFO" doc:name="Logger"/>
<db:insert config-ref="" doc:name="Database"><!-- bulkMode disabled -->
<db:parameterized-query><!-- the query --></db:parameterized-query>
</db:insert>
</foreach>
Use splitter to split your array and insert individually:
<splitter expression="#[payload]" />
<db:insert config-ref="Config" doc:name="Database">
<db:parameterized-query><![CDATA[insert into xx(Id, Billing_Number__c, type) values('#[payload['Id']]','#[payload['Billing_Number__c']]','#[payload['type']]');]]></db:parameterized-query>
</db:insert>
You can iterate over the ArrayList using a for, inserting values one by one using db:dynamic-query.
Mule support the bulk mode to insert a collection of data. I prefer the db:in-param Element with labels within the SQL statement. Configuration has been tested with Mule 3.8.5.
<db:insert config-ref="databaseConfiguration" bulkMode="true" doc:name="Database">
<db:parameterized-query>
<![CDATA[INSERT INTO T_ORDER (ORDER_NO,CUSTOMER_NO) VALUES (:orderNo, :customerNo)]]>
</db:parameterized-query>
<db:in-param name="orderNo" value="#[payload.orderNo]" />
<db:in-param name="customerNo" value="#[payload.customerNo]" />
</db:insert>
The bulk mode offers a much better performance. Make sure your DBMS is configured correctly for this use case.
Collection with huge entries can be partioned, for example to sub collection of 100 entries, before calling the db:insert component.
<!-- Sample: Collection with 1.000 entries -->
<!-- will be chunked into sub collections with 100 entries -->
<foreach batchSize="100" />

SQL Update statement with MEL expression - Mule

I have a SQL UPDATE statement, to update a particular record to the Database within a mule flow. I am having problems with including MEL expression within the statement and the SQL is not getting executed in my flow.
I am trying the next command:
UPDATE CUSTOMERS SET STATUS=#[flowVars['TxnStatus']] WHERE REF_NUM=#[flowVars['ReferenceNumber']]
where TxnStatus and ReferenceNumber are flow variables in my mule Flow. It looks seemingly simple, but the record is not updated.
When I try a similar SELECT statement with MEL expressions it does retrieve the value for me. Please let me know your thoughts.
Thanks,
Added config file:
<?xml version="1.0" encoding="UTF-8"?>
<jdbc-ee:mssql-data-source name="MuleDB_DataSource" user="${MuleDB_User}" password="${MuleDB_Password}" url="${MuleDB_URL}" transactionIsolation="UNSPECIFIED" doc:name="MS SQL Data Source"/>
<jdbc-ee:connector name="Database" dataSource-ref="MuleDB_DataSource" validateConnections="true" queryTimeout="-1" pollingFrequency="10000" doc:name="Database" transactionPerMessage="false">
</jdbc-ee:connector>
<flow name="ExceptionFlowFlow1" doc:name="ExceptionFlowFlow1">
<vm:inbound-endpoint exchange-pattern="one-way" path="Exception" doc:name="VM"/>
<set-variable variableName="ExceptionPayload" value="#[payload]" doc:name="ExceptionPayload"/>
<set-variable variableName="TxnStatus" value="Failure" doc:name="Variable"/>
<logger message="#[variable:TxnStatus]" level="INFO" category="Status" doc:name="Logger"/>
<jdbc-ee:outbound-endpoint exchange-pattern="one-way" queryKey="Update_Status" queryTimeout="-1" connector-ref="Database" doc:name="Update_Status">
<jdbc-ee:query key="Update_Status" value="UPDATE CUSTOMERS SET STATUS=#[flowVars['TxnStatus'] WHERE PAYMENT_REFERENCE_NUMBER=#[flowVars['TxnReference']"/>
</jdbc-ee:outbound-endpoint>
<logger message="#[payload]" level="INFO" doc:name="Logger"/>
<catch-exception-strategy doc:name="Catch Exception Strategy">
<logger message="#[exception]" level="INFO" category="ExceptionFlow failed with the exception --" doc:name="Logger"/>
</catch-exception-strategy>
</flow>
</mule>
I can see difference between value you used in query key and command given by you above
value="UPDATE CUSTOMERS SET STATUS=#[flowVars['TxnStatus'] WHERE PAYMENT_REFERENCE_NUMBER=#[flowVars['TxnReference']"/>
Both are missing end ] in query value. Correct it and try again.
I've had similar issues when trying to use a flow variable as an SQL input value. Try replacing #[flowVars['varName']] with #[variable:varName] like so:
UPDATE CUSTOMERS SET STATUS=#[variable:TxnStatus] WHERE REF_NUM=#[variable:ReferenceNumber]
This has worked for me. Hope that helps!
UPDATE audit_detail
SET
status = '3'
WHERE
request_id = #[flowVars['ses_request_id']
AND
message_id = #[flowVars['ses_message_id']

Mule MEL to read database result-set from an second 'database outbound endpoint'

I have a flow something like this
A 'Database inbound endpoint' which polls(for every 5 mins) to mySQL Database-Server and get result-set by a select-query (automatically this becomes the current payload i.e #[message.payload])
'For each' component and a 'Logger' component in it using a expression as #[message.payload]
Now flow has one more 'Database-out-bound-endpoint' component which executes another select-query and obtains result-set.
'For each' component with a 'Logger' component in it using a expression as #[message.payload]
Note: in the loggers result-set of first DB is printing. I mean second logger is also showing result-set of first query itself.Because the result-set is storing as payload
so, my questions are
what is the MEL to read the result-set of second database-query in the above scenario.
is there any another way to read result-set in the flow
Here is the configuration XML
<jdbc-ee:connector name="oracle_database" dataSource-ref="Oracle_Data_Source" validateConnections="true" queryTimeout="-1" pollingFrequency="0" doc:name="Database"/>
<flow name="testFileSaveFlow3" doc:name="testFileSaveFlow3">
<poll frequency="1000" doc:name="Poll">
<jdbc-ee:outbound-endpoint exchange-pattern="one-way" queryKey="selectTable1" queryTimeout="-1" connector-ref="oracle_database" doc:name="get data from table 1">
<jdbc-ee:query key="selectTable1" value="SELECT * FROM TABLE1"/>
</jdbc-ee:outbound-endpoint>
</poll>
<foreach doc:name="For Each">
<logger message="#[message.payload]" level="INFO" doc:name="prints result-set of table1"/>
</foreach>
<jdbc-ee:outbound-endpoint exchange-pattern="one-way" queryKey="selectTable2" queryTimeout="-1" connector-ref="oracle_database" doc:name="get data from table 2">
<jdbc-ee:query key="selectTable2" value="SELECT * FROM TABLE2"/>
</jdbc-ee:outbound-endpoint>
<foreach doc:name="For Each">
<logger message="#[message.payload]" level="INFO" doc:name="prints result-set of table2"/>
</foreach>
</flow>
thanks in advance.
This is not the issue with the MEL. It is the issue with your flow logic.
The second result set is not available in the message.
The JDBC Outbound Endpoint is one-way. So Mule flow will not wait for the reply (result set) from the second JDBC (outbound ) in the middle of the flow. So the second time also it is printing the first result set.
Type 1:
Try making your JBDC outbound request-response instead of one-way.
Type 2:
Try Mule Enricher to call the JDBC outbound to call the DB and store the result set into a varaible and try looping the varaible.
Hope this helps.