I have following JSON data:
{
"CustomerNames":{
"Update":[
{
"CustName":"Name1",
"id":"3"
},
{
"CustName":"Name3",
"id":"32"
}
],
"Create":[
{
"Name":"Name2"
}
]
}
}
If the Update JSONARray exists I need to call UpdateCustomer Sequence. And if the Create JSONArray exists I need to call CreateCustomer Sequence. I am trying to achieve this using Conditional Router Mediator. I have tried the below code for conditional routing:
<property expression="json-eval($.CustomerNames.Update)" name="CREATE_PAYLOAD" scope="default" type="STRING"/>
<property expression="json-eval($.CustomerNames.Create)" name="UPDATE_PAYLOAD" scope="default" type="STRING"/>
<conditionalRouter continueAfter="true">
<conditionalRoute asynchronous="true" breakRoute="false">
<condition>
<match regex="true" source="boolean(get-property('CREATE_PAYLOAD'))"/>
</condition>
<target sequence="CREATE_CUSTOMER"/>
</conditionalRoute>
<conditionalRoute asynchronous="true" breakRoute="false">
<condition>
<match regex="true" source="boolean(get-property('UPDATE_PAYLOAD'))"/>
</condition>
<target sequence="UPDATE_CUSTOMER"/>
</conditionalRoute>
</conditionalRouter>
But this is not giving desired output. Am I doing anything wrong here?
The Conditional Router Mediator was removed from EI 6.5.0 onwards and the latest version doesn't support it. Therefore you may need to use the Switch Mediator to call the required sequences. In the Switch Mediator, if a matching case is found, it will be executed, and the remaining switch cases are not processed. Since you need to call both sequences, you can use two switch mediators as follows,
<property expression="json-eval($.CustomerNames.Update)" name="CREATE_PAYLOAD" scope="default" type="STRING"/>
<property expression="json-eval($.CustomerNames.Create)" name="UPDATE_PAYLOAD" scope="default" type="STRING"/>
<switch source="boolean(get-property('CREATE_PAYLOAD'))">
<case regex="true">
<sequence key="CREATE_CUSTOMER"/>
</case>
<default/>
</switch>
<switch source="boolean(get-property('UPDATE_PAYLOAD'))">
<case regex="true">
<sequence key="UPDATE_CUSTOMER"/>
</case>
<default/>
</switch>
For more information check https://ei.docs.wso2.com/en/latest/micro-integrator/references/mediators/switch-Mediator/
Related
I have a REST API on Enterprise Integrator that uses a db lookup mediator to search a microsoft sql server database and redirects based on the whether or not the data exists in the db. I need to make the redirect part of the code configurable/dynamic as it wouldn't make sense to constantly update the url and redeploy every time the url changes.
<api xmlns="http://ws.apache.org/ns/synapse" name="DBLookupAPI" context="/dblookup">
<resource methods="GET" uri-template="/{UserCode}">
<inSequence>
<log level="custom">
<property name="Value" expression="get-property('uri.var.UserCode')"/>
</log>
<dblookup>
<connection>
<pool>
<driver>com.microsoft.sqlserver.jdbc.SQLServerDriver</driver>
<url>jdbc:sqlserver://10.1.1.111\test;databaseName=UserDB</url>
<user>admin</user>
<password>admin</password>
</pool>
</connection>
<statement>
<sql>select UserCode from UserDB.dbo.Users where UserCode =?;</sql>
<parameter expression="get-property('uri.var.UserCode ')" type="CHAR"/>
<result name="foundnr" column="UserCode "/>
</statement>
</dblookup>
<log level="custom">
<property name="Value" expression="get-property('foundnr')"/>
</log>
<filter source="boolean(get-property('foundnr'))" regex="true">
<then>
<log>
<property name="Message" value="Name Exists Lets redirect"/>
</log>
<property name="HTTP_SC" value="302"/>
<property name="Location" value="https://wso2.com/" scope="transport"/>
</then>
<else>
<log>
<property name="Message" value="Name Does Not Exist Lets redirect"/>
</log>
<property name="HTTP_SC" value="302"/>
<property name="Location" value="https://www.youtube.com/" scope="transport"/>
</else>
</filter>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</resource>
</api>
You can use the property mediator as below.
<property name="Location" expression="get-property('registry','REGISTRY_PATH')"/>
Below are the possible options for get-property method.
Read from registry
get-property('registry', String registryPath#propertyName)
get-property('registry', String registryPath)
Read from Java System property
get-property('system', String propertyName)
Read from the environment
get-property('env', String propertyName)
Read from a file
get-property('file', String propertyName)
Read from the context
You can use the class mediator or any other mediator and set the redirect url to the context and use the following property mediator to retrieve it from the context.
<property name="Location" expression="$ctx:ERROR_MESSAGE"/>
Please refer the documentation - https://ei.docs.wso2.com/en/latest/micro-integrator/references/mediators/property-reference/accessing-properties-with-xpath/#get-property-function
There are different ways to do this. One way is to read from environment variables. In the following example the Location property is set from the environment variable named REDIRECT_URL.
<property name="Location" expression="get-property('env','REDIRECT_URL')" scope="transport"/>
After reading of WSO2 EI References, I still confuse about how use iterators inside a EI sequence.
In my case I have a payload like this....
{
...
"array": [
{"cpf": "12345678911"},
{"cnpj":"12345678912346"}
]
}
So I have to iterate to check if those guys exist using another web services. in order to achieve that flow, I am using the iterate mediator to split the message and then building the logic to make those validations as follows..
The code that implements this image is following:
<iterate description="" expression="//jsonObject/array" id="myid">
<target>
<sequence>
<property expression="json-eval($.array.cpf)" name="tipoCPF" scope="default" type="STRING"/>
<filter description="" xpath="boolean(get-property('tipoCPF'))">
<then>
<property expression="json-eval($.array.cpf)" name="uri.var.cpf" scope="default" type="STRING"/>
<call>
<endpoint>
<http method="get" uri-template="http://endpoint/service/{uri.var.cpf}"/>
</endpoint>
</call>
<filter regex="200" source="get-property('axis2','HTTP_SC')">
<then/>
<else>
<payloadFactory description="" media-type="json">
<format>{
"code":"400",
"error":"CPF inexistente"
}</format>
<args/>
</payloadFactory>
<property name="HTTP_SC" scope="axis2" type="STRING" value="400"/>
<respond/>
</else>
</filter>
</then>
<else>
<property expression="json-eval($.array.cnpj)" name="tipoCNPJ" scope="default" type="STRING"/>
<filter xpath="boolean(get-property('tipoCNPJ'))">
<then>
<property expression="json-eval($.array.cnpj)" name="uri.var.cnpj" scope="default" type="STRING"/>
<header name="Authorization" scope="transport" value="Basic Y29yZS5jb25zdWx0aW5nOm8xNXRyZWI="/>
<call>
<endpoint>
<http method="get" uri-template="http://endpoint/service/cnpj/{uri.var.cnpj}"/>
</endpoint>
</call>
<filter regex="200" source="get-property('axis2','HTTP_SC')">
<then/>
<else>
<payloadFactory media-type="json">
<format>{
"code":"400",
"error":"CNPJ inexistente"
}</format>
<args/>
</payloadFactory>
<property name="HTTP_SC" scope="axis2" type="STRING" value="400"/>
<respond/>
</else>
</filter>
</then>
<else>
<call>
<endpoint>
<http method="get" uri-template="http://endpoint/service/info"/>
</endpoint>
</call>
</else>
</filter>
</else>
</filter>
</sequence>
</target>
</iterate>
This iterator work as part inside of the an 'insequence'. The 'Insequence' is deigned to allow to insert new contracts information inside the Database.
Problem: after add this iterator, the service starts to make duplicated insertions inside Database. It´s looks like the iteration don´t finish in the edge of tags 'iterator'. It´s like the iteration continues to the rest of insequence.
Try: In order to solve this problem i try to add an aggregator mediator after the iterator. But or doesn't have any effect end the duplicated insert persist, or I receive an error message.
So What is the correct whey to make this iterations inside WSO2 EI?
As you have mentioned, Iteration will occur even outside the iterate tag, until the Aggregate mediator is used. To resolve this issue, you need to add the aggregate mediator inside the iterate mediator. This will stop the iteration within the iterator tag itself.
For your use case, you may need to set continueParent="true" in the IterateMediator, so that the mediation will continue after the iterate mediator for the insertion Operation in database.
Thanks for the helping Arunan!
After your answer I try to add the Aggregator as follows
The config of aggregator is following:
...
<aggregate id="NIRO">
<completeCondition>
<messageCount max="-1" min="-1"/>
</completeCondition>
<onComplete expression="//jsonObject">
<log description="" level="full" separator=";">
<property expression="json-eval($.)" name="jsonObject"/>
</log>
</onComplete>
</aggregate>
</sequence>
</target>
</iterate>
As you sad I change the iterator property 'Continue Parent' to 'true'. But the problem persists....
As proposed in the other answer, you need to
use an Aggregate mediator to close the iteration
If and only if the Iterator is set to continueParent="true"
However, I am not sure that putting it inside the <iterate> works. Here is a working solution using an Aggregate mediator right after your Iterator.
<sequence>
<iterate continueParent="true" description="" expression="//jsonObject/array" id="myid">
<target>
<your_sequence />
</target>
</iterate>
<aggregate>
<completeCondition>
<messageCount max="-1" min="-1" />
</completeCondition>
<onComplete enclosingElementProperty="//jsonObject/array" expression="/whatever/you/want"/>
</aggregate>
</sequence>
Notice expression="//jsonObject/array" you used in your Iteration, you'll need to use it in the Aggregator's enclosingElementProperty. This is how your EI will know from which iterator it should aggregate from (not 100% sure about this point, more of an empirical consideration).
I'm using ESB-4.9.0 version.
An ESB mediation flow has to be continued based on two filtering logic. JSON message is transformed in the mediation flow. Currently, I'm using two Filter mediators to achieve this. Is there any possibility to use a single filter mediator to fulfill the same scenario?
Input JSON message
{
"filterId": "CorrectId",
"approvalStatus": "approved",
"lifeCycleStatus": "BRANCH_READY",
"channelData": [
{
"status": "pending",
"indexId": "correctIndexId",
"description": "Test Description"
}
]
}
The used ESB Synapse part
<filter description="" regex="CorrectId" source="json-eval($.filterId)">
<then>
<filter description="" regex="correctIndexId" source="json-eval($.indexId)">
<then>
<!-- continue the mediation flow-1-->
</then>
<else>
<!-- continue the mediation flow-2-->
</else>
</filter>
</then>
<else>
<drop/>
</else>
</filter>
Yes, this is possible with a filter mediator and the xpath concat function:
<resource methods="POST" uri-template="/onefilter">
<inSequence>
<property name="filterId" expression="json-eval($.filterId)"/>
<property name="correctIndexId" expression="json-eval($.channelData[0].indexId)"/>
<property name="combinedID" expression="fn:concat($ctx:filterId, $ctx:correctIndexId)"/>
<filter source="$ctx:combinedID" regex="CorrectIdcorrectIndexId">
<then>
<log level="custom">
<property name="message" value="continue 1"/>
</log>
<drop/>
</then>
<else>
<log level="custom">
<property name="message" value="continue 2"/>
</log>
<drop/>
</else>
</filter>
</inSequence>
By the way your code snippet would NEVER go into the continue 1 route because your JSON path is invalid.
I am very new in WSO2 ESB and I have the following doubt about how to implement an "if(){...} else{...}" like structure in my ESB project.
So in the input flow of the application on which I am working I have this property mediator followed by a log mediator that simply print the value of this property, something like this:
<property expression="count(//ds:Sample)" name="total_samples" scope="default" type="STRING" xmlns:ds="http://ws.wso2.org/dataservice"/>
<log level="custom">
<property expression="$ctx:total_samples" name="total samples: "/>
</log>
This works fine.
This total_samples property contains the number of record obtained from a previous call of a DSS service (I am not putting here in the code).
So the value of this total_samples property could be:
0: if the the query implemented by the DSS service returned 0 records.
A numeric value >0: if this query returned some records.
Now what I need to do at this time is only to chain a n "if(){...} else{...}" structure that print different log message if the total_samples property value is 0 or whatever number >0.
It should be a ver simple task but I have some doubts about how achieve it:
FIRST DOUBT: Looking on the online documentation it seems to me that exists 2 mediator that can be used to perform choice in the WSB flow: the switch mediator and the filter mediator. They seems to me very similar. What are the difference between these mediators? And what is better for my purpose?
SECOND DOUBT: It seems to me that these mediators works only on XPATH expression (something like count(//ds:Sample)), can they work directly on my property (something like "$ctx:total_samples") ?
THIRD DOUBT: At this stage I have implemented something like this in my flow:
<property expression="count(//ds:Sample)" name="total_samples" scope="default" type="STRING" xmlns:ds="http://ws.wso2.org/dataservice"/>
<log level="custom">
<property expression="$ctx:total_samples" name="total samples: "/>
</log>
<filter xpath="EXPRESSION THAT DO SOMETHING LIKE: $ctx:total_samples == 0">
<then>
<log description="No Resource Log">
<property name="message" value=""EMPTY RESULTSET, NO RESOURCES TO PROCESS""/>
</log>
</then>
<else>
<log description="Found Resource Log">
<property name="message" value=""Resources have been found, will be processed""/>
</log>
</else>
</filter>
Ok so my problem is: What have I to use as expression to enter in the case if the $ctx:total_samples value is 0 in the following line?
<filter xpath="EXPRESSION THAT DO SOMETHING LIKE: $ctx:total_samples == 0">
A more generic solution:
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="testIfElse"
transports="https http"
startOnLoad="true">
<target>
<inSequence>
<payloadFactory media-type="xml">
<format>
<ds:Sample xmlns:ds="http://ws.wso2.org/dataservice">
<ds:INT_ID>1</ds:INT_ID>
<ds:INT_ID>2</ds:INT_ID>
<ds:INT_ID>3</ds:INT_ID>
</ds:Sample>
</format>
<args>
</args>
</payloadFactory>
<property expression="count(//ds:Sample/ds:INT_ID)" name="total_samples" scope="default" xmlns:ds="http://ws.wso2.org/dataservice" type="DOUBLE"/>
<property value="0" name="initial_value" scope="default" type="DOUBLE"/>
<property expression="fn:number($ctx:total_samples) > fn:number($ctx:initial_value)" name="result" scope="default"/>
<log level="custom">
<property expression="$ctx:initial_value" name="initial value: "/>
<property expression="fn:number($ctx:total_samples)" name="total samples: "/>
<property expression="$ctx:result" name="if total samples greater than initial value: "/>
</log>
<filter xpath="$ctx:result" regex="true">
<then>
<log description="Found Resource Log">
<property name="message" value=""Resources have been found, will be processed""/>
</log>
</then>
<else>
<log description="No Resource Log">
<property name="message" value=""EMPTY RESULTSET, NO RESOURCES TO PROCESS""/>
</log>
</else>
</filter>
</inSequence>
<outSequence>
<log level="full"/>
<drop/>
</outSequence>
<faultSequence/>
</target>
</proxy>
Use this expression
<filter xpath="fn:number(get-property('total_samples')) = fn:number(0)">
you are really asking three questions here so I'll try to answer all of them:
The Switch mediator allows for multiple cases, so for example you could have a case for count = 0, count = 1 and count > 1. The filter mediator on the other hand is like the classic if/else. If this than do x, else do .
The filter mediator can either work comparing some value with a regular expression using the 'source' and 'regex' attributes in which case it checks if they match. Or it uses the xpath attribute in which case it evaluates the result of the xpath expression as a boolean. In the xpath expression as well as the source you can refer directly to your property using $ctx. For example:
What you could do is
<filter xpath="fn:number($ctx:total_samples) = fn:number(0)">
I want to customize the error messages sent by api manager, for instance when an access token is missing or expired. I've configured _auth_failure_handler_ to return messages in json as described here, and get responses like:
{"fault":{"code":"900902","message":"Missing Credentials","description":"Required OAuth credentials not provided"}}
I would like to modify the message description and remove the "code" altogether. Is there a way to do this? I've tried tweaking the sequence with no luck.
You need to target the error codes from https://docs.wso2.com/display/AM260/Error+Handling and update it to your custom JSON messages. For auth token related errors try modify _auth_failure_handler_ as below:
<sequence name="_auth_failure_handler_" xmlns="http://ws.apache.org/ns/synapse">
<property name="error_message_type" value="application/json"/>
<filter source="get-property('ERROR_CODE')" regex="405">
<then>
<sequence key="converter"/>
<drop/>
</then>
<else>
</else>
</filter>
<filter source="get-property('ERROR_CODE')" regex="900901">
<then>
<sequence key="invalidCredential"/>
<drop/>
</then>
<else>
</else>
</filter>
<filter source="get-property('ERROR_CODE')" regex="900902">
<then>
<sequence key="missingCredential"/>
<drop/>
</then>
<else>
</else>
</filter>
<sequence key="_cors_request_handler_"/>
For your case Missing Credential has a 900902 code , so it will match and need to define missingCredential.xml as below :
<?xml version="1.0" encoding="UTF-8"?>
<sequence xmlns="http://ws.apache.org/ns/synapse" name="missingCredential">
<payloadFactory media-type="json">
<format>{ "status": "Error","message": "Missing Credentials" }</format>
<!--Add your custom message and format here. This will be your output-->
</payloadFactory>
<property name="RESPONSE" value="true"/>
<header name="To" action="remove"/>
<property name="HTTP_SC" value="401" scope="axis2"/>
<property name="messageType" value="application/json" scope="axis2"/>
<send/>
</sequence>
It is not wise advice to modify the error code. Nevertheless, yes it is possible to modify the payload. Use the filter mediator and Json path and identify the data and use enrich mediator to modify the payload as you want.