How to pass session variables to Groovy script in mule studio
I just started working with Mule. Flow description: I have an HTTP inbound endpoint receiving an XML message and I Hvae to update a database (derby) using an XML payload. Example: I get Emp Id and Emp name, Exp in a request. I need to update the table with these values.
My implementation:
After receiving the XML input, I use the Property transformer message to store the values ββin the session scope.
<message-properties-transformer scope="session" doc:name="Message Properties">
<add-message-property key="EmpNum"
value="#[xpath:/CreateEmployee/EmpNum]" />
</message-properties-transformer>
as mentioned above. And then I have a Groovy Script component to update the table. My request:
r.update(conn, "INSERT INTO Employee values(#[header:session:EmpNum],#[header:session:EmpName],#[header:session:Experience],#[header:session:Role])");
But this is a mistake:
Lexical error at line 1, column 29. Encountered: "#" (35), after: "". (org.apache.derby.iapi.error.StandardException) org.apache.derby.iapi.error.StandardException: -1 (null) Lexical error at line 1, column 29. Encountered: "#" (35), after: "". Query: INSERT INTO Employee values ββ(# [header: session: EmpNum], # [header: session: EmpName], # [header: session: Experience], # [header: session: Role]) Parameters: [] (SQL Code : 30000, SQL State: + 42X02) (java.sql.SQLException) org.apache.commons.dbutils.QueryRunner: 540 (null)
I have used a log component to display values.
#[header:session:EmpNum]
displays the correct value.
Please help me how to pass these session values ββto a Groovy script?
source to share
When using Groovy script in Mule for changing flow variables or session variables, the following works for me.
To read stream variables, I use
message.getInvocationProperty('yourVarsName').toString()
For reading session variables, I use
sessionVars['yoursVarsName'] or flowVars['yoursVarsName']
They work great for me in a Groovy script in Mule 3.5.
source to share
You cannot use the Mule Expression Language (MEL) directly in a Groovy script.
If you are using Mule 3.3, replace #[header:session:EmpName]
with sessionVars('EmpName')
and similar with other variables.
For previous versions, replace #[header:session:EmpName]
withmessage.getProperty('EmpName',PropertyScope.SESSION)
source to share
You have to allow the Groovy script to set the value before sending it as a SQL command. You send the literal "message.getProperty (" Experience ", PropertyScope.SESSION) directly to the SQL command.
qr.update(conn, "INSERT INTO Employee values("+message.getProperty('EmpNum',PropertyScope.SESSION)+","+message.getProperty('EmpName',PropertyScope.SESSION)+","+message.getProperty('Experience',PropertyScope.SESSION)+","+message.getProperty('Role',PropertyScope.SESSION)+")")
Also don't forget to import the PropertyScope class into your script:
import org.mule.api.transport.PropertyScope
source to share