How to refer session variables in Groovy script in mule studio - mule

I just started working with Mule.
Flow description:
I have an HTTP inbound endpoint receive XML message, and I Hvae to update the database (derby) using the XML payload.
Ex: I will be receiving Emp Id and Emp name, Exp in the request. I have to update the table with these values.
My Implementation:
After receiving XML input I am using the message Property transformer to save the values in Session scope.
<message-properties-transformer scope="session" doc:name="Message Properties">
<add-message-property key="EmpNum"
value="#[xpath:/CreateEmployee/EmpNum]" />
</message-properties-transformer>
like above. And then I have Groovy Script component to update the table.
My Query is:
r.update(conn, "INSERT INTO Employee values(#[header:session:EmpNum],#[header:session:EmpName],#[header:session:Experience],#[header:session:Role])");
But it is throwing error:
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 logger component to display the values.
#[header:session:EmpNum]
is displaying the proper value.
Please help me how to refer this session values in Groovy script?

The following works for me when using Groovy script in Mule to read flow variables or session variables respectively.
For reading flow variables I'm using
message.getInvocationProperty('yourVarsName').toString()
For reading session variables I'm using
sessionVars['yoursVarsName'] or flowVars['yoursVarsName']
They work very well for me in the Groovy script in Mule 3.5.

You cannot use Mule Expression Language (MEL) directly in a Groovy script.
If you're using Mule 3.3, replace #[header:session:EmpName] with sessionVars('EmpName') and similar with the other variables.
For previous versions, replace #[header:session:EmpName] with message.getProperty('EmpName',PropertyScope.SESSION)

You have to allow the Groovy script to set the value before sending it as a SQL command. You are sending the literal "message.getProperty('Experience',PropertyScope.SESSION)" straight into 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 in the script:
import org.mule.api.transport.PropertyScope

#[groovy:message.getSessionProperty('sesVarValue')

Not sure if any one if anyone needs the answer but for Mule 3.6+ I was able to access Sessions or flow variable by simply doing sessionVars['sessVarName'] /flowVars['flowVarName']
**DO NOT Forget to use "+" to concatenate Strings if values used as strings.

Related

Unable to create VM from existing template using powershell

I am getting below error message when creating VM from existing parameter.json and template.json file.
Code : InvalidDeploymentParameterValue
Message : The value of deployment parameter 'publicIPAddresses_azuse2qaautovm2_ip_name' is null. Please specify the
value or use the parameter reference. See https://aka.ms/arm-deploy/#parameter-file for details.
You need to provide a value for that parameter (in a parameters file) publicIPAddresses_azuse2qaautovm2_ip_name or provide a default value for that parameter.

Jmeter: validating Code in Beanshell Sampler

Here is the simple code
vars.put("str" , "${__time(dd/mm/yyyy HH:MM:SS)}");
log.info("${str}");
I am expecting to see the value of str in logs but I am getting ${str}. I am validating it because I have to assign the current time to a variable and later want to use it in script. But I am not getting the value stored in str.
try as follows using vars.get:
vars.put("str" , "${__time(dd/mm/yyyy HH:MM:SS)}");
log.info("str " + vars.get("str"));
I wouldn't recommend inlining functions and/or variables into Beanshell script as you may face syntax error issues, i.e. type mismatch if the value has quotation marks.
So either use log.info(vars.get("str")); or use Debug Sampler and View Results Tree listener combination to see JMeter variables values.
More information: How to Debug your Apache JMeter Script

How to find current flow name in mule?

I need to capture current flow name into a variable.
I tried with #[flow.name] but no luck in mule 3.8.0
can anybody please assist me?
Based on the answer in this post: How to get caller flow name in private flow in Mule
There is a simplest way to get the flow name and put it into a variable:
<expression-component doc:name="Expression"><![CDATA[flowVars.flowName = flow.name;]]></expression-component>
Alternately, you can directly use expression #[mule:context.serviceName] in a variable :-
<set-variable variableName="myFlowName" value="#[mule:context.serviceName]" doc:name="Variable"/>
<!-- Print the value of variale in logger -->
<logger message="#[flowVars.myFlowName]" level="INFO" doc:name="Logger"/>
This will set your current flow name directly in variable
In mule 3.8.5 using Groovy script component,
flowVars.currentFlowName = eventContext.getFlowConstruct().getName();
I have been using #[flow.name] in 3.7.3 and just tried in 3.8.0 to make sure it had not been removed and it worked fine for me in logger and setting a flowVars value. I suggest posting up at least a snippet of your flow and maybe we can spot the issue you are having.
PS, not sure why flow.name is not in standard forms or really documented by Mule, and as it is not there continues to be some worries they will remove it. I have seen it stated more than just here that it is not accessible in MEL, but #[flow.name] is a MEL expression and does work. To use if for something like I Parse Template in exception strategies, I use sulthony's form, set a flowVars value in an expression and refer to that flowVars in my template.
You can access flow name in logger by using #[flow.name] but its not accessible in MEL. Use flowconstruct for getting flow name. Refer this answer
Hope this helps.

How to read properties from .properties file in Mule

I'm trying to use Mule Credentials Vault security feature.
I've created .properties file, Security Property Placeholder and defined the key and encryption algorithm.
Now I want to use some of the properties from the file when I return HTTP response.
I have the file src/main/resources/data.properties that contains for example:
In my canvas, under Configuration XML I added:
<secure-property-placeholder:config name="Secure_Property_Placeholder" key="24681357" location="data.properties" doc:name="Secure Property Placeholder" encryptionAlgorithm="DES"/>
<set-variable variableName="card.number" value="${number}" />
In my canvas I have message flow that builds xml 'Create XML response based on User'. The value in settings is:
This doesn't work. The error I get is:
-> org.mule.module.launcher.DeploymentInitException: IllegalArgumentException: Could not resolve placeholder 'key' in string value "${key}"
-> Caused by: org.mule.api.lifecycle.InitialisationException: Invalid bean definition with name 'org.mule.autogen.bean.13' defined in null: Could not resolve placeholder 'key' in string value "${key}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'key' in string value "${key}"
-> Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'key' in string value "${key}"
Does anyone know how can I read the properties from .properties file (credentials vault)? And then use it in my flow?
Thanks,
Keren
If you simply want to get the value for the property number and add it into the XML you can use ${number} from .properties. No need to define any other variables in Configuration XML.
<set-payload value="<user><name>Royal Bank of Canada</name><id>Royal_Bank_Of_Canada</id><cc><company>>Visa</company><number>${number}</number><secret>123</secret></cc></user>" doc:name="Set Payload"/>
However note that the property placeholder is resolved at startup so you will not be able to dynamically retrieve a property based on some user input. For this you will have to do some Java coding. This SO post gives you some hints on how this can be achieved. Based on those answers I have created a simple example on how this can be done with a very simple helper bean.
I'm afraid you just can't. The Mule Credentials Vault is an enterprise feature and therefore tipically you won't have access to the source code unless you are a MuleSoft customer.
Even if you were a customer, the api you'd use would be sort of unsupported. I suggest to manually create a custom java component levearing your code and Jasypt (not as a property placeholder but as a library).
The other option, if you are a customer (I guess you are given you are using the credentials vault) is to contact the official support so they take care of it for you.
The property placeholder is used resolve at startup so you will not be able to dynamically retrieve a property based on some user input.
Use ${propertyName} from .properties in MEL to access particular property
From Dataweave you can read it as given below
p('variablename')
where variablename is defined in property files ex: variablename = 15

Message.InboundProperty always return String - MULE - AnyPoint Studio - APIkit

im developing an API using RAML + MULE AnypointStudio (APIkit) . so in my RAML file i had defined a resourse like this.
/player
post:
queryParameters:
year: type: integer
place: type: string
Then, into AnyPoint Studio, after importing my .raml file i got a flow with the post method asociated. I use the MySQL Conector to insert in a data base. the problem resides in the query:
INSERT INTO Matches (day,place,max_players)
VALUES (#[message.inboundProperties.'day'],#[message.inboundProperties'place'],
#[message.inboundProperties.'maxPlayers'])
when i call #[message.inboundProperties.day] it returns a string, but i want an integer value.
im new at MULE, so it would be great if you can explain me how.
ty
All query parameters are treated as Strings. You can use MEL to convert to an int though. Here's an example suing Java in a Mel expression to parse the parameter to an int.
#[Integer.parseInt(message.inboundProperties.day)]