How to know the client Url in WSO2esb - wso2

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

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 APIM-Analytic service (version:2.6.0) is not able to send the alert emails

In order to test this function, I chosed Abnormal Request Count option, which is in Alert Management menu of Api Store, and added a restful api. Then I called this api for many times by Postman.
The carbon.log, which is in <API-M_ANALYTICS_HOME>/wso2/worker/logs, recorded the following error message:
[2020-10-19 11:03:36,094] ERROR {org.wso2.siddhi.core.stream.output.sink.Sink} - Error on 'APIM_ALERT_EMAIL_NOTIFICATION'. Dropping event at Sink 'email' at 'EmailNotificationStream' as its still trying to reconnect!, events dropped '<strong>Message:</strong>A request from a new IP (10.9.16.77) detected by user:admin#carbon.super using application:devMap owned by admin#carbon.super. <br><br> <strong>Type:</strong>UnusualIPAccess <br><br> <strong>AlertTimestamp:</strong>2020-10-19 11:03:35'
[2020-10-19 11:06:10,307] ERROR {org.wso2.siddhi.core.stream.output.sink.Sink} - Error on 'APIM_ALERT_EMAIL_NOTIFICATION'. Dropping event at Sink 'email' at 'EmailNotificationStream' as its still trying to reconnect!, events dropped '<strong>Message:</strong>Abnormal request count detected during last minute using application devMap owned by admin#carbon.super for api :全球风向查询, abnormal request count:9. <br><br> <strong>Type:</strong>AbnormalRequestsPerMin <br><br> <strong>AlertTimestamp:</strong>2020-10-19 11:06:10'
About detailed configuration, I referred the following links:
Configuring Alerts:
https://docs.wso2.com/display/AM260/Configuring+Alerts#ConfiguringAlerts-ConfiguringalertsviatheStore
Enabling Notifications:
https://docs.wso2.com/display/AM260/Enabling+Notifications
According to these documents, I did the following things:
1.Open the <API-M_ANALYTICS_HOME>/conf/worker/deployment.yaml file to configure the sender email address. The sample code is shown below:
siddhi:
extensions:
...
-
extension:
name: email
namespace: sink
properties:
username: abcd#163.com
address: abcd#163.com
password: xxxx
...
2.Go to the <API-M_ANALYTICS_HOME>/resources/apim-analytics/ directory. Copy the APIM_ALERT_EMAIL_NOTIFICATION.siddhi file and paste it in the <API-M_ANALYTICS_HOME>/wso2/worker/deployment/siddhi-files directory.
3.Set the email server configurations in the <API-M_HOME>/repository/conf/output-event-adapters.xml file under the section.
<adapterConfig type="email">
<!-- Comment mail.smtp.user and mail.smtp.password properties to support connecting SMTP servers which use trust
based authentication rather username/password authentication -->
<property key="mail.smtp.from">abcd#163.com</property>
<property key="mail.smtp.user">abcd</property>
<property key="mail.smtp.password">xxxx</property>
<property key="mail.smtp.host">smtp.163.com</property>
<property key="mail.smtp.port">25</property>
<property key="mail.smtp.starttls.enable">true</property>
<property key="mail.smtp.auth">true</property>
<!-- Thread Pool Related Properties -->
<property key="minThread">8</property>
<property key="maxThread">100</property>
<property key="keepAliveTimeInMillis">20000</property>
<property key="jobQueueSize">10000</property>
</adapterConfig>
4.Log in to the Management Console and click Main > Resource > Browse. Browse to the /_system/config/apimgt/applicationdata/tenant-conf.json file and click Edit as Text.Set the NotificationsEnabled property to true as shown below:
"NotificationsEnabled":"true",
"Notifications":[{
"Type":"new_api_version",
"Notifiers" :[{
"Class":"org.wso2.carbon.apimgt.impl.notification.NewAPIVersionEmailNotifier",
"ClaimsRetrieverImplClass":"org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever",
"Title": "Version $2 of $1 Released",
"Template": " <html> <body> <h3 style=\"color:Black;\">We’re happy to announce the arrival of the next major version $2 of $1 API which is now available in Our API Store.</h3>Click here to Visit WSO2 API Store</body></html>"
}]
}
]
I've also checked APIM_ALERT_EMAIL_NOTIFICATION.siddhi:
#App:name("APIM_ALERT_EMAIL_NOTIFICATION")
#App:description('Send email to all the subscribers of a particular alert')
#source(type="inMemory", topic="APIM_EMAIL_NOTIFICATION", #map(type='passThrough'))
define stream EmailAlertStream (
type string,
message string,
alertTimestamp string,
emails string);
#sink(type='email', content.type="text/html", #map(type ='text', #payload('<strong>Message:</strong>{{message}} <br><br> <strong>Type:</strong>{{type}} <br><br> <strong>AlertTimestamp:</strong>{{alertTimestamp}}')),subject='Alerts from WSO2 APIM Analytics',to='{{emails}}')
define stream EmailNotificationStream (
type string,
message string,
alertTimestamp string,
emails string);
from EmailAlertStream
select *
insert into EmailNotificationStream;
As you can see, there is nothing special.
Have I missed anything to do? I don't know what the problem is, please help me.
As per the exceptions you received. Looks like there are issues with connecting to the SMTP server. Can you please check the configurations and check there are any restrictions to use your email.
ex: in Gmail, you have to enable 'untrusted applications' to access Gmail.
I've found the reason of this problem.
By reading the source code (EmailSink.java), I know the information of SMTP Server should be configured in APIM_ALERT_EMAIL_NOTIFICATION.siddhi, otherwise the analytic server is going to use smtp.gmail.com by default.

WSO2 EI - retrieving property set inside script

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.

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)

CXF RestFul Service - Get Post Body Parameters

I have developed a webservice following the below link, however I am unable to get the request parameters from the POST request body.
http://info.appdirect.com/blog/how-to-easily-build-rest-web-services-with-java-spring-and-apache-cxf
I use the Soap UI to invoke the
service, with "Post QueryString in Message Body" option checked.
So far, I have tried below options, but none seem to work:
Tried MultiValued Map, but the map is always empty.
#POST
#Path("/getpostfile/{fileName}")
#Produces("application/pdf")
#Consumes("application/x-www-form-urlencoded")
public Response getPostFile(MultivaluedMap form){...}
Tried #FormParam() & #QueryParam as well, but still the params are null in webservice method.
Tried creating a POJO bean with #XmlRootElement annotation, however this time I get an exception saying "SEVERE: No message body reader has been found for class com.wcc.LoginInfo, ContentType: application/x-www-form-urlencoded". LoginInfo is my bean class with two parameters:
#XmlRootElement
public class LoginInfo {
String username;
String password;
....
Below is the service method:
#POST
#Path("/getpostfile/{fileName}")
#Produces("application/pdf")
#Consumes("application/x-www-form-urlencoded")
public Response getPostFile(LoginInfo logininfo){...}
Below is my cxf-beans.xml file:
<bean .....>
<jaxrs:server id="wccservice" address="/">
<jaxrs:serviceBeans>
<ref bean="wccdocumentservice" />
</jaxrs:serviceBeans>
<jaxrs:providers>
<ref bean="formUrlEncodeProvider" />
</jaxrs:providers>
</jaxrs:server>
<bean id="wccdocumentservice" class="com.wcc.WCCDocumentServiceImpl" />
<bean id="formUrlEncodeProvider" class="org.apache.cxf.jaxrs.provider.FormEncodingProvider" />
<bean id="jsonProvider" class="org.apache.cxf.jaxrs.provider.json.JSONProvider">
<property name="marshallAsJaxbElement" value="true" />
</bean>
Any ideas on how to retrieve the POST parameters in request body, in the Webservice method?
Guess I was dwelling too much into CXF, missed the simple approach. We can get the Post request parameters in CXF service similar to the way we get the parameters in a Servlet.
For Query Parameters in POST request:
#POST
#Path("/getpostfile/{fileName}")
#Produces("application/pdf")
#Consumes("application/x-www-form-urlencoded")
public Response getPostFile(#PathParam("fileName") String fileName, #Context HttpServletRequest request)
{
System.out.println("id is : " + request.getParameter("id")+", password is : " + request.getParameter("password"));
and for Parameters in POST message body, you may use getBody() method from below link:
Getting request payload from POST request in Java servlet
Hope that helps someone!