WSO2 Lopp through Json array - wso2-api-manager

This is my input Json :
How to get "Value" fields and set it to property?
[
{
"Name": "Утасны дугаар",
"Value": "95252351",
"ParameterName": "{xacparam01}",
"IsRequired": "1",
"MinLength": "5",
"MaxLength": "10",
"Type": "String"
},
{
"Name": "dans",
"Value": "99115544",
"ParameterName": "{xacparam02}",
"IsRequired": "1",
"MinLength": "5",
"MaxLength": "10",
"Type": "String"
},
{
"Name": "dfd",
"Value": "88554455",
"ParameterName": "{xacparam03}",
"IsRequired": "1",
"MinLength": "5",
"MaxLength": "10",
"Type": "String"
}
]
When i loop through json, i can only get last iteration
Desired Output :
{
"val1" : "95252351",
"val2" : "99115544",
"val3" : "88554455"
}

Generating field names for a JSON object is not possible. You can get an output like below by using the given proxy.
output JSON
{
"values": [
95252351,
99115544,
88554455
]
}
proxy service
<?xml version="1.0" encoding="UTF-8"?>
<proxy name="test2" startOnLoad="true" transports="http https" xmlns="http://ws.apache.org/ns/synapse">
<target>
<inSequence>
<log level="full">
<property name="log1" value="invoked"/>
</log>
<property name="messageType" scope="axis2" type="STRING" value="application/xml"/>
<property name="Content-Type" scope="transport" type="STRING" value="application/xml"/>
<log level="full">
<property name="log2" value="after conversion"/>
</log>
<foreach expression="//jsonArray/jsonElement" id="foreach">
<sequence>
<payloadFactory media-type="xml">
<format>
<values xmlns="">$1</values>
</format>
<args>
<arg evaluator="xml" expression="//jsonElement/Value" literal="true"/>
</args>
</payloadFactory>
</sequence>
</foreach>
<property name="messageType" scope="axis2" type="STRING" value="application/json"/>
<property name="Content-Type" scope="transport" type="STRING" value="application/json"/>
<respond/>
</inSequence>
<outSequence/>
<faultSequence/>
</target>
</proxy>

Related

how to add mediation for get token of WSO2 API Manager?

I Have This API And I Used the Message Mediation Below to Authenticate and Get the Token:
curl -X POST "URL" -H "accept: /" -H "Content-Type: application/x-www-form-urlencoded" -d "username=user&password=password"
result is:
enter image description here
<payloadFactory media-type="x-www-form-urlencoded">
<format>
{
"username":"user",
"password":"password"
}
</format>
<args>
</args>
</payloadFactory>
<header name="Content-Type" value="application/x-www-form-urlencoded" scope="transport" />
<property name="messageType" value="application/json" scope="axis2" type="STRING" />
<property name="REST_URL_POSTFIX" value="" scope="axis2" type="STRING" />
<call blocking="true">
<endpoint>
<http method="POST" uri-template="URL" />
</endpoint>
</call>
<property name="bearer-token" expression="json-eval($..token)" scope="default" type="STRING" />
<property name="REST_URL_POSTFIX" expression="get-property('resource')" scope="axis2" type="STRING" />
<header name="Authorization" expression="fn:concat('Bearer ', get-property('bearer-token'))" scope="transport" />
<payloadFactory media-type="x-www-form-urlencoded">
<format>$1</format>
<args>
<arg evaluator="xml" expression="get-property('request-body')" />
</args>
</payloadFactory>
But i have this error:
enter image description here
WSO2 API Manager Logs
INFO - LogMediator STATUS = Message dispatched to the main sequence. Invalid URL., RESOURCE = url, HEALTH CHECK URL = url
[2021-07-28 16:22:39,696] INFO - LogMediator STATUS = Message dispatched to the main sequence. Invalid URL., RESOURCE = url, HEALTH CHECK URL = url
Make sure that, you have provided the correct token endpoint url for the Call mediator
<call blocking="true">
<endpoint>
<http method="POST" uri-template="https://your-token-endpoint/oauth" />
</endpoint>
</call>

WSO2 ESB-How to pass dates with rest url

url likes:
http://ict.esg.ilfseducation.com`/gtrapi/api/profilesystem?`d1=17-10-2018&d2=17-10-2018
Iam trying this code to pass with dates dynamically d1 and d2 but not working.but how to pass dates with dynamically please any one suggest me.i have try this another url with sigle parms working fine.but dates was not working any one please suggeat me.
api:
<?xml version="1.0" encoding="UTF-8"?>
<api context="/gtrapi/api/profilesystem?" name="SCR_profileapi" xmlns="http://ws.apache.org/ns/synapse">
<resource methods="GET" protocol="http" uri-template="/{date1}/{date2}">
<inSequence>
<property description="http" name="HTTP_SC" scope="axis2" type="STRING" value="404"/>
<log level="full"/>
<send>
<endpoint key="SCR_profileendpoint"/>
</send>
</inSequence>
<outSequence>
<switch source="get-property('axis2','HTTP_SC')">
<case regex="200">
<log description="200log" level="custom">
<property expression="$ctx:ERROR_CODE" name="200reserrorcode"/>
</log>
<send/>
</case>
<default>
<log description="reslog" level="custom">
<property expression="$ctx:ERROR_CODE" name="reserrorcode"/>
<property expression="$ctx:ERROR_MESSAGE" name="reserrormessage"/>
<property expression="get-property('axis2','HTTP_SC')" name="reshttpsc"/>
</log>
</default>
</switch>
<send/>
</outSequence>
<faultSequence>
<switch source="get-property('axis2','HTTP_SC')">
<case regex="200">
<log description="200log" level="custom">
<property expression="$ctx:ERROR_CODE" name="200reserrorcode"/>
</log>
</case>
<default>
<log description="reslog" level="custom">
<property expression="$ctx:ERROR_CODE" name="reserrorcode"/>
<property expression="$ctx:ERROR_MESSAGE" name="reserrormessage"/>
<property expression="get-property('axis2','HTTP_SC')" name="reshttpsc"/>
</log>
</default>
</switch>
<send/>
</faultSequence>
</resource>
</api>
endpoint:
<?xml version="1.0" encoding="UTF-8"?>
<endpoint name="SCR_profileendpoint" xmlns="http://ws.apache.org/ns/synapse">
<http uri-template="http://ict.esg.ilfseducation.com/gtrapi/api/profilesystem?d1={uri.var.service.date1}&d2={uri.var.service.d2}" method="get">
</http>"/>
</endpoint>

getting "org.apache.http.nohttpresponseexception the target server failed to respond" while calling wso2 http endpoint

I am getting below error while calling http endpoint:-
The endpoint is HTTP endpoint which I am using.
Also added timeout parameters in axis2.xml and axis2.blocking.xml.
But it did not work.
Can anyone provide any solution to it?
HTTPSender Unable to sendViaPost to url[http://*********]
org.apache.commons.httpclient.NoHttpResponseException: The server ****** failed to respond
at org.apache.commons.httpclient.HttpMethodBase.readStatusLine(HttpMethodBase.java:1976)
at org.apache.commons.httpclient.HttpMethodBase.readResponse(HttpMethodBase.java:1735)
at org.apache.commons.httpclient.HttpMethodBase.execute(HttpMethodBase.java:1098)
the esb proxy looks like below:--
<?xml version="1.0" encoding="UTF-8"?>
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="mqListener"
startOnLoad="true"
statistics="disable"
trace="disable"
transports="http,https">
<target>
<inSequence>
<log description="print message" level="full">
<property name="message" value=""In listenAbc1Mq""/>
</log>
<payloadFactory media-type="json">
<format>
{
"orderId": ""
}
</format>
<args>
<arg evaluator="xml" expression="//verkkopvc/text()"/>
</payloadFactory>
<log description="print message" level="full">
<property name="message" value=""after payload factory""/>
</log>
<property name="OUT_ONLY" value="true"/>
<property name="DISABLE_CHUNKING"
scope="axis2"
type="STRING"
value="true"/>
<call blocking="true">
<endpoint key="abc"/>
</call>
<log description="print message" level="full">
<property name="message" value=""Out sequence""/>
</log>
</inSequence>
<outSequence/>
<description/>
</proxy>
I believe the error is printed by your http client. To fix it, do these.
1) Remove <property name="OUT_ONLY" value="true"/>
2) Add <respond/> mediator at the end of inSequence.

Active MQ tcp connection failure

am using Active MQ 5.10 version,I have configured it with wso2esb for message processing.
After around 7-10 days Active MQ is throwing tcp connections failure exception,since ESB is not receiving a successful tcp connection it is failing to submit messages in the Queue.
In this case am restarting the server and again it will run for 7-10 days and the same thing repeats.
my questions is
what may be the exact reason for active MQ stops giving successful tcp connection..?
why after restarting the server it returns to normal state..?
is there any best solution to over come this issue..
memory configuration in activemq.xml file
<systemUsage>
<systemUsage sendFailIfNoSpace="true">
<memoryUsage>
<memoryUsage limit="1430 mb"/>
</memoryUsage>
<storeUsage>
<storeUsage limit="300 gb"/>
</storeUsage>
<tempUsage>
<tempUsage limit="100 gb"/>
</tempUsage>
</systemUsage>
</systemUsage>
Here is the Proxy service which is placing message in queue. In the proxy service it will check the user authentication if its true the user can place the message in the queue, here i use a class mediator where in that it connects with the active MQ and places message
<proxy xmlns="http://ws.apache.org/ns/synapse"
name="JmsStore2.0"
transports="https http"
startOnLoad="true"
trace="disable"
statistics="enable">
<description/>
<target>
<inSequence onError="fault">
<property name="messageType" value="application/json" scope="axis2"/>
<property name="FORCE_ERROR_ON_SOAP_FAULT" value="true"/>
<property name="jmsuri" value="tcp://0.0.0.0:61616"/>
<property name="jmsqueue" expression="get-property('transport', 'jmsqueue')"/>
<property name="readingspayload" expression="$body" type="OM"/>
<property name="username" expression="get-property('transport', 'username')"/>
<property name="password" expression="get-property('transport', 'password')"/>
<property name="PartyBranchID"
expression="//FieldValue/text()"
scope="default"
type="STRING"/>
<property name="Body" expression="$body" scope="default" type="STRING"/>
<property name="usercode"
expression="fn:substring-before(get-property('username'),'|')"
scope="default"
type="STRING"/>
<property name="clientid"
expression="fn:substring-after(get-property('username'),'|')"
scope="default"
type="STRING"/>
<property name="requestMsgId"
expression="get-property('MessageID')"
scope="default"
type="STRING"/>
<property name="client_ip_address"
expression="get-property('axis2','REMOTE_ADDR')"
scope="default"
type="STRING"/>
<payloadFactory media-type="xml">
<format>
<send xmlns="">
<username>$1</username>
<password>$2</password>
</send>
</format>
<args>
<arg evaluator="xml" expression="get-property('username')"/>
<arg evaluator="xml" expression="get-property('password')"/>
</args>
</payloadFactory>
<send receive="JmsStore_Seq">
<endpoint>
<address uri="http://localhost:8282/services/Login2.0" format="soap11">
<suspendOnFailure>
<errorCodes>101500,101501,101506,101507,101508,101503,50000</errorCodes>
<initialDuration>30</initialDuration>
<progressionFactor>1.0</progressionFactor>
<maximumDuration>300</maximumDuration>
</suspendOnFailure>
</address>
</endpoint>
</send>
</inSequence>
<outSequence onError="fault">
<send/>
</outSequence>
</target>
</proxy>
Sequence:
<sequence xmlns="http://ws.apache.org/ns/synapse"
name="JmsStore_Seq"
trace="disable">
<property name="FORCE_ERROR_ON_SOAP_FAULT" value="true"/>
<property xmlns:ns="http://org.apache.synapse/xsd"
name="Authentication"
expression="//Authentication/text()"/>
<property xmlns:ns="http://org.apache.synapse/xsd"
name="UserId"
expression="//UserId/text()"
scope="default"
type="STRING"/>
<property xmlns:ns="http://org.apache.synapse/xsd"
name="WorkOUid"
expression="//WorkOUid/text()"/>
<property xmlns:ns="http://org.apache.synapse/xsd"
name="WorkPartyBranchId"
expression="//WorkPartyBranchId/text()"/>
<filter xmlns:ns="http://org.apache.synapse/xsd"
xpath="get-property('Authentication')=''">
<then>
<payloadFactory media-type="xml">
<format>
<ResponseJSON xmlns="">
<Exception>Service trying to connect inactive service</Exception>
<Status>101503</Status>
</ResponseJSON>
</format>
<args/>
</payloadFactory>
<property name="messageType" value="application/json" scope="axis2"/>
<property name="HTTP_METHOD" value="POST" scope="axis2" type="STRING"/>
<property name="RESPONSE" value="true" scope="default" type="STRING"/>
<property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
<send/>
</then>
<else>
<filter xpath="get-property('Authentication')='false'">
<then>
<payloadFactory media-type="xml">
<format>
<ResponseJSON xmlns="">
<Exception>Authentication Failed</Exception>
<Status>401</Status>
</ResponseJSON>
</format>
<args/>
</payloadFactory>
<property name="messageType" value="application/json" scope="axis2"/>
<property name="HTTP_METHOD" value="POST" scope="axis2" type="STRING"/>
<property name="RESPONSE" value="true" scope="default" type="STRING"/>
<property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
<send/>
</then>
<else>
<property name="jmspayload"
expression="get-property('readingspayload')"
type="OM"/>
<property name="ResponseJSON" expression="$body/ResponseJSON" type="OM"/>
<property name="jmsuri" expression="get-property('jmsuri')"/>
<property name="jmsqueue" expression="get-property('jmsqueue')"/>
<payloadFactory media-type="xml">
<format>
<PLData>
<JMpayload>$1</JMpayload>
<AuthData>$2</AuthData>
<LogData>
<usercode>$3</usercode>
<clientid>$4</clientid>
<requestMsgId>$5</requestMsgId>
</LogData>
</PLData>
</format>
<args>
<arg evaluator="xml" expression="get-property('jmspayload')"/>
<arg evaluator="xml" expression="get-property('ResponseJSON')"/>
<arg evaluator="xml" expression="get-property('usercode')"/>
<arg evaluator="xml" expression="get-property('clientid')"/>
<arg evaluator="xml" expression="get-property('requestMsgId')"/>
</args>
</payloadFactory>
<class name="in.youtility.esb.custommediators.JMSStoreMediator"/>
<payloadFactory media-type="xml">
<format>
<ResponseJSON xmlns="">
<Body>
<Datalist>
<Data>Successfully stored</Data>
</Datalist>
</Body>
<Status>200</Status>
</ResponseJSON>
</format>
<args/>
</payloadFactory>
<property name="messageType" value="application/json" scope="axis2"/>
<header name="To" action="remove"/>
<property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
<property name="RESPONSE" value="true"/>
<send/>
</else>
</filter>
</else>
</filter>
<description/>
</sequence>
Class Mediator:
public class JMSStoreMediator extends AbstractMediator implements
ManagedLifecycle {
Connection connection;
public boolean mediate(MessageContext msgCtx) {
try {
boolean topic=false;
String jmsuri=""+msgCtx.getProperty("jmsuri");
String t=""+msgCtx.getProperty("topic");
if(t.isEmpty()){
topic=false;
}
else {
topic=Boolean.valueOf(t);
}
ConnectionFactory factory= new ActiveMQConnectionFactory(jmsuri);
connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination=null;
if(!topic)destination= session.createQueue(""+msgCtx.getProperty("jmsqueue"));
else destination= session.createTopic(""+msgCtx.getProperty("jmsqueue"));
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
String xml = ""+msgCtx.getEnvelope().getBody().toStringWithConsume();
if(topic){
JSONObject obj=XML.toJSONObject(xml);
JSONObject ar=obj.getJSONObject("soapenv:Body");
ar.remove("xmlns:soapenv");
xml=ar.toString();
}
TextMessage message = session.createTextMessage(xml);
producer.send(message);
} catch (Exception e) {
log.info("LogLocation = "+getClass().getName()+",Error in storing message in JMS stacktrace is :"+e.toString());
((Axis2MessageContext) msgCtx).setProperty(NhttpConstants.HTTP_SC, 500);
handleException("Error while storing in the message store", msgCtx);
}
finally {
try {
connection.close();
} catch (JMSException e) {
log.info("LogLocation = "+getClass().getName()+",Error in closing JMS connection stacktrace is :"+e.toString());
}
}
log.info("LogLocation = "+getClass().getName()+",ProxyName = "+msgCtx.getProperty("proxy.name")+
",Usercode = "+msgCtx.getProperty("usercode")+",Clientid = "+msgCtx.getProperty("clientid")+
",requestMsgId = "+msgCtx.getProperty("requestMsgId")+",Position = END");
return true;
}
You should share your proxys conf but you can always verify that :
You've set the cachelevel to avoid new connections at each scan : <parameter name="transport.jms.CacheLevel">consumer</parameter>
You've asked to consume all messages a each scan : <parameter name="transport.jms.MaxMessagesPerTask">-1</parameter>

Unable to get http header

Hi I have the source view of my api from APIM and modified it to get the the htttp header "Authorization" and log it to the log file I added 2 entries in code one for insequence and one for outsequence. In the insequence I added the line
<property name="AuthHeader" expression="$trp:Authorization"/>
In order to get the header and assign it to a property. In the out sequence I added
<log level="custom">
<property name="AuthHeader value" expression="get-property('AuthHeader')"/>
</log>
To determine if the AuthHeader property will display and get the header, however inside the log file it was said that
TID: [0] [AM] [2014-11-19 04:23:01,997] INFO {org.apache.synapse.mediators.builtin.LogMediator} - AuthHeader value = null {org.apache.synapse.mediators.builtin.LogMediator}
TID: [0] [AM] [2014-11-19 04:23:07,335] INFO {org.apache.synapse.mediators.builtin.LogMediator} - AuthHeader value = null {org.apache.synapse.mediators.builtin.LogMediator}
TID: [0] [AM] [2014-11-19 04:56:17,177] INFO {org.apache.synapse.mediators.builtin.LogMediator} - AuthHeader value = null {org.apache.synapse.mediators.builtin.LogMediator}
Which means I'm not getting the correct http header value, is there something wrong with the code? Please help, the complete API code is below.
Thanks,
Drew
<api name="admin--fte" context="/fte">
<resource methods="POST GET DELETE OPTIONS PUT" url-mapping="/*">
<inSequence>
<property name="AuthHeader" expression="$trp:Authorization"/>
<property name="isDefault" expression="get-property('transport', 'WSO2_AM_API_DEFAULT_VERSION')"/>
<filter source="get-property('isDefault')" regex="true">
<then>
<log level="custom">
<property name="STATUS" value="Faulty invoking through default API.Dropping message to avoid recursion.."/>
</log>
<payloadFactory media-type="xml">
<format>
<am:fault xmlns:am="http://wso2.org/apimanager">
<am:code>500</am:code>
<am:type>Status report</am:type>
<am:message>Internal Server Error</am:message>
<am:description>Faulty invoking through default API</am:description>
</am:fault>
</format>
<args/>
</payloadFactory>
<property name="HTTP_SC" value="500" scope="axis2"/>
<property name="RESPONSE" value="true"/>
<header name="To" action="remove"/>
<property name="NO_ENTITY_BODY" scope="axis2" action="remove"/>
<property name="ContentType" scope="axis2" action="remove"/>
<property name="Authorization" scope="transport" action="remove"/>
<property name="Host" scope="transport" action="remove"/>
<property name="Accept" scope="transport" action="remove"/>
<send/>
</then>
<else>
<header name="WSO2_AM_API_DEFAULT_VERSION" scope="transport" value="true"/>
<property name="uri.var.portnum" expression="get-property('http.nio.port')"/>
<send>
<endpoint>
<http uri-template="http://localhost:{uri.var.portnum}/fte/1.0">
<timeout>
<duration>30000</duration>
<responseAction>fault</responseAction>
</timeout>
<suspendOnFailure>
<errorCodes>-1</errorCodes>
<initialDuration>0</initialDuration>
<progressionFactor>1.0</progressionFactor>
<maximumDuration>0</maximumDuration>
</suspendOnFailure>
<markForSuspension>
<errorCodes>-1</errorCodes>
</markForSuspension>
</http>
</endpoint>
</send>
</else>
</filter>
</inSequence>
<outSequence>
<property name="messageType" value="application/json" scope="axis2" type="STRING"/>
<log level="custom">
<property name="AuthHeader value" expression="get-property('AuthHeader')"/>
</log>
<send/>
</outSequence>
</resource>
<handlers>
<handler class="org.wso2.carbon.apimgt.gateway.handlers.common.SynapsePropertiesHandler"/>
</handlers>
</api>
By default, the Authorization header is removed by the Authentication handler. That's why you cant' seem to access it or log it. Handlers act before the mediation inSequence.
The Authentication header can be preserved by editing the api-manager.xml config file in /repository/conf. Simply uncomment the following node and change the value to false:
<RemoveOAuthHeadersFromOutMessage>false</RemoveOAuthHeadersFromOutMessage>

Resources