groovy - problem parsing xml - groovy

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)

Related

PathNotFoundException in the groovy script SoapUI

While executing this script in the line 2, error message is getting, instead of null response.
If there is no "success_text" in the response, it should show null value instead of error.
def response = context.expand( '${moneytransfer#Response}' )
def id =parse(response).read('$.success_text')
log.info id
Could you please help me, is there anyway "id" value returns null, if the success_text not found
Since you don't share the parse and read method it's hard to know what is happening under the hood. However in groovy there is a null-safe operator ?., it avoids NPE returning null instead.
I suspect that the problem is inside your methods, however you can try with it:
def response = context.expand( '${moneytransfer#Response}' )
def id =parse(response)?.read('$.success_text')
log.info id

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

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

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,

Find an element in XML using XML Slurper

"I have a code that is working as expected but now I have to find the element in different format. Example is below
<car-load>
<car-model model="i10">
<model-year>
<year.make>
<name>corolla</name>
</year.make>
</model-year>
</car-model>
</car-load>
I have to find the value of "corolla" from this XML. Please reply.
You can run this in the Groovy console
def text = '''
<car-load>
<car-model model="i10">
<model-year>
<year.make>
<name>corolla</name>
</year.make>
</model-year>
</car-model>
</car-load>'''
def records = new XmlSlurper().parseText(text)
// a quick and dirty solution
assert 'corolla' == records.toString()
// a more verbose, but more robust solution that specifies the complete path
// to the node of interest
assert 'corolla' == records.'car-model'.'model-year'.'year.make'.name.text()

XmlSlurper and http.get in groovy

I first save a txt file using http.get:
http.get(path: path,
contentType: TEXT,
query: [id:dapId, instance:alias, format:'xml', file:portalFile]) {resp, reader ->
println "response status: ${resp.statusLine}"
println 'Headers: -----------'
resp.headers.each { h ->
println " ${h.name} : ${h.value}"
}
new File(outputFileName).withWriter{out -> out << reader}
}
And then use the newly created file in outputFileName in XmlSlurper().parse, as below:
def inputFile = new File(outputFileName)
def domain = new XmlSlurper().parse(inputFile)
But I get an error when doing new XmlSlurper().parse(inputFile):
Caught: org.xml.sax.SAXParseException: White spaces are required between publicId and systemId.
I noticed that the textfile outputFileName which is being created with http.get seems to be an HTML file and not an XML file. So I copied and pasted the XML code which it is supposed to contain into outputFileName, skipped the first part of the code and only ran the XmlSlurper().parse() bit and it worked.
Is outputFileName supposed to be an xml file? It has lots of HTML tags.
Thanks in advance! :D
HTML != XML. Your HTML file probably is not valid XML. Therefore, the XML parser fails during parsing. Are you sure that the file created from the http GET is a valid XML file?

Resources