Camunda-Pass parameter between HTTP-CONNECTOR - camunda

I want to pass output of one REST API to another REST-API in camunda . My first API is returning JSON which has value of email .
I am getting output from first REST-API using HTTP-CONNECTOR script variable
<camunda:outputParameter name="email">
<camunda:script scriptFormat="JavaScript">var value = S(NUMBER, 'application/json');
print("DATA ::: "+ value);
var response = S(connector.getVariable("response"), 'application/json');
print("Response ::: "+ response );
print("Email :::"+ response.prop("email"));
response.prop("email");</camunda:script>
</camunda:outputParameter>
now I want to pass email in payload of another rest-API call for which I am using HTTP-CONNECTOR
<camunda:connector>
<camunda:inputOutput>
<camunda:inputParameter name="url">http://localhost:8080/step2</camunda:inputParameter>
<camunda:inputParameter name="method">POST</camunda:inputParameter>
<camunda:inputParameter name="header">
<camunda:map>
<camunda:entry key="accept">application/json</camunda:entry>
<camunda:entry key="content-type">application/json</camunda:entry>
</camunda:map>
</camunda:inputParameter>
<camunda:inputParameter name="payload">
<camunda:script scriptFormat="JavaScript">var email=execution.getVariable("email");</camunda:script>
</camunda:inputParameter>
</camunda:inputOutput>
<camunda:connectorId>http-connector</camunda:connectorId>
</camunda:connector>
but it's giving error as
w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type '' not supported]
How to pass output variable to next REST-API ?

<camunda:inputParameter name="header"> instead of this <camunda:inputParameter name="headers"> should be used , more-ever it's not possible to pass script as input to text variable.
so I used
<camunda:outputParameter name="email">
${response}
</camunda:outputParameter>
to pass complete response to next service

Related

You called the function 'Value Selector' with these arguments

I am in the process of implementing a LoanBroker with Mulesoft but have an error message when sending a request. I get the following error message back from Postman and Mulesoft Anypoint Studio:
ERROR 2021-06-27 15:20:51,133 [[MuleRuntime].uber.04: [loanbroker].LoanBrokerFlow_Gr7.CPU_LITE #254be3ee] [processor: LoanBrokerFlow_Gr7/processors/0; event: 7e49f560-d74a-11eb-b598-b66921dc5aa5] org.mule.runtime.core.internal.exception.OnErrorPropagateHandler:
********************************************************************************
Message: "You called the function 'Value Selector' with these arguments:
1: Binary ("" as Binary {base: "64"})
2: Name ("amount")
But it expects one of these combinations:
(Array, Name)
(Array, String)
(Date, Name)
(DateTime, Name)
(LocalDateTime, Name)
(LocalTime, Name)
(Object, Name)
(Object, String)
(Period, Name)
(Time, Name)
1| payload.amount
^^^^^^^^^^^^^^
Trace:
at main (line: 1, column: 1)" evaluating expression: "payload.amount".
Element : LoanBrokerFlow_Gr7/processors/0 # loanbroker:bi_gruppe7.xml:34 (Copy_of_setAmount)
Element DSL : <set-variable value="#[payload.amount]" doc:name="Copy_of_setAmount" doc:id="cbcca557-1a69-4cf2-80b1-64333175589d" variableName="amount"></set-variable>
Error type : MULE:EXPRESSION
FlowStack : at LoanBrokerFlow_Gr7(LoanBrokerFlow_Gr7/processors/0 # loanbroker:bi_gruppe7.xml:34 (Copy_of_setAmount))
(set debug level logging or '-Dmule.verbose.exceptions=true' for everything)
********************************************************************************
Can anyone help me?
Thanks
This generally happens when one tries to access inner value of a payload like json but incoming payload is NOT actually a json type.
One could check the payload mediaType and then try to access the amount in order to avoid Value Selector exception.
%dw 2.0
output application/java
---
if( !isEmpty(payload) and payload.^mediaType contains "json" )
payload.amount
else
read(payload, "application/json").amount //best effort
Would recommend creating a separate dataweave file like dwl/set-amount.dwl and referencing it.
You are probably sending some body in the HTTP request from Postman but Mule doesn't know how to read it. Maybe you did not the Content-Type header in the request to let DataWeave know it is a JSON (application/json) or XML (application/XML).
Ensure you are sending the right content type.
I ran into the same situation. I know exactly the base64 is a json. So, I tried to set the MIME Type by
<set-payload value="#[payload]" doc:name="Set Payload" mimeType="application/json"/>
It works for me.

can we pass multiple args in Get Json Value key?

I'm for now fetching one arg value through Get Json Value key
Create Session Get_Inventory_Details ${Base_URL}
${Headers}= Create Dictionary Content-Type=application/json Authorization=bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6InByaXRpc3dhaW4iLCJpYXQiOjE1Njc1MTQ2NDd9.o3qTPbj2KH6AgHpIf1BLV5nOlGL-fR83wSGAYyuWsBQ
${Response}= Get Request Get_Inventory_Details inventorybyOutlet/7 headers=${Headers}
Log To Console ${Response.status_code}
Log Many ${Response.content}
${actual_response}= Convert To String ${Response.status_code}
Should Be Equal ${actual_response} 200
${quantity}= Get Json Value ${Response.content} /0/currentInventory
Run Keyword If ${quantity}>10 Log Threshold Condition Pass ELSE Log Threshold Condition Fail
What can be the possible way out if I want to pass more than one arg in Get Json Value
I have tried
${quantity}= Get Json Value ${Response.content} /0/currentInventory/0/itemid
Reference to Json Data
[
{
"isInventoryOperationEnable":1,
"itemId":1,
"name":"Afghani Chicken Tikka Biryani (Heavy Eater)",
"posName":"Afghani Chicken Tikka Biryani (Heavy Eater)",
"image":"https://d30mle0t4iy75h.cloudfront.net/websiteV2/images/menuItems/AfghaniTikkaBiryani.jpg",
"typeid":2,
"isCombo":0,
"currentInventory":100,
"categoryId":1,
"categoryname":"Biryani",
"subCategoryId":1,
"sequenceInCategory":1
},
{
"isInventoryOperationEnable":1,
"itemId":3,
"name":"Chicken Tikka Biryani (Heavy Eater)",
"posName":"Chicken Tikka Biryani (Heavy Eater)",
"image":"https://d30mle0t4iy75h.cloudfront.net/websiteV2/images/menuItems/ChickenTikkaBiryani.jpg",
"typeid":2,
"isCombo":0,
"currentInventory":100,
"categoryId":1,
"categoryname":"Biryani",
"subCategoryId":1,
"sequenceInCategory":14
}
]
But RobotFramework throws error as :-
JsonPointerException: Document '' does not support indexing, must be mapping/sequence or support __getitem__
Error Message on RobotFramework
Please can anyone help in finding out a way how to pass more than 1 arg in this case
Thank You
Create Session Get_Inventory_Details ${Base_URL}
${Headers}= Create Dictionary Content-Type=application/json Authorization=bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyTmFtZSI6InByaXRpc3dhaW4iLCJpYXQiOjE1Njc1MTQ2NDd9.o3qTPbj2KH6AgHpIf1BLV5nOlGL-fR83wSGAYyuWsBQ
${Response}= Get Request Get_Inventory_Details inventorybyOutlet/7 headers=${Headers}
Log To Console ${Response.status_code}
Log Many ${Response.content}
${actual_response}= Convert To String ${Response.status_code}
Should Be Equal ${actual_response} 200
${response_content_json}= To Json ${Response.content} #To Json is from RequestsLibrary
${quantity}= Set Variable ${response_content_json}[0][currentInventory]
Run Keyword If ${quantity}>10 Log Threshold Condition Pass ELSE Log Threshold Condition Fail
In this case, ${quantity} was 100.
Note two things:
after converting to JSON, variable values can be accessed alike dictionary type variables
To JSON keyword is from RequestsLibrary

WSO2 Script mediator unable to parse self closing XML tags

I'm using a script mediator to convert the XML response to a JSON. The mediator works properly if the XML is well formatted but if the XML has self closing tags , it fails..
Any ideas to fix this issue is greatly appreciated..
<!-- XML data-->
<getMyClsScheduleResponse >
<RegisteredClass>
<ClassNumber>10757</ClassNumber>
<SubjectCode>AAS</SubjectCode>
<CatalogNumber>510</CatalogNumber>
<SectionNumber>001</SectionNumber>
<SectionType>IND</SectionType>
<SectionTypeDescr>Independent Study</SectionTypeDescr>
<SessionDescr>Regular</SessionDescr>
<CourseDescr>Supervised Research</CourseDescr>
<ClassTopic />
<CreditHours>1 - 6</CreditHours>
<LMSURL /> <!-- Self Closing tag -->
<Meeting>
<MeetingNumber>1</MeetingNumber>
<Days />
<Times />
<StartDate>09/02/2014</StartDate>
<EndDate>12/10/2014</EndDate>
<Location>TBA</Location>
<TopicDescr />
</Meeting>
/** Script Mediator */
function transformPayload(output) {
payload = output.getPayloadJSON();
results = payload.getMyClsScheduleResponse.RegisteredClasses;
var response = new Array();
var registeredClass = new Array();
for (i=0;i<results.length; i++ ) {
class_schedule = results[i];
newcls = new Object();
newcls.Link = class_schedule.LMSURL; // Error at this line..
}
}
Error Log :
TID: [0] [ESB] [2014-10-24 14:19:45,541] ERROR - The script engine returned an error executing the external js script : Value {name ='null', keyValue ='conf:/repository/esb/js/functions.js'} function transformPayload {org.apache.synapse.mediators.bsf.ScriptMediator}
com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.WrappedException: Wrapped com.sun.phobos.script.util.ExtendedScriptException: org.mozilla.javascript.EvaluatorException: syntax error (<Unknown source>#1) in <Unknown source> at line number 1 (<Unknown source>#53) in <Unknown source> at line number 53
at com.sun.phobos.script.javascript.RhinoScriptEngine.invokeMethod(RhinoScriptEngine.java:259)
Thanks
Kranthi
According to the given scenario that issue will be occur with self closing tags(As you described).In the case of self closing tags it returns the value as null.Workaround for this to check the value in the js mediator and handle the null value in the case of the self closing tags.
You can use the following js function to set the value in such a scenario within the js mediator.
function assignValuesWithNull(value){
var returnValue;
if(!value){
returnValue='';
}
else{
returnValue=value;
}
return returnValue;
}
Why do you use script mediator to change XML to JSON? what you have to do is , set content-type properly to get required format response.

Mule - Pass Parameters to datamapper and access them in xpath conditions

How to pass parameters to datamapper in mule and access them. (In XSLT, I pass them as context parameters, receive them in param and access using $ symbol). I need to do the same thing in datamapper. Any suggestions/links/example are appreciated.
Approach1:
We are using invokeTransformer method in datamapper
output.abc= invokeTransformer("MyTransformer",input.abcdef);
This MyTransformer is a java component which has this default method overridden.
#Override
public String transformMessage(MuleMessage message, String outputEncoding)
throws TransformerException {
System.out.println("Inside transformer" +message.getProperty ("sessionVariable1",PropertyScope.SESSION));
return message.getProperty("sessionVariable1",PropertyScope.SESSION);
But, the problem is I am not calling this transformer from mule flow. But, invoking it from datamapper. Hence the argument 'message' does not get passed. So, Unable to retrive that session variable to return to datamapper. Is there a way to send this argument(MuleMessage from datamapper)?
You can use input arguments with DataMapper and then refer to them in the output:
<set-variable variableName="testvar" value="value of testvar"/>
<data-mapper:transform config-ref="new_mapping_grf"">
<data-mapper:input-arguments>
<data-mapper:input-argument key="testvar">#[flowVars['testvar']]</data-mapper:input-argument>
</data-mapper:input-arguments>
</data-mapper:transform>
and
output.myField = invokeTransformer("MyTransformer",inputArguments.testvar);
or
output.myField = inputArguments.testvar;
Adding input arguments available in the DataMapper GUI through the input side green plus icon.

params is empty when i call Post method on Grails

i'm writing webservices for my application.
my problem is that when i call it using GET method it works , but when i use the POST method params doesn't contains ant of my parameters:
when i call using GET , this is the content of params :
params : [username:azerty, test:test, param2:param2, action:editProfile, controller:userWebService]
when i call using POST, this is the content of params :
params : [action:editProfile, controller:userWebService]
EDIT :
/* user controller */
"/service/$action?"(controller: "userWebService", parseRequest: true)
in UserWebServiceController
....
static allowedMethods = [editProfile:['POST', 'GET']]
....
def editProfile(){
println "params : "+ params
....
}
to test i'm using REST console plugin in chrome
params are not sent as a query string in POST requests unlike GET. The parameter strings has to be embedded in the request body in case of POST request.
Use content-type: application/x-www-form-urlencoded
and in the request-body use
username=azerty&test=test
You should be able to see the parameters in params inside controller.
You should be able to see
params : [age:25, name:Hamila, action:editProfile, controller:userWebService]
Did I make you look younger in the test? :)