Cannot get property after using jsonSplurper.parseText(prev.getResponseDataAsString()) - groovy

I'm a new on Jmeter, I'm using JSR223 PostProcessor to get some properties in the response. Unfortunately, my response is returned as a string json as below:
"{\n "trueOdds": "1.9047619047619047",\n "displayOdds": "1.90",\n "minStake": 50.0,\n "maxStake": 105263,\n "selectionId": "11318855000001015h",\n "oddsStyle": "de",\n "offerId": "1911208285033005"\n}"
Now I want to get trueOdds, displayOdds for using in the next request. I tried to use following code to get them:
import groovy.json.JsonSlurper
def jsonString = prev.getResponseDataAsString();
def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText(jsonString);
vars.put("trueOdds", object.trueOdds);
vars.put("displayOdds", object.displayOdds);
But I get following error:
ERROR o.a.j.e.JSR223PostProcessor: Problem in JSR223 script, JSR223
PostProcessor javax.script.ScriptException:
groovy.lang.MissingPropertyException: No such property: trueOdds for
class: java.lang.String
Can anyone support to resolve this? thanks a lot.

I cannot reproduce your issue given the following JSON payload:
{
"trueOdds": "1.9047619047619047",
"displayOdds": "1.90",
"minStake": 50.0,
"maxStake": 105263,
"selectionId": "11318855000001015h",
"oddsStyle": "de",
"offerId": "1911208285033005"
}
Demo:
If your response looks exactly how you show it to us it's not a valid JSON therefore you need:
Remove first and last " via i.e. substring function
Remove all occurrences of \n via i.e. replaceAll function
Suggested code amendment:
import groovy.json.JsonSlurper
def jsonString = prev.getResponseDataAsString();
def withoutQuotationMarks = jsonString.substring(1, jsonString.length() - 1)
def withoutLineBreaks = withoutQuotationMarks.replaceAll('\\\\n','')
def jsonSlurper = new JsonSlurper();
def object = jsonSlurper.parseText(withoutLineBreaks);
vars.put("trueOdds", object.trueOdds);
vars.put("displayOdds", object.displayOdds);
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It

Related

how can I get value from json object in groovy

def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
log.info RawRecordsDateRangeResponse
My response is:
{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}
Here I want to get the value from the json response key as date.
Your response represents JSON document and it stores it in variable of type String. You can parse it using groovy.json.JsonSlurper class. Consider following example:
import groovy.json.JsonSlurper
def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')
def json = new JsonSlurper().parseText(RawRecordsDateRangeResponse)
def url = json.'2018-09-03'
println url
Output:
https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json
If it's just the key of the JSON message you need rather than the value, you could use something like:
import groovy.json.JsonSlurper
def rawRecordsDateRangeResponse = '''{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}'''
def json = new JsonSlurper().parseText(rawRecordsDateRangeResponse)
def date = json.collect({it.key})
print date
This produces [2018-09-03].

Camunda: Use in an external Groovy script a provided Class

I want to use for scripting external Groovy Scripts.
To not copy a lot of code, I want to share classes.
I have:
- external_test.groovy
- Input.groovy
Running the external_test.groovy in Intellij works.
Input is a simple class:
package helpers
class Input {
String serviceConfig
String httpMethod
String path
LinkedHashMap headers = [:]
String payload
Boolean hasResponseJson
}
When the script is executed by Camunda, it cannot find the class:
import helpers.Input
...
And throws an Exception:
unable to resolve class helpers.Input # line 16, column 9. new helpers.Input(serviceConfig: "camundaService", ^ 1 error
It is listed in the Deployment:
Do I miss something or is this not supported?
I found a post in the Camunda forum, that helped me to solve this:
https://forum.camunda.org/t/groovy-files-cant-invoke-methods-in-other-groovy-files-which-are-part-of-same-deployment/7750/5
Here is the solution (that is not really satisfying - as it needs a lot of boilerplate code):
static def getScript(fileName, execution) {
def processDefinitionId = execution.getProcessDefinitionId()
def deploymentId = execution.getProcessEngineServices().getRepositoryService().getProcessDefinition(processDefinitionId).getDeploymentId()
def resource = execution.getProcessEngineServices().getRepositoryService().getResourceAsStream(deploymentId, fileName)
def scannerResource = new Scanner(resource, 'UTF-8')
def resourceAsString = scannerResource.useDelimiter('\\Z').next()
scannerResource.close()
GroovyShell shell = new GroovyShell()
return shell.parse(resourceAsString)
}
def helper = getScript("helpers/helper_classes.groovy", execution)
helper.myFunction("hello")

groovy extract value from string

I got a string from a server response:
responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"
then I do:
responseString[1..-2].tokenize(',')
got:
[""session":"vvSbMInXHRJuZQ=="", ""age":7200", ""prid":"901Vjmx9qenYKw"", ""userid":"user_1""]
get(3) got:
""userid":"user_1""
what I need is the user_1, is there anyway I can actually get it? I have been stuck here, other json methods get similar result, how to remove the outside ""?
Thanks.
If you pull out the proper JSON from responseStr, then you can use JsonSlurper, as shown below:
def s = 'responseString:"{"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1"}"'
def matcher = (s =~ /responseString:"(.*)"/)
assert matcher.matches()
def responseStr = matcher[0][1]
import groovy.json.JsonSlurper
def jsonSlurper = new JsonSlurper()
def json = jsonSlurper.parseText(responseStr)
assert "user_1" == json.userid
This code can help you get you to the userid.
def str= 'responseString:"{:"session":"vvSbMInXHRJuZQ==","age":7200,"prid":"901Vjmx9qenYKw","userid":"user_1","hdkshfsd":"sdfsdfsdf"}'
def match = (str=~ /"userid":"(.*?)"/)
log.info match[0][1]
this pattern can help you getting any of the values you want from the string. Try replacing userid with age, you will get that
def match = (str=~ /"age":"(.*?)"/)
#Michael code is also correct. Its just that you have clarified that you want the user Name to be specific

SoapUI, temper request data break when value is read from property file

I have a groovy script as the first test step inside a test case, part of it looks like:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def holder = groovyUtils.getXmlHolder("SampleTestt#Request").getXml()
log.info holder
When SampleTest test step has all element values hardcoded, the request xml can be printed fine.
However if some of the request values is read from a test case property, like the following for example
${#TestCase#Id}
The the above groovy script through error as:
org.apache.xmlbeans.XMLException: error: Unexpected character encountered : '$'
Can you please help?
Thanks.
You can use context.expand() to evaluate the properties inside your request and then parse the result to xmlHolder, your code could looks like:
// get your request replacing the properties inside by their values
def xmlRequest = context.expand('${SampleTestt#Request}')
def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context)
def holder = groovyUtils.getXmlHolder(xmlRequest)
log.info holder.getXml()
Note that I use SampleTestt as your test step request name, but I think that the last t could be a typo... check if it's the correct request name before use the code.
Hope this helps,

groovy - problem parsing xml

I am new to Groovy and I am trying to parse both a valid rest resource and an invalid one.
For example:
this code works fine -
def entity = new XmlSlurper().parse('http://api.twitter.com/1/users/show/slashdot.xml')
println entity.name()
println entity.screen_name.text()
when I run it, I get output:
user
slashdot
but when I pass an invalid url to xmlSlurper, like this
def entity = new XmlSlurper().parse('http://api.twitter.com/1/users/show/slashdotabc.xml')
println entity.name()
println entity.screen_name.text(
)
I get this error message:
Caught: java.io.FileNotFoundException: http://api.twitter.com/1/users/show/slashdotabc.xml
at xmltest.run(xmltest.groovy:1)
Although the url returns an hash code (like below) with an error message which I would like to parse and display it.
<hash>
<request>/1/users/show/slashdotabc.xml</request>
<error>Not found</error>
</hash>
How can I parse a url which returns a 404 but with error information?
Any help will be appreciated.
--
Thanks & Regards,
Frank Covert
The response you want to see is available on the URL connection's errorStream instead of the inputStream. Fortunately, given the InputStream, XmlSlurper.parse can read an InputStream as well.
Here's a sample to switch to reading the errorStream when you don't get a 200 status:
def con = new URL("http://api.twitter.com/1/users/show/slashdotaxxxbc.xml").openConnection()
def xml = new XmlSlurper().parse(con.responseCode == 200 ? con.inputStream : con.errorStream)

Resources