How can a groovy script help in extracting the Version Number using Parse()?

Seeking guidance on parsing a version number using a groovy script

When extracting a payload from Ariba, encountering an issue with the ItemNumber field

Initially, it parsed as a float, but now returning a version instead

Struggling to update this part of the script

if (ItemNumber?.trim()){
        list.ItemNumber = Double.parseDouble(ItemNumber.toString());
    }
    

UPDATE: Current field retrieved: { "ItemNumber": "4.4.5" }

Desired format: { "ItemNumber" : 4.4.5 }

Any assistance would be greatly appreciated,

Thanks, Kostas

Answer №1

When it comes to parsing a version number, the first step is to tokenize the string. It's recommended to create a custom class called Version to store all the version details. This makes it easier to manage and sort a collection of versions. Once the string is tokenized, you can instantiate a new Version object by passing the tokens as integer values.

With a Version object in hand, you can easily access fields such as 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 releases of Groovy, the Version constructor can be invoked in a simplified manner like this:

new Version(major: tokens[0], minor: tokens?[1], patch: tokens?[2])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Looking to update the elements within a KnockoutJS observable array

In my code, I have a knockoutJS observable array that was created in the typical way: var MyGridModel = function(items) { var self = this; this.items = ko.observableArray(items); ... Now, I want to update this array with new data. My goal here is to comp ...

Using Jquery to loop through various select options within a designated container div

I am seeking a way to loop through multiple select options within a specific div using the jQuery each function. If any field is left empty during this iteration, I would like the loop to break and set the reqCourseFlag variable to 0. The current implement ...

Ways to unlock all the information windows in Google Maps

Is it possible to automatically display all info windows on the map when it is first opened, eliminating the need for users to click on markers? In other words, I would like all info windows for all markers to be shown by default when the map is opened. ...

How can I access a component variable within a foreach loop in Typescript?

Can anyone please explain how I can access a component variable within a foreach loop? Check out my code on Plunker public exampleVariable:number; test(){ console.log('fired'); var x =[1,2,3,4]; x.forEach(function (e){ th ...

When using AutoComplete in MUI, I encountered an issue while attempting to assign a default value to the checkbox from an API. Instead of achieving the desired result, I received an error stating "(inter

Within this snippet, I am seeking to retrieve a default value from the API to populate a checkbox initially. I have employed the Material-UI Autocomplete component, which includes a defaultValue prop. Despite my efforts to utilize this prop, I am encounter ...

Automatically Populate list upon webpage initialization - React, Redux, Firebase

A webpage I am working on consists of two main components: Categories and Items By utilizing the function initCategories() called within the componentDidMount() lifecycle method of Categories, I successfully display all categories on the screen. The initC ...

An error was thrown at line 474 in module.js

After recently installing nodejs on my laptop, I'm struggling to run a js file in the node environment. I attempted using this command: node C:\Program Files\nodejs\file.js, but encountered the following error: module.js:474 thr ...

Tips for effectively nesting HTML Custom Elements visually

I'm currently working on developing a basic HTML Custom Element for incorporating trees into web pages. The code structure I'm using is quite simple, as shown below: <html-tree title="root"> <tree-node title="child1" ...

Looking to customize scrolling behavior when navigating back in Next.js?

I have a function in my index.js file that fetches a list of posts like this: const Index = (props) => { return ( <div> {props.posts.map((each) => { return ( <Link scroll={false} as ...

An incorrect object was removed from the array

Having an issue where the wrong item is getting deleted from an array in my component's state. Here is a simplified version of my parent Component: export default class BankList extends Component { state = { banks: [new Bank("Name1"), new ...

How to execute a JavaScript function within PHP code

Hey there, seeking some assistance. On my main page index.php, I have a simple js function named function1() that opens test.php as a pop-up window when clicked. The content in this pop-up window comes from another page called p1.php. Now, I need to set it ...

Creating a serial number in a Class without relying on a global variable is a useful technique that

I am looking for a way to assign a unique ID to each instance of a Class without relying on global variables. I have tried using a global variable and incrementing it, but I would prefer a more efficient approach. Is there a way to generate an ID within t ...

`Check out Vue3's property watching feature`

Currently, I have a form that is being edited and the created method is used to prefill the form information from an api call, which works perfectly fine. However, my goal is to monitor the fields in the form. If any of them are edited, I want to set a va ...

The VueJS Watcher fails to activate when monitoring changes within nested objects

I have created a codesandbox to demonstrate my issue: codesandbox example watcher not triggering. Currently, I am developing a component that depends on an object with dynamically added data. In a separate .js file, I export the following object: export d ...

Creating a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

Ways to invoke a class method by clicking on it

My initialization function is defined as follows: init: function() { $("#editRow").click(function() { <code> } $(".removeRow").click(function() { <code> } } I am trying to find a way to call the class method removeRow directly in the onc ...

Managing VueJS components and Observers during the rendering process to ensure smooth functionality in a multi-phase environment

Situation: As part of my development work, I am creating a Vue scroll component that encompasses a variable number of HTML sections. This component dynamically generates vertical page navigation, allowing users to either scroll or jump to specific page lo ...

HTML-Formatted Email Content

Similar Question: MailTo with HTML body I am looking to utilize JavaScript to send emails. I came across this helpful post: Sending emails with JavaScript. My goal is to include images, bold text, and color changes in the email content. Does anyone h ...

The absence of parameters in the Express.js middleware object

const application = express(); let routerInstance = require('express').Router({mergeParams: true}); const payloadMiddlewareFunction = (request, response, next) => { console.log('A:', request.params); const {params, query} = reque ...

What are some ways to lazily load directives in AngularJS?

Currently, I am exploring the capabilities of angularjs and aiming to dynamically load directives only when they are required instead of loading all of them initially on the page. My focus is on creating custom directives for the plugins that I use frequen ...