WSO2 EI - retrieving property set inside script - wso2

I'm trying to retrieve a property set inside a script mediator for later use, however it seems to be blank. This is my code:
<script language="js"><![CDATA[var log = mc.getServiceLog();
var payload = mc.getPayloadXML();
var numDevices5GHz = payload["Device.WiFi.AccessPoint.10101.AssociatedDeviceNumberOfEntries"];
log.info("numDevices5GHz :"+numDevices5GHz);
var devices5GHz = new Array(numDevices5GHz);
//formats 5GHz associated devices parameters
for(i = 0; i<numDevices5GHz; i++){
var device = new Object();
device.name="nome"+i;
device.value=i;
devices5GHz[i] = device;
}
mc.setProperty("devices5GHz",devices5GHz);
]]></script>
<log>
<property expression="get-property('devices5GHz')" name="DEVICES 5GHz"/>
</log>
and this is the result:
[2020-03-31 12:11:30,223] [EI-Core] INFO - CommonScriptMessageContext numDevices5GHz :1
[2020-03-31 12:11:30,224] [EI-Core] INFO - CommonScriptMessageContext name: nome0, value: 0
[2020-03-31 12:11:30,224] [EI-Core] INFO - LogMediator To: , WSAction: , SOAPAction: , MessageID: urn:uuid:44561262-94fa-4d92-99f0-d5a25e0d28bd, Direction: response, DEVICES 5GHz =
So, I can see that inside the script the devices5GHz Array has one member (this will later be populated with real data), but when I try to retrieve it outside the script it's empty. What am I doing wrong here?
Thanks.

This is because the javascript array object you are assigning inside the Script mediator, cannot be read by the Property mediator. If you can create an appropriate string inside the Script mediator and assign, then it would become accessible outside the Script mediator.

Related

How to get Request payload content at Response path class mediator using OMElement - WSO2 APIM ver 3.2.0

I am using WSO2 APIM version 3.2.0.
I have a POST request with the request payload.
In the response message mediation of WSO2 APIM I have added the policy that contains the class mediator that tries to get the payload sent during the request.
OMElement element = (OMElement) mc.getEnvelope().getBody().getFirstOMChild();
log.info("payload: " + element.toString());
The above code snippet prints the response payload content but I need the request payload content at the response path.
Response message mediation with a policy added
Below is the sequence with class mediator
sequence with class mediator
Code snippet inside class mediator
OMElement element = (OMElement) mc.getEnvelope().getBody().getFirstOMChild();
log.info("payload: " + element.toString());
Pls let me know what changes to be done, to get the request payload content.
First, we have to store the request payload in a custom property in the Message Context. Then, we can use that property to retrieve the Request Payload in the Response path of the execution.
For example: You are invoking an API with JSON Payload. So, we have to first capture the sent payload and store it in a custom property in the Message Context. Given below is a sample sequence to perform the same
<?xml version="1.0" encoding="UTF-8"?>
<sequence xmlns="http://ws.apache.org/ns/synapse" name="admin--MockAPI:v1.0.0--In">
<property name="RequestPayload" expression="json-eval($)" />
<log level="custom">
<property name="RequestPayload" expression="$ctx:RequestPayload" />
</log>
</sequence>
Then, in the Response path, inside your custom class mediator, you have to access the RequestPayload property from the MessageContext to extract the stored payload. You can achieve this by using the following snippet
synapseContext.getProperty("RequestPayload");

WSO2 API Manager change http method

Does wso2 api manager v1.10.0 permit transforming the HTTP method of the request to the backend through custom in sequence?
I created an api with http GET resource through publisher web console. But since the endpoint support POST method only, i tried changing the HTTP Method by creating custom in sequence with property mediator :
<property name="HTTP_METHOD" value="POST" scope="axis2"/>
but the response showed a fault message :
{
"fault": {
"code": 403,
"type": "Status report",
"message": "Fault Call",
"description": "No matching resource found in the API for the given request"
}
}
The log files only showed these lines :
==> /opt/wso2am-gateway/repository/logs/wso2carbon.log <==
[2016-04-08 10:30:16,868] INFO - STATUS = Executing default 'fault' sequence, ERROR_CODE = 403, ERROR_MESSAGE = No matching resource found in the API for the given request {org.apache.synapse.mediators.builtin.LogMediator}
If i remove the property mediator, the request pass through and reach the backend.
Does anyone know how to solve this problem?
You can use the following custom inFlow mediation sequence to convert the HTTP_METHOD into POST from GET.
<?xml version="1.0" encoding="UTF-8"?>
<sequence name="CustomIn" xmlns="http://ws.apache.org/ns/synapse">
<property action="remove" name="HTTP_METHOD" scope="axis2"/>
<property name="HTTP_METHOD" scope="axis2" type="STRING" value="POST"/>
</sequence>
Here, the request is the GET request from the client-side.
But, the above solution will be possible only when you are defining the GET and the POST resources similarly on your API (Although you don't use one of the both).
Otherwise, you will get the following error messages while you are invoking the API.
No matching resource found for given API Request
Method not allowed for given API resource
No matching resource found in the API for the given request
You need to also define POST resource on your API (although you don't use it)

How to reserve property value between every task call

I used WSO2 ESB schedule task to fetch data from external system, the task call my proxy service every 5 seconds. In my proxy service, I used a property name "startTime" and "endTime", it means I want to fetch data from "startTime" to "endTime". "startTime" and "endTime" should be increase 5 seconds every task call.
But it seems ESB cannot store these properties(startTime and endTime) between every task call. I try to use the script to write the "startTime" :
importPackage(Packages.org.apache.synapse.config);
var id = mc.getProperty("id");
var res = "conf/data_task/"+id ;
var startTimeInReg = mc.getProperty("_endTime");
mc.getConfiguration().getRegistry().updateResource(res+"/startTime", startTimeInReg.toString());
and get it
<property expression="get-property('registry', fn:concat('conf/data_task/',get-property('id'),'/startTime'))"
name="startTimeInReg" scope="default" type="STRING"/>
I can get the "startTime", but it remain the same value , and I found that after 2 or 3 times schedule task call ( maybe elaps more than 15s ), the value of startTime change.
I think this maybe caused by ESB caching , how I can commit the changing of the startTime value immediately after updateResource method called. Or how can solve this issue.
Try to save your value in the governance registry :
mc.getConfiguration().getRegistry().newResource("gov:/trunk/test/MyCounter.txt",false); // create the resource the 1st time, does nothing the others
mc.getConfiguration().getRegistry().updateResource("gov:/trunk/test/MyCounter.txt", startTimeInReg.toString());
An other solution, have a look at this sample that create a "global" counter (lost when the ESB is restarted) :
<script language="js"><![CDATA[
var curValue = mc.getEnvironment().getServerContextInformation().getProperty("MyCounter");
if (curValue == null) {
curValue = 0;
} else {
curValue++;
}
mc.getEnvironment().getServerContextInformation().addProperty("MyCounter",curValue);
mc.setProperty("MyCounter",curValue);
]]></script>

Error when accessing ESB Proxy with Jaggery WSStub

I created a web service and was able to send requests to it from a serverside Jaggery.js script with no problem. Then I created a WSDL Proxy Service inside WSO2 ESB and tested it using the "Try it!" feature.
After I redirected my serverside script from the original web service to its proxy inside ESB, I got the error in System Logs:
The endpoint reference (EPR) for the Operation not found is /services/BpmAdderProcessProxy.BpmAdderProcessProxyHttpSoap11Endpoint and the WSA Action = urn:anonOutInOpResponse. If this EPR was previously reachable, please contact the server administrator.
To see in detail what was happening I activated the "SOAP Message Tracer" of the ESB. Suddenly my serverside script could access the webservice via my ESB proxy. Then I deactivated the "SOAP Message Tracer" and the error message was back again. Is my serverside script correct? Or does the debugging tool modify behavior of debugged code?
I'm a JavaScript developer. Actually Jaggery and UES are targeted at people like me. I'm not supposed to look inside Java code, am I? Is there a forum where JavaScript developers discuss WSO2 UES and Jaggery?
My serverside code is as follows:
<%
var x = request.getParameter("x");
var y = request.getParameter("y");
//var sum = parseInt(x) + parseInt(y);
var sum = add(parseInt(x), parseInt(y));
response.content = {
success: true,
data: {
result: sum
}
};
function add(x, y) {
var ws = require('ws');
var stub = new ws.WSStub("http://02-128:8280/services/BpmAdderProcessProxy?wsdl");
var process = stub.services["BpmAdderProcessProxy"].operations["process"];
var payloadTemplate = process.payloadXML();
var payload = replaceQuestionMarks(payloadTemplate, arguments);
var resultXml = process.request(payload);
var resultValue = resultXml.children().text();
return parseInt(resultValue);
}
function replaceQuestionMarks(template, values) {
var i = 0;
return template.replace(
/\?/g,
function() {
return values[i++];
}
);
}
%>
In ESB v4.8.1, pass-through transport is enabled by default and it does not support SOAP body based dispatching (it does not build the message so it can't acces the body's first element to find the operation)
You can append the operation name to the endpoint url : http://host:8280/services/BpmAdderProcessProxy/OperationName
You can add this parameter in your proxy conf (BpmAdderProcessProxy) in WSO2 ESB : <parameter name="disableOperationValidation" locked="false">true</parameter>
You can edit wso2esb/repository/conf/axis2/axis2.xml and replace <handler class="org.apache.axis2.dispatchers.SOAPMessageBodyBasedDispatcher" name="SOAPMessageBodyBasedDispatcher"/>
with
<handler class="org.apache.synapse.core.axis2.SynapseSOAPMessageBodyBasedDispatcher" name="SOAPMessageBodyBasedDispatcher"/>

How to know the client Url in WSO2esb

i am getting messages from Proxy client how could i know client url means i want to do a filter condition based on url so in that case i could know that which url hitting me
i have tried with some sample code nut its notworking my code like this
<property name="client_url" expression="get-property('From')"/>
and also i logged it but its not returning null log is like this
LogMediator To: /services/RoleDetails, MessageID: urn:uuid:695faeb5-b26e-405d-ab7b-ce27213f5cbe, Direction: request, client_url = null
same thing working for
<property name="client_url" expression="get-property('To')"/>
Log for his
LogMediator To: /services/RoleDetails, MessageID: urn:uuid:a550ba76-201d-48c8-b069-3afdbb2b2db1, Direction: request, client_url = /services/RoleDetails
how could i know the client uri
I think You need to set 'From' property from your client.
But you can do something like this.
<property name="from property------->" expression="get-property('axis2','REMOTE_ADDR')"/>
and
<property name="from property------->" expression="get-property('axis2','REMOTE_HOST')"/>
you have to get that from axis2 context. refer this post