Reputation: 1
I would like to ask if there's a way to parse a version number using a groovy script.
I extract from Ariba a payload, the issue comes with a specific field called ItemNumber
.
At first it was working, but this month I started to retrieve a version instead of a float.
This is the part of the script that needs to be changed, but I can't find a way to do it.
if (ItemNumber?.trim()){
list.ItemNumber = Double.parseDouble(ItemNumber.toString());
}
EDIT: This is the field I retrieve: { "ItemNumber": "4.4.5" }
.
I would like to get this: { "ItemNumber" : 4.4.5 }
.
Any help is greatly appreciated,
Thank you, Kostas
Upvotes: 0
Views: 593
Reputation: 48590
To parse a version number, you will need to tokenize the string. You should create a Version
class to hold the version information. This can help when sorting a list of versions. After tokenizing, you can call the Version
constructor, and pass the tokens as integers.
Once you have a Version
object, you can access fields like major
, minor
, and patch
.
class Version {
int major
Integer minor, patch
@Override String toString() {
return [major, minor, patch].findAll().join('.')
}
}
def parseVersion(String versionString) {
if (!versionString) return null
int[] tokens = versionString.split(/\./).collect { it as int }
return new Version(
major: tokens[0],
minor: tokens.length > 1 ? tokens[1] : null,
patch: tokens.length > 2 ? tokens[2] : null,
)
}
class Payload {
String ItemNumber
}
Payload payload = new Payload(ItemNumber: "2.4")
Version version = parseVersion(payload.ItemNumber?.trim())
printf("Major version : %d%n", version.major)
printf("Minor version : %s%n", version.minor ?: "<UNSET>")
printf("Patch version : %s%n", version.patch ?: "<UNSET>")
printf("Full version : %s%n", version)
In later versions of Groovy, you can call the Versions
constructor like this:
new Version(major: tokens[0], minor: tokens?[1], patch: tokens?[2])
Upvotes: 0