Groovy - Substring from a string - groovy

def testString = '''
relkey = CAT_RELEASE_AUG_2018
relkey2 = CAT_RELEASE_SEP_2019
'''
using groovy - how can i get both the relkey and relkey2 values - Thanks

Method 1:
String val = testString.substring(testString.indexOf("=")+1)
For more options, you can use this too.
Method 2:
String val = testString.split("=")[1]
But it is up to you.
For example to load as map:
There are many methods to load as map but for simple example,
String a= "h=1"
Map kv=[:]
List b = a.split("=");
kv[b[0]]=b[1]
println kv

Related

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'

obtain value from Key/value in map array groovy

I have code like this:
def options = JsonPath.read(prev.getResponseDataAsString(), '$.options')
def randomOption = options.get(RandomUtils.nextInt(0, options.size()))
def code = randomOption.get("code")
vars.put('code1', code)
def values = randomOption.get('values')
def randomValue = values.get(RandomUtils.nextInt(0, values.size())) as
String
def val = randomValue['value']
vars.put('randomValue', randomValue)
vars.put('ValueF', val).
In Random Variable i am getting value as [label:Red, value:8] . I need to fetch the value of Value=8
Youre trying to invoke
vars.put('ValueF', [label:Red, value:8])
which is put(String, Map)
JMeterVariables have no such method https://jmeter.apache.org/api/org/apache/jmeter/threads/JMeterVariables.html
you can use putObject() which accepts String as key and Object as value:
vars.putObject('ValueF', val)

Access variable value by its name as String (groovy)

I've done some research but I haven't found a working code for my case. I have two variables named test and test2 and I want to put them in a map in the format [test:valueof(test), test2:valueof(test2)]
My piece of code is the following:
def test="HELLO"
def test2="WORLD"
def queryText = "\$\$test\$\$ \$\$test2\$\$ this is my test"
def list = queryText.findAll(/\$\$(.*?)\$\$/)
def map = [:]
list.each{
it = it.replace("\$\$", "")
map.putAt(it, it)
}
queryText = queryText.replaceAll(/\$\$(.*?)\$\$/) { k -> map[k[1]] ?: k[0] }
System.out.println(map)
System.out.println(queryText)
Output:
Desired output:
"HELLO WORLD this is my test"
I think I need something like map.putAt(it, eval(it))
EDIT
This is the way I get my inputs. the code goes into the 'test' script
The ones on the right are the variable names inside the script, the left column are the values (that will later be dynamic)
You are almost there.
The solution is instead of putting the values into separate variables put them into the script binding.
Add this at the beginning ( remove the variables test and test2):
def test="HELLO"
def test2="WORLD"
binding.setProperty('test', test)
binding.setProperty('test2', test2)
and change this:
{ k -> map[k[1]] ?: k[0] }
to this:
{ k -> evaluate(k[1]) }
It should be very simple if you could use TemplateEngine.
def text = '$test $test2 this is my test'
def binding = [test:'HELLO', test2:'WORLD']
def engine = new groovy.text.SimpleTemplateEngine()
def template = engine.createTemplate(text).make(binding)
def result = 'HELLO WORLD this is my test'
assert result == template.toString()
You can test quickly online Demo
Final working code, thanks to all, in particular to dsharew who helped me a lot!
#input String queryText,test,test2,test3
def list = queryText.findAll(/\$\$(.*?)\$\$/)
def map = [:]
list.each{
it = it.replace("\$\$", "")
map.putAt(it, it)
}
queryText = queryText.replaceAll(/\$\$(.*?)\$\$/) { k -> evaluate(k[1]) }
return queryText

How to make snakeyaml and GStrings work together

When I'm trying to use snakeyaml to dump out Yaml out of Groovy interpolated strings, it ends up printing a class name instead.
For example:
#Grab(group='org.yaml', module='snakeyaml', version='1.16')
import org.yaml.snakeyaml.Yaml
Yaml yaml = new Yaml();
def a = "a"
def list = ["$a"]
def s = yaml.dump(list)
Prints:
- !!org.codehaus.groovy.runtime.GStringImpl
metaClass: !!groovy.lang.MetaClassImpl {}
I'm guessing it has something to do with the fact that GStrings get transformed to Strings when they used and I suspect snakeyaml uses some sort of introspection to determine the class of the object.
Is there a better solution than calling toString() on all GStrings?
Try to create a new Representer :
public class GroovyRepresenter extends Representer {
public GroovyRepresenter() {
this.representers.put(GString.class, new StringRepresenter());
}
}
Yaml yaml = new Yaml(new GroovyRepresenter())
...
You could add type info to your variables
Yaml yaml = new Yaml();
def a = "a"
String aStr = "$a"
def list = [aStr]
def s = yaml.dump(list)

Is there a way to declare a Groovy string format in a variable?

I currently have a fixed format for an asset management code, which uses the Groovy string format using the dollar sign:
def code = "ITN${departmentNumber}${randomString}"
Which will generate a code that looks like:
ITN120AHKXNMUHKL
However, I have a new requirement that the code format must be customizable. I'd like to expose this functionality by allowing the user to set a custom format string such as:
OCP${departmentNumber}XI${randomString}
PAN-${randomString}
Which will output:
OCP125XIBQHNKLAPICH
PAN-XJKLBPPJKLXHNJ
Which Groovy will then interpret and replace with the appropriate variable value. Is this possible, or do I have to manually parse the placeholders and manually do the string.replace?
I believe that GString lazy evaluation fits the bill:
deptNum = "C001"
randomStr = "wot"
def code = "ITN${deptNum}${->randomStr}"
assert code == "ITNC001wot"
randomStr = "qwop"
assert code == "ITNC001qwop"
I think the original poster wants to use a variable as the format string. The answer to this is that string interpolation only works if the format is a string literal. It seems it has to be translated to more low level String.format code at compile time. I ended up using sprintf
baseUrl is a String containing http://example.com/foo/%s/%s loaded from property file
def operation = "tickle"
def target = "dog"
def url = sprintf(baseUrl, operation, target)
url
===> http://example.com/foo/tickle/dog
I believe in this case you do not need to use lazy evaluation of GString, the normal String.format() of java would do the trick:
def format = 'ITN%sX%s'
def code = { def departmentNumber, def randomString -> String.format(format, departmentNumber, randomString) }
assert code('120AHK', 'NMUHKL') == 'ITN120AHKXNMUHKL'
format = 'OCP%sXI%s'
assert code('120AHK', 'NMUHKL') == 'OCP120AHKXINMUHKL'
Hope this helps.
for Triple double quoted string
def password = "30+"
def authRequestBody = """
<dto:authTokenRequestDto xmlns:dto="dto.client.auth.soft.com">
<login>support#soft.com</login>
<password>${password}</password>
</dto:authTokenRequestDto>
"""

Resources