WSO2 null response - wso2

I am trying to use WSO2 StoreAPI in my code for performing validations from WSO2.Here is a snippet
def wso2Subscription(){
println "Inside Subscription"
def serverName = grailsApplication.config.grails.wsoconfig.serverName.toString()
println serverName
withHttp(uri: serverName) {
def resp = post(path : '/store/site/blocks/subscription/subscription-add/ajax/subscription-add.jag', query : [action:'addAPISubscription',name:'NewAPI',version:'1.0.0',provider:'admin',tier:'Unlimited',applicationName:'DefaultApplication'])
println "Subscription Response from WS02 ="+resp
resp.each { h -> println " ${h.key} : ${h.value}" }
}
}
This value of resp is null everytime. What is missing here? I already login and perform this operation. Also, the user is not subscribed to this API previously. "Inside Subscription" is displayed and hence, the function is getting called. However, the response is null always. What is going wrong?

The issue was session management which was not being possible here. A very good reference is this link on solving this. It worked for me!
http://refaktor.blogspot.in/2013/01/how-to-keep-session-in-httpbuilder-with.html

You should send below information as body, not as query string.
action:'addAPISubscription',name:'NewAPI',version:'1.0.0',provider:'admin',tier:'Unlimited',applicationName:'DefaultApplication'
It's better you send the request from cURL and see the response.

Related

How to test a Cloud Function in Google Cloud Platform (GCP)?

I have been trying to find the answer to this but am unable to find it anywhere. On the Cloud Functions section in the Google Cloud Platform console there is a section title 'Testing' but I have no idea what one is supposed to put here to test the function, i.e. syntax.
I have attached an image for clarity:
Any help would be much appreciated.
HTTPS Callable functions must be called using the POST method, the Content-Type must be application/json or application/json; charset=utf-8, and the body must contain a field called data for the data to be passed to the method.
Example body:
{
"data": {
"aString": "some string",
"anInt": 57,
"aFloat": 1.23,
}
}
If you are calling a function by creating your own http request, you may find it more flexible to use a regular HTTPS function instead.
Click Here for more information
Example with the Cloud Function default Hello_World that is inserted automatically whenever you create a new Cloud Function:
def hello_world(request):
"""Responds to any HTTP request.
Args:
request (flask.Request): HTTP request object.
Returns:
The response text or any set of values that can be turned into a
Response object using
`make_response <http://flask.pocoo.org/docs/1.0/api/#flask.Flask.make_response>`.
"""
request_json = request.get_json()
if request.args and 'message' in request.args:
return request.args.get('message')
elif request_json and 'message' in request_json:
return request_json['message']
else:
return f'Hello World!'
Must be tested with a json as the input args:
{
"message": "Hello Sun!"
}
Out in the Testing Tab:
Hello Sun!
In the Testing tab editor: since we give the function the args in form of a json as we would elsewise write them like in python3 -m main.py MY_ARG, and since "message" is a key of that json, it is found by the elif and returns the value of the dictionary key as the message, instead of "Hello World". If we run the script without json args, else: is reached in the code, and output is "Hello World!":
This looks to be the same as gcloud functions call, with the JSON required being the same as the --data provided in the CLI.
You can check the docs for examples using the CLI, and the CLI documentation itself for further details.
There are multiple ways you could test you cloud function.
1) Use a google emulator locally if you want to test your code before deployment.
https://cloud.google.com/functions/docs/emulator.
This would give you a similar localhost HTTP endpoint that you can send request to for testing your function.
2) Using GUI on deployed function: The triggering event is the json object that the function expects in the request body. For example:
{
"key": "value"
}
Based on your function code dependency for the request it should trigger the function.
Simple Tests for Cloud Pub/Sub:
{"data":"This is data"}
Base64 'Hello World !' message :
{"data":"SGVsbG8gV29ybGQgIQ=="}

How can I print the Canonical String which aws-requests-auth sends?

I want to have a lambda calling a Sagemaker instance in another region. If both are in the same region, everything works fine. If they are not, I get the following error:
The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.
The Canonical String for this request should have been
'POST
/endpoints/foo-endpoint/invocations
host:runtime.sagemaker.us-east-1.amazonaws.com
x-amz-date:20180406T082536Z
host;x-amz-date
1234567890foobarfoobarfoobarboofoobarfoobarfoobarfoobarfoobarfoo'
The String-to-Sign should have been
'AWS4-HMAC-SHA256
20180406T082536Z
20180406/us-east-1/sagemaker/aws4_request
987654321abcdeffoobarfoobarfoobarfoobarfoobarfoobarfoobarfoobarf'
I use aws-requests-auth (0.4.1) with boto3 (1.5.15 - updating to 1.7.1 didn't change anything, changelog) like this:
import requests
from aws_requests_auth.aws_auth import AWSRequestsAuth
auth = AWSRequestsAuth(aws_access_key=config['AWS']['ACCESS_KEY'],
aws_secret_access_key=(
config['AWS']['SECRET_ACCESS_KEY']),
aws_host=config['AWS']['HOST'],
aws_region=config['AWS']['REGION'],
aws_service=config['AWS']['SERVICE'])
payload = {'foo': 'bar'}
response = requests.post(post_url,
data=json.dumps(payload),
headers={'content-type': 'application/json'},
auth=auth)
printing auth only gives <aws_requests_auth.aws_auth.AWSRequestsAuth object at 0x7f9d00c98390>.
Is there a way to print the "Canonical String" mentioned in the error message?
(Any other ideas how to fix this are appreciated as well)
A work-around for the asked question:
req = requests.request('POST', 'http://httpbin.org/get')
req.body = b''
req.method = ''
print(auth.get_aws_request_headers(req,
aws_access_key=auth.aws_access_key,
aws_secret_access_key=auth.aws_secret_access_key,
aws_token=auth.aws_token))
The problem is not solved, though. And now I wonder what the first argument of auth.get_aws_request_headers is.

SoapUI: Using Groovy to return a MockResponse based on validation of the request

In SoapUI (and a SOAP web service), how do you evaluate a string from a request and return a response based on conditions around that request?
So far, I am able to read the values in the request and use those values in the response, but if I try to extend this to a response based on an if statement then no value is returned. Any help would be appreciated. Here is my code so far:
// create XmlHolder for request content
def holder = new com.eviware.soapui.support.XmlHolder( mockRequest.requestContent )
// get arguments from the request (this looks like it is all working correctly)
def FirstName = holder.getNodeValue("//FirstName")
def LastName = holder.getNodeValue("//LastName")
def Phone = holder.getNodeValue("//Phone")
def Gender = holder.getNodeValue("//Gender")
def Age = holder.getNodeValue("//Age")
//here are where the problems start
//I am using an evaluation in the if statement that should always be true
//I was trying something closer to the end solution I would like eg. if(Gender == "M")
//but this also failed to return any response
def response
if("M" == ("M")){
reponse = FirstName;
//return response
//context.setProperty("responseMessage", response)
}else
{
response = "error"
//return response
//context.setProperty("responseMessage", response)
}
return response
context.setProperty("responseMessage", response)
I have left in as comments some of the other things I have tried
Thanks
EDIT: This is within the SoapUI MockResponse, I want to set ${responseMessage} in the MockReponse as the value of the response in the XML. My objective is to send a request to the mock service and to be able to respond based on the strings contained in the request, such as whether "Gender" is "M" or "F", age is within some range etc. I feel that if my issue with the code in the question is resolved so that a value is returned, then I can solve the extended parts myself
Thanks to albciff, this has solved my problem:
...
if("M" == ("M"))
{
requestContext.responseMessage = FirstName
}else
{
requestContext.responseMessage ="error"
}
I suppose that you've the follow scenario.
You're creating a MockService in SOAPUI, inside MochService there is an operation which has a MockResponse and you dispatch your response from the operation as script. In the follow image the MockService, operation and MockResponse are shown:
So if for example you have a MockResponse with the follow content:
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>${responseMessage}</soap:Body>
</soap:Envelope>
In your script to fill ${responseMessage} you have to assign the property value through requestContext object instead of setting property in the context or returning the value, in this case requestContext.responseMesssage.
In your script this could be:
...
if(Gender == "M" ){
requestContext.responseMesssage = FirstName
}else
{
requestContext.responseMesssage = "error"
}
...
You can also take a look at SOAPUI MockService documentation
Hope this helps,

Why variable is `None` in my case?

My code:
if not 'last_user_visit' in request.COOKIES:
response.set_cookie('last_user_visit', now)
last_visit = request.COOKIES.get('last_user_visit')
print last_visit
Why last_visit is None in my case?
Because you're setting it on the response, and reading it back from the request. The version in request won't be updated until the response has been sent to the client and the next request has been received.
You have to send response first like Daniel have suggested, you are setting cookie on response and then you have to return it. So that from that time, whenever a request will come it will be holding that cookie and you can access it. you can create function like this:
def cookie_setter(request):
'''Do your function task and create response object
'''
if not 'last_user_visit' in request.COOKIES:
response.set_cookie('last_user_visit', now)
return response

Grails RESTFUL web service api

I am currently developing a web app which should do restful service calls to existing web service api.
What I have is the base URL and the API names.
Any help on how do I start working on it?
I suppose I need to use httpbuilder for the base url I have, then followed by /api name. But how do I test it on grails if its working?
When I paste the base url on the browser it does return some xml information, so what I need is to do it on grails instead.
XML response when I paste the url through browser
<ns1:createNewUserResponse>
<userId>21</userId>
</ns1:createNewUserResponse>
So I need to be able to get this response through my web-app (grails) instead of pasting it on the browser.
EDIT*
this is a good example I found useful
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.5.0-RC2' )
import groovyx.net.http.*
import static groovyx.net.http.ContentType.*
import static groovyx.net.http.Method.*
def http = new HTTPBuilder( 'http://ajax.googleapis.com' )
// perform a GET request, expecting JSON response data
http.request( GET, JSON ) {
uri.path = '/ajax/services/search/web'
uri.query = [ v:'1.0', q: 'Calvin and Hobbes' ]
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
// response handler for a success response code:
response.success = { resp, json ->
println resp.statusLine
// parse the JSON response object:
json.responseData.results.each {
println " ${it.titleNoFormatting} : ${it.visibleUrl}"
}
}
// handler for any failure status code:
response.failure = { resp ->
println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
but i do not understand the query part and how do I alter it to my need?
the URL I have contains credential of username and password, the response should return a securityToken which I need to get it out from the results. Any help would be greatly appreciated!
You can start with groovy-wslite, it provides both SOAP and REST webservice clients.
To make a call to a resfull service look at Groovy HttpBuidler - http://groovy.codehaus.org/HTTP+Builder