I m using Soap UI basic version for some mocking. I need to persist my requests to some file. I just have generated mock services with some predefined input to output rules, and i searched on net and found this:
def logArea = com.eviware.soapui.SoapUI.logMonitor.getLogArea( "http log" );
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
Date startTime = new Date();
def cur_Time = startTime.getMonth() + "_" + startTime.getDate()
cur_Time = cur_Time + "_" + startTime.getHours() + "_" + startTime.getMinutes() +startTime.getSeconds()
def testPath = "C:/Users/..." + cur_Time + ".log"
def logFile = new File(testPath)
logFile.write("soapUI Logs In a file.\r\n")
if( logArea !=null )
{
def model = logArea.model
if( model.size > 0 )
for( c in 0..(model.size-1) )
logFile.append("\n" + model.getElementAt( c ))
}
logArea.clear()
and this works fine only from Soap UI GUI request calling. How can i persist my requests even if i call this mock service from external services?
I don't have any test cases, and don't need to save requests from them, only direct requests from external system.
Thanks!
If you want to save in a file all request that your Mock service recieve, simply do the follow. In your mock service open the onRequest script tab as in the follow image (this script executes each time that your service receives a request):
And add the follow groovy script in this tab.
def myRequestPath = 'C:/temp/request_' + System.currentTimeMillis() + ".log"
def logFile = new File(myRequestPath)
logFile.append(mockRequest.getRequestContent())
In the onRequest script context you've available a mockRequest object (of com.eviware.soapui.impl.wsdl.mock.WsdlMockRequest type) and from this object you can get the request content using getRequestContent() method, and then this script save this object in a file.
This script is easier than yours because it takes directly the response from the object instead of trying to get the response from the soapui log tabs...
Hope this helps,
Related
I am using Dialogflow to receive user input and the received values are passed to the flask program using a webhook call. Session variables are set for this action on webhook call. For another google action, I am trying to retrieve the session variables. But, I am not able to access them. Let me know where I am going wrong. Thanks in advance.
DialogFlow Intent - setclass
Receives the parameter 'class' (grade) from the User and invokes the Action setclass, which sets the session variables class and grade through webhook call.
Dialogflow Intent - getclass
Action getclass gets the values set in the session through webhook call.
Flask program to store and receive values from session:
from flask import Flask, request, session, jsonify
app = Flask(__name__)
app.secret_key = "abc"
#app.route("/sessiontrial",methods=['POST','GET'])
def sessiontrial():
req = request.get_json(silent=True, force=True)
value = req.get('queryResult')
params = value.get('parameters')
action = value.get('action')
print("Inside sessiontrial")
if (action == "setclass"):
classno = params.get('class')
print (classno)
session['class'] = classno
session['grade'] = str(classno) + " Grade"
print (session['grade'])
res = {"fulfillmentText": classno}
return(jsonify(res))
if (action == "getclass"):
if 'class' in session:
classs = session['class']
print("Class is: ", classs)
gradee = session['grade']
print("Grade is: ", gradee)
res = {"fulfillmentText": gradee}
return(jsonify(res))
else:
print("Class not found in Session")
res = {"fulfillmentText": "Class not found in Session"}
return(jsonify(res))
if __name__ == '__main__':
app.run()
You can use Redis Session Store to solve your problem. Since you've created the session in the webbook without allowing end-users to interact with the application, this could be the culprit.
You can do the following.
Go to the following link: https://github.com/aws-samples/amazon-elasticache-samples/blob/master/session-store/example-4.py
Download the class example-4.py from the session store section
Setup in your flask app.
If you are using Heroku, you can create Heroku Redis by executing the following command:
heroku addons:create heroku-redis:hobby-dev -a your-app-name
Redis Session store requires two input values: TOKEN and REDIS URL.
You can get the REDIS_URL configuration variable in the settings section of Heroku app after you setup the Redis as described in the step 4.
You must create a unique token for each user that remains active for as long as you want by specifying it in the session store. It is known as TTL (remaining time of key expiry in seconds). If you're using the dialogflow-fullfilment package, you can create this in the dialogflow and get it easily by using agent.session. In the example below, I've set the expiration time to one hour.
ttl=3600
Then do the following in your code snippets.
store = SessionStore(token, REDIS_URL)
if (action == "setclass"):
classno = params.get('class')
print (classno)
store.set('class', classno)
#session['class'] = classno
store.set('grade', str(classno) + " Grade")
#session['grade'] = str(classno) + " Grade"
print (store.get('grade'))
res = {"fulfillmentText": classno}
return(jsonify(res))
if (action == "getclass"):
if 'class' in session:
classs = session['class']
print("Class is: ", classs)
gradee = store.get('grade')
#gradee = session['grade']
print("Grade is: ", gradee)
res = {"fulfillmentText": gradee}
return(jsonify(res))
If you get the data in byte format, then you can easily convert this into integers or whatever format you like. Here is an example: How could I convert a bytes to a whole hex string?
I'm building a web app which accesses the location of the user when a particular button is pressed for this I'm using the HTML geolocation api.
Below is the location.js file:
`var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
console.log(position.coords.latitude)
console.log(position.coords.longitude)
}
Below is the snippet of the HTML file:
<button onclick="getLocation()">HELP</button>
<p id="demo"></p>
<script src="../static/location.js"></script>
What I want to do is send this information ( i.e. longitude/latitude of the user ) to list of e-mails associated with that user but I don't know how to store this data and access this after the button is pressed.
It would be of great use if someone could get me started on how to save this data corresponding to the user and accessing it from the database.
If you want to store this info to a django DB, then if might be easier to do this in a django view. This could be a RedirectView that just redirects to the same view after the button is clicked.
I have previously used a downloaded DB of the GeoLite2-City.mmdb, which might not always be up to date, but is ok.
You can get the ip address of a request in django with the ipware library. Then convert it into a python IP object in IPy. You can then use the geoip library to get the information out of the DB.
Import the following libraries;
from ipware.ip import get_ip
from IPy import IP
import geoip2.database
Then your method to get the IPs would be something like
class MyRedirectView(RedirectView)
def get_redirect_url(self, request, *args, **kwargs):
## Write some code to handle the redirect url first ##
ip_address = get_ip(self.request)
"""Ensure that the IP address is a valid IP first"""
try:
IP(ip_address)
except Exception:
logger.exception("GEOIP2 error: ")
"""Then get the IP location"""
geo_path = settings.GEOIP_PATH
reader = geoip2.database.Reader(geo_path + '/GeoLite2-City.mmdb')
try:
response = reader.city(ip_address)
city = response.city.name
country = response.country.name
### Some code here to save to your DB
return super(MyRedirectView, self).get_redirect_url(*args, **kwargs)
If you need a much more accurate IP location service you could involce an API call to something like http://ip-api.com/. But then you would have to wait for this response before serving the next view.
I have to fetch the retweets for the tweets and create the JSON file with retweets,user id etc using the python script. Kindly help me to sort it our this issues.
Thanks in advance!!
This task require some fields of knowledge, and since you ask in a general way, I reckon you need a script to run immediately, but setting up this process requires sometime
This part to get connect to twitter API
from twython import Twython, TwythonError
APP_KEY = 'YOUR_APP_KEY'
APP_SECRET = 'YOUR_APP_SECRET'
twitter = Twython(APP_KEY, APP_SECRET)
Use Twitter API call from Twython,
you can find a list here https://twython.readthedocs.io/en/latest/api.html, the param is the same as twitter API
response = twitter.get_retweets(id, 100)
Pagnation
each call to API have limit of returns, in example for engine.get_friends_ids was limited to 5000 (https://dev.twitter.com/rest/reference/get/friends/ids), if you want to get more than 5000, you have to use the cursor in the returned result (if cur = 0 in json returned means no more results), following is example of how to handling cursor
#Set a temp to loop
cur = -1
#Stop when no more result
while cur !=0:
response = twitter.get_friends_ids(user_id=user_id, cursor=cur)
#Some code to handle the response
cur = response["next_cursor"]
API key
Key expires after some calls (https://dev.twitter.com/rest/public/rate-limits), so you need to set some code to auto change your key, or wait for some period (key reached limit return error code 429)
Response
The response from API was in JSON format, which was easy to use, you can access data by selecting base on response[key], in example
reponse["ids"] or response["next_cursor"]
I'm looking for a way to add 2 custom cookies to every http request.
The browsermob proxy (https://github.com/lightbody/browsermob-proxy) has removeHeaders() and addHeader() methods, but what can I do to keep existing cookies in request, but add 2 more cookies?
Thanks!
You can use this method to invoke your custom js code in each request/response
https://github.com/lightbody/browsermob-proxy#http-request-manipulation
Some example in Python
def response_interceptor(self, js):
"""
Executes the javascript against each response
:param js: the javascript to execute
"""
r = requests.post(url='%s/proxy/%s/interceptor/response' % (self.host, self.port),
data=js,
headers={'content-type': 'x-www-form-urlencoded'})
return r.status_code
def request_interceptor(self, js):
"""
Executes the javascript against each request
:param js: the javascript to execute
"""
r = requests.post(url='%s/proxy/%s/interceptor/request' % (self.host, self.port),
data=js,
headers={'content-type': 'x-www-form-urlencoded'})
return r.status_code
and test:
def test_request_interceptor_with_parsing_js(self):
"""
/proxy/:port/interceptor/request
"""
js = 'alert("foo")'
status_code = self.client.request_interceptor(js)
assert(status_code == 200)
As I answered above, you could use proxy's REST API to set custom js handler on every request, made through the proxy.
For example you could add any custom cookies to every request:
curl -X POST -H 'Content-Type: text/plain' -d 'js code' http://10.100.100.20:8080/proxy/8081/interceptor/request
In php it would look like:
/**
* #param Proxy $proxyObject
* #param array $cookiesArray
*/
protected function _setRequestCookies(Proxy $proxyObject, array $cookiesArray)
{
foreach ($cookiesArray as $nameString => $valueString) {
$cookiesArray[$nameString] = $nameString . '=' . $valueString;
}
$jsHandlerString = sprintf(
'var c = request.getMethod().getFirstHeader("Cookie") ? request.getMethod().getFirstHeader("Cookie").getValue() : ""; request.getMethod().setHeader("Cookie", c + "; %s");',
implode('; ', $cookiesArray)
);
$urlString = sprintf('%sproxy/%u/interceptor/request', $this->_hubUrlString, $proxyObject->getPort());
$this->_requesterObject->makeRequest($urlString, Requester::REQUEST_METHOD_POST, $jsHandlerString);
}
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