Using a range in a groovy case statement - groovy

I'm writing a Jenkins pipeline, and I'd like to use a groovy switch statement to match on a range on int values so I don't have to write a case for each number in the range. Not used to groovy, so apologies if this is a simple question. For example (not working):
switch (diskuse) {
case 1-5: //this doesn't work
println('disk use is under 50')
break
case [5-9]: //this also doesn't work
println('disk use is OVER 50!')
break
default: //the switch always hits this case
println('no disk use info available')
}

The correct range literal looks like 1..5 in Groovy.
Your switch op shall look like so:
switch (diskuse) {
case 1..5: //inclusive range
println('disk use is under 50')
break
case 5..<9: //exclusive range, 9 is exluded
println('disk use is OVER 50!')
break
default:
println('no disk use info available')
}

Related

Match Operator prettier syntax in Groovy

I'm very new to groovy (here working on Jenkinsfile)
One of my coworkers uses a Match Operator to check a condition. But I find it not readable and hard to maintain.
Original Match Operator:
PROJECT_NAME = 'projectA' // User Input from Jenkins params normaly
if ( "${PROJECT_NAME}" ==~ /projectA|projectB|projectC|projectD/) { // The real line is 300 Char long
// Do stuff
}
There is 15 projects in total, i've shorten up the line because it was too long. So every time he needs to add a project name, he appends at the start or end of his regex.
Also, those project name are in a list before.
projects = ['projectA',
'projectB',
'projectC',
'projectD']
Could there be a way to use this list to build the regex?
Here is what I tried:
string_regex = "/"
for (project in projects) {
string_regex = string_regex + project + "|"
}
string_regex = string_regex.substring(0, string_regex.length() - 1)
string_regex = string_regex + "/"
print "${string_regex}\n"
if ("${PROJECT_NAME}" ==~ string_regex) {
print "Well Done you did it\n"
// Do stuff
}
But saddly it doesn't seems to work, since I'm using a string?
EDIT: I found out that I could use the contains method from a list in Groovy. In my case, it fixes my original problem. But I'm still curious on how to build such regex with strings.
if (projects.contains(PROJECT_NAME)) {
// Do stuff
}
You can join your projects and then turn the string into a regexp via Pattern.compile(). For good measure use Pattern.quote() to safe-guard against chars in your project names with "meaning" in regexp.
import java.util.regex.Pattern
def projects = ['projectA',
'projectB',
'projectC',
'projectD']
def re = Pattern.compile(projects.collect{ Pattern.quote it }.join("|"))
['projectA', 'projectX'].each{
println it ==~ re
}
// -> true
// -> false
For what it's worth, I came to like the Groovy matching operators for their compact syntax. If you learn about them and practice for a short bit, you will probably get to like them, too.
Regardless, for a simple check, on whether a String is part of a list, there is a much simpler way in Groovy than using full blown regexp : the in operator, e.g.:
def projects = ['projectA',
'projectB',
'projectC',
'projectD']
['projectA', 'projectX'].each {
println "${it} is ${it in projects ? 'IN' : 'NOT IN'} the project list"
}
which yields e.g.:
projectA is IN the project list
projectX is NOT IN the project list
More info on that operator and many other aspects of the Groovy language from the always excellent MrHaki here
Of course, if you need to account for case differences, etc... you have to massage the code a bit, but at some point, a regexp might be warranted.
If you have already an collection, you should nearly always use an collection operator; E.g. replace
if ( "${PROJECT_NAME}" ==~ /projectA|projectB|projectC|projectD/) {
with:
if (PROJECT_NAME in projects) {
Much easier to read and understand, no? šŸ˜‰

Switching on String Value Yields Unexpected Results in Groovy

I am working in a groovy/grails set up and am having some trouble trying to execute a switch statement on a String value.
Basically, I am looping through the attribute names in a webservice response to see if they match pre-defined mappings that are configured on a per user basis. If they have established a mapping on that field, I pull the value out of the response and use it elsewhere.
The code looks something like this:
switch(attributeName)
{
case {attributeName} :
log.info("Currently switching on value... ${attributeName}")
case user.getFirstNameMapping():
model.user.userInfo.firstName = attributeValue
break
case user.getLastNameMapping():
model.user.userInfo.lastName = attributeValue
break
case user.getAuthenticationKeyMapping():
model.authenticationValue = attributeValue
break
case user.getEmailMapping():
model.email = attributeValue.toLowerCase()
break
}
The value being switched on (attributeName) is of type String, and the getter methods for the user instance also return type String.
Based on my research and understanding of the Groovy language, switching on an Object such as a String should end up using String.equals() to make the comparison. The result, however, is that it is matching on the user.getFirstNameMapping() case every time, and repeatedly overwriting the value in the model; therefore, the last value that comes back in the response is what ends up saved, and none of the other values are saved.
What's interesting is that if I use an if/else structure and do something like this:
if(attributeName.equals(user.getFirstNameMapping())
{
...
}
It works fine every time. I've verified through logging that it's not something silly like extra whitespace or a capitalization issue. I've also tried changing things around to run the switch by default and explicitly compare the attributeName in the case like this:
switch(true)
{
case {attributeName} :
log.info("Currently switching on value... ${attributeName}")
case {user.getFirstNameMapping().equals(attributeName)}:
model.user.userInfo.firstName = attributeValue
break
case {user.getLastNameMapping().equals(attributeName)}:
model.user.userInfo.lastName = attributeValue
break
case {user.getAuthenticationKeyMapping().equals(attributeName)}:
model.authenticationValue = attributeValue
break
case {user.getEmailMapping().equals(attributeName)}:
model.email = attributeValue.toLowerCase()
break
}
And it still fails to meet my expectations in the exact same way. So, I'm wondering why this is the behavior when the switch statement should simply be using .equals() to compare the strings, and when I explicitly compare them in an if/else using .equals(), it works as expected.
The issue is in your switch case.
Have a look here :-
case {attributeName} :
log.info("Currently switching on value... ${attributeName}")
case user.getFirstNameMapping():
model.user.userInfo.firstName = attributeValue
break
As you can see your these two cases will run every time because the switch condition is :-
switch(attributeName)
So the first one will get match and will run until it encounters break; which is at after case 2 i.e. case user.getFirstNameMapping(): so i would suggest you to print the value of {attributeName} before the swtich starts.
Hope that will help you.
Thanks
I don't know exactly what's your issue, but the case statement works just fine, even with methods. See my example
String something = "Foo"
class User {
String firstName
String lastName
}
User u = new User(firstName: 'Something', lastName:'Foo')
switch(something) {
case u.getFirstName():
println "firstName: ${u.firstName}"
break;
case u.getLastName():
println "lastName: ${u.lastName}"
break;
default:
println "nothing..."
}
This code will print lastName as expected.
ā€‹

Can switch use String.contains?

I'm trying to make this work, and it seems not to be accepted. Is there any fix, or workaround to it?
switch(email){
case (email.contains('acceptall')):
log.info email
break
default:
log.info "Doesn't work!"
}
I'm using groovy for a script in SoapUI
Use a regex, roughly:
switch (email) {
case ~/.*acceptall.*/:
log.info(email)
break;
default:
log.info("Doesn't work!")
}
http://groovy.codehaus.org/Logical+Branching#LogicalBranching-switchstatement
Switch supports the following kinds of comparisons
Class case values matches if the switchValue is an instanceof the
class
Regular expression case value matches if the string of the
switch
Value matches the regex Collection case value matches if the
switch
Value is contained in the collection. This also includes ranges
too (since they are Lists)
if none of the above are used then the case
value matches if the case value equals the switch value
you almost got it right, just need to turn it into a closure e.g.
switch (email) {
case { it.contains('acceptall') }:
log.info(email)
break;
default:
log.info("Doesn't work!")
}

Groovy - How can I compare part of a list to a string

I have a list which contains two types of text. One type is used for authorization while other type is used for all other purposes.
The type used for authorization always uses the same text + some code after it.
I would like to compare content of these two types of text and separate them based on content.
My idea is to look for pattern in authorization type and if it matches the pattern then this would be marked as authorization, otherwise it would be marked as "other".
I researched about comparison of patterns in Groovy, but all variations I tried did not work for me. Here is the part which should do the comparison, I am obviously doing something wrong but I don't know what.
jdbcOperations.queryForList(sql).collect { row ->
if(assert (row['MSG'] ==~ /token/)){
mark as authorization
}
else{
mark as other
}
}
Sorry for the vague code, I can not share more than this.
I think you just missing the match for the rest of the text, since you are looking only for the first part to match.
assert ("abc" ==~ /abc/) == true
assert ("abcdefg" ==~ /abc/) == false
assert ("abcdefg" ==~ /abc(.*)/) == true // <--- This can also be made more complicated

call name of method contained in a string

How can I call a method based on the value of a string in Groovy? For example instead of
switch (val) {
case "one":
Obj.one()
break
case "two":
Obj.two()
break
}
Iā€™d like to do something like obj.val where val contains either "one" or "two" instead of a case statement.
Dynamic method invocation looks like this
obj."$val"()

Resources