how do I make sure a function does not return Null - groovy

I'm trying to parse XML from my Request in Soapui. And when I parse a Node without anything in it, logically the String is Null if the defining func() returns Null:
def groovyUtils = new com.eviware.soapui.support.GroovyUtils( context )
def request = groovyUtils.getXmlHolder( mockRequest.requestContent )
def argumentString = request.getNodeValue("/soap:Envelope/soap:Body[1]/emm:RunApplication[1]/emm:argument[1]")
now I tried doing it like this:
try{argumentString.length()}catch(e){argumentsString = " "}
but this kills the Process after the correction, and doesn't quite give what I want. Can't use a Simple if(func()!=NULL) as i'm used to in Java? How can I do this? Thanks for your Help!

You can test for null values ...:
argumentString = (argumentString != null) ? argumentString : " "
BTW, with argumentString?.length(), length() will only be evaluated if argumentString isn't null.

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

use jsonSlurper.parseText for text that has dash

How can I use jsonSlurper.parseText to parse "807-000" that has dash in it with groovy ?
You are generating the below string for parsing:
[807-000]
What I think you wanted is an json array containing a string:
["807-000"]
You could generate that json yourself:
def arr2 = "[" + arr.collect({ '"' + it + '"' }).join(",") + "]"
But why reinvent the wheel, when you can do it like this:
def arr2 = groovy.json.JsonOutput.toJson(arr)
It's not entirely clear what exactly do you want to do. parseText() is waiting for json to be input. I suggest several options for parsing.
def text = jsonSlurper.parseText("""{ "key": "807-000" } """)
Or did you mean that before the dash is the key, and after it is the value? If so then you can try this:
def map = "807-000".split("-").toSpreadMap()
map.each {row ->
def parsedText = jsonSlurper.parseText("""{ "${row.key}": "${row.value}" } """)
println(parsedText)
}
output is = [807:000]
How can I use jsonSlurper.parseText to parse "807-000" that has dash
in it with groovy ?
I am not sure what the challenge actually is. Something I can think of is possibly you are having trouble using Groovy property access to retrieve the value of a key when the key has a hyphen in it. You can do that by quoting the property name:
String jsonString = '''
{"807-000":"Eight O Seven"}
'''
def slurper = new JsonSlurper()
def json = slurper.parseText(jsonString)
// quote the property name which
// contains a hyphen...
String description = json.'807-000'
assert description == 'Eight O Seven'

Groovy JsonSlurper - How to check for null value vs missing field?

I am parsing a JSON string with Groovy's JsonSlurper. I want to find out how to (1) check if a field is missing from the string OR (2) if its value is set to null. This is my code:
def JsonSlurper jSlurp = new JsonSlurper()
def obj = jSlurp.parseText(myJsonString)
assert obj.myField == null
Unfortunately, this does not tell me if the field is missing or if its present with a value of null. How do I figure that out?
def obj = new groovy.json.JsonSlurper().parseText('{"a":null, "b":1}')
assert obj.containsKey('a')==true
assert obj.a==null
assert obj.containsKey('c')==false
assert obj.c==null

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

Is there a functional programming way to retrieve the first element of a collection?

The list can be empty. I would like to do :
def value = "";
def list = getList()
if (!list.isEmpty()){
value = list.first().foo
}
for instance I have found this way :
assert ( [].find()?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]].find()?.foo?:"empty") == "notEmpty1"
Is there a better way ?
Thanks! :)
EDIT:
I got great answer by using [0]
assert ( [][0]?.foo?:"empty" ) == "empty"
assert ([[foo:"notEmpty1"], [foo:"notEmpty2"]][0]?.foo?:"empty") == "notEmpty1"
If it is a List just try
if (!list?.isEmpty()){
list.get(0);
}
If the list element cannot be null you don't need the ?
If it is a Collection there are several forms to retrieve it. Take a look at this post
Java: Get first item from a collection
I got an answer from tweeter. The statements :
def value = "";
def list = getList()
if (!list.isEmpty()){
value = list.first().foo
}
Can be write :
def value = list[0]?.foo?:""
find may be use if the list can contain null values

Resources