How to use operator `?` to get an item from an array? - groovy

Groovy code:
def line = "aa bb"
println line?.split("\\s+")?[1]
I want to use ? for an array to get an item. If the array is null, then return null, just like ?..
But the above code can't be compiled. How to fix it? Or is there any other simple alternative solution to this?

You can use getAt instead of [] (subscript operator)
def line = "aa bb"
println line?.split("\\s+")?.getAt(1)
http://groovyconsole.appspot.com/script/801001

It's the default behavior for List:
println (line?.split("\\s+")as List)[1]

Related

Need to remove unwanted symbols from value using replaceAll method

I am getting the value of a field as ["value"]
I want to print only the value removing the [ "from the result value.
That looks like a JSON array of Strings? No idea, as you don't provide any context, but you could do:
import groovy.json.JsonSlurper
def valueField = '["value"]'
def result = new JsonSlurper().parseText(valueField).head()
println result
Prints value
The following script should be what you need
def str = '["value"]'
println(str.replaceAll(/\[|\]/,''))

Groovy remove null elements from a map

I am getting a map in my method from another server and I have some null values, I wanted to remove those ones, because I am struggling with those values in the following process:
My map looks something like:
I had done the next code, but without satisfactory results:
map.values().removeAll(Collections.singleton(null))
Any ideas?
Thanks
Edit
The Groovy way, is to filter the entries you want:
def map = [a:42, b:null]
def cleanMap = map.findAll{ it.value!=null }
println cleanMap
// => [a:42]
Previous answer:
Seems to work with Jdk8/Groovy 2.5, but not for OP
To remove all elements with a value with null, remove on the map directly:
def map = [a:42, b:null]
map.removeAll{ it.value == null }
println map
// => [a:42]

How to pass Map between testCases using properties

I want to do the following in SOAPUI using Groovy:
In a TestCase1 select values (Lastname, firstname) from database, and create a Map with dynamic values: def Map = [Login :"$Login", Nom: "$Nom"]
I need my map to be transferred to another TestCase, for this
I'm trying to put my map into properties:
testRunner.testCase.setPropertyValue( "Map", Map)
But I have error:
groovy.lang.MissingMethodException: No signature of method:
com.eviware.soapui.impl.wsdl.WsdlTestCasePro.setPropertyValue() is
applicable for argument types: (java.lang.String,
java.util.LinkedHashMap) values: [OuvInfoPersoMap,
[Login:dupond0001, Nom:Dupond]] Possible solutions:
setPropertyValue(java.lang.String, java.lang.String),
getPropertyValue(java.lang.String) error at line: 123
I found some posts on internet that suggests to use metaClass groovy property
context.testCase.metaClass.map = Map
log.info context.testCase.map
But I don't think it enough in my case.
I would like to be able to pass a map to Testcase2 using:
createMap = testRunner.testCase.testSuite.project.testSuites.testCases["TestCase1"]
createMap.map
Hopefully you can help me solving this problem.
Thanks advance
As #SiKing correctly explain in the comments, setPropertyValue method expects and String for the property name and for the property value.
Note that as #Rao suggest in general testCase execution should be independent, however despiste this technically it's possible to do what you ask for.
So a possible solution for your case is in the first testCase to serialize the Map to String in order that it's possible to save using setPropertyValue(Strig propertyName, String value) method, and then in the second testCase deserialitze it, something like the follow code must work:
TestCase 1
Serialize the map using inspect() method and save it as a property:
def map = ['foo':'foo','bar':'bar', 'baz':'baz']
testRunner.testCase.setPropertyValue('map',map.inspect())
TestCase2
Deserialitze the String property using Eval.me(String exp)::
// get the first testCase
def testCase1 = testRunner.testCase.testSuite.testCases["TestCase1"]
// get the property
def mapAsStr = testCase1.getPropertyValue('map')
// deserialize the string as map
def map = Eval.me(mapAsStr)
assert map.foo == 'foo'
assert map.bar == 'bar'
assert map.baz == 'baz'

Groovy: Different behaviour observed using the eachWithIndex method

I was doing a Groovy tutorial online there and after playing around with the code I observed some behaviour that I can't understand.
First I created a Map object like this:
def devMap = [:]
devMap = ['name':'Frankie', 'framework':'Grails', 'language':'Groovy']
devMap.put('lastName','Hollywood')
Then I called eachWithIndex to print out the values like so:
devMap.eachWithIndex { println "$it.key: $it.value"}
Which printed this to the console:
name: Frankie
framework: Grails
language: Groovy
lastName: Hollywood
But when I printed to the console from the eachWithIndex method like this using the arrow operator:
devMap.eachWithIndex { it, i -> println "$i: $it" }
The following got printed to the console:
0: name=Frankie
1: framework=Grails
2: language=Groovy
3: lastName=Hollywood
So what I can't understand is why the indexes got printed with the second statement and why there are = signs but no : signs between the key-value pairs?
Thanks.
When you use the no-arg version of eachWithIndex, it is the current entry in the Map. That means that it.key and it.value return what you expect.
When you use the two-arg version of eachWithIndex, again, it is the current entry in the Map and i is the current index. You're printing i, the index, and then since you are only printing it, you are getting the result of it.toString(), which formats the map entry as "${it.key}=${it.value}"
Your second example is equivalent to:
devMap.eachWithIndex { it, index -> println "$index: ${it.toString()}" }
where this shows that the toString() implementation uses the = syntax:
devMap.each { println it.toString() }
Note that this is closer to your goal (as I interpret it):
devMap.eachWithIndex { it, index -> println "$index: ${it.key}: ${it.value}" }

Get key in groovy maps

def map = [name:"Gromit", likes:"cheese", id:1234]
I would like to access map in such a way that I can get the key
something like the output should be
map.keys returns array of string. basically i just want to get the keys
output:
name
likes
id
try map.keySet()
and if you want an array:
map.keySet() as String[]; // thx #tim_yates
Or, more groovy-ish:
map.each{
key, value -> print key;
}
Warning: In Jenkins, the groovy-ish example is subtly broken, as it depends on an iterator. Iterators aren't safe in Jenkins Pipeline code unless wrapped in a #NonCPS function.
def map = [name:"Gromit", likes:"cheese", id:1234]
println map*.key
In groovy * is use for iterate all

Resources