PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label groovy. Show all posts
Showing posts with label groovy. Show all posts

Monday, December 19, 2022

[FIXED] How to Groovy-ify a null check?

 December 19, 2022     groovy, null-check, syntax     No comments   

Issue

Is there a more "Groovy" way to write this Groovy code:

def myVar=(System.getProperty("props") == null)?
    null : System.getProperty("props")

Logic is:

  • If System.getProperty("props") is NULL, I want props to be NULL;
  • Else, I want props to be the value of System.getProperty("props")

Solution

Typically for null-checking I reach for ?: (elvis operator, returns a default value if the left-hand side is null or resolves to false) or ?. (safe navigation, evaluates to null if left-hand side is null). If you want to set a default value to use when a property is not present you can do this:

def myVar = System.properties['props'] ?: 'mydefaultvalue'

which sets myVar to 'mydefaultvalue' if there is nothing found in System.properties for the key 'props' (or if the value returned resolves to false).

But since the default value in your case is null then

def myVar = System.properties['props']

would do the job as well, because when nothing is found for the given key then null is returned.

The Groovy-ifications here are:

  • prefer single-quoted strings to double-quoted ones if you don't need GroovyString interpolation

  • use indexing-with-brackets syntax for maps and lists (instead of 'get' or 'put')

  • use the shortened property form (without the get prefix) if the getter has no arguments (unlike Java, Groovy implements the universal access principle); System.getProperty(String) is a convenience for Java programmers but it's unneeded in Groovy

  • shorten default-if-null cases with ?:

This idiom found in JavaScript using || :

def myVar = System.properties['props'] || 'mydefaultvalue'

doesn't work in Groovy. The result of a boolean test is a boolean, so myVar gets set to true.



Answered By - Nathan Hughes
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 21, 2022

[FIXED] How can I get objects based off of certain associations?

 October 21, 2022     grails, grails-orm, groovy, has-many     No comments   

Issue

I have the following domain classes (Only trying to show what is needed to get the idea) :

class Scholarship {

   static hasMany = [grades:Grade]
}

and

class Grade {

   String id
   String description
}

In words I would like to, "Get all scholarships where the associated grade_id = myId". I would like to accomplish this using grails domain classes and not using sql. Any help appreciated


Solution

Are you looking for something like this?...

def results = Scholarship.withCriteria {
    grades {
        // myId must be defined somewhere above...
        idEq myId
    }
}

EDIT

A comment below adds to the original question and asks what if another relationship was expressed like this...

class Scholarship {
    static hasMany = [grades:Grade,majors:Major]     
}

The query I show above would still be exactly the same. The fact that there is a majors collection would not be relevant unless you wanted to include some attribute of Major to also be part of the criteria, which could look something like this...

def results = Scholarship.withCriteria {
    grades {
        // myId must be defined somewhere above...
        idEq myId
    }

    majors {
        // only return Scholarship instances which
        // contain a Major with the name 'Mechanical Engineering'
        eq 'name', 'Mechanical Engineering'
    }
}

I hope that helps.



Answered By - Jeff Scott Brown
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 26, 2022

[FIXED] How can I create parallel stages in Jenkins scripted pipeline?

 September 26, 2022     continuous-deployment, continuous-integration, groovy, jenkins-groovy, jenkins-pipeline     No comments   

Issue

I am trying to implement parallelization in my Jenkins pipeline code where I can run two stages in parallel. I know this is possible in declarative pipeline, but I am using scripted pipeline.

I've attempted to implement this by doing something like this:

parallel(
    stage('StageA') {
        echo "This is branch a"
    },
    stage('StageB') {
        echo "This is branch b"
    }
  )

When I run this and look at this in Blue ocean, the stages do not run in parallel, but instead, StageB is executed after StageA. Is it possible to have parallel stages in scripted jenkins pipeline? If so, how?


Solution

Try this syntax for scripted pipeline:

            parallel(
                    "StageA": {
                        echo "This is branch a"
                    },
                    "StageB": {
                        echo "This is branch b"
                    }
            )

It should look like this in Blue Ocean, this is what you expect right?

Parallel blue ocean

If you want to see the stages (and console output) in the classic view, you can use stage like this:

 parallel(
                        "StageA": {
                            stage("stage A") {
                                echo "This is branch a"
                            }
                        },
                        "StageB": {
                            stage("stage B") {
                                echo "This is branch b"
                            }
                        }
                )


Answered By - Unforgettable631
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, August 22, 2022

[FIXED] How to use Jenkins pipeline variable into powershell or cmd code?

 August 22, 2022     environment-variables, groovy, jenkins, windows     No comments   

Issue

I am in need of modifying a Jenkins Pipeline script. This is a snippet. It works down to the Def in the rename. The error I get is

groovy.lang.MissingPropertyException: No such property: newFileName for class: groovy.lang.Binding

I am looking to inject the version number into the filename which is then processed by a homegrown app to move it where it needs to go and some other stuff. I have tried passing the concatenated ${version} into the Upload executable but it then errors as a literal instead of a variable.

Update: I predefine the variable and get a new error

powershell.exe : newFileName : The term 'newFileName' is not recognized as the name of a cmdlet, function, script file, or operable At C:\workspace\workspace\Centurion Dashboard@tmp\durable-eb5db1ae\powershellWrapper.ps1:3 char:1 & powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -Comm

  • CategoryInfo : NotSpecified: (newFileName : T...e, or >operable :String) [], RemoteException
    • FullyQualifiedErrorId : NativeCommandError

Thoughts?

stage('Rename') {
      powershell """
        rename-item -Path "C:\\Users\\Administrator\\Documents\\Advanced Installer\\Projects\\Proj\\Setup Files\\SetupCenturionDashboard.exe" -NewName "OtherProject-${version}.exe"
        def newFileName = "C:\\Users\\Administrator\\Documents\\Advanced Installer\\Projects\\Proj\\Setup Files\\OtherProject-" + ${version} + ".exe"
        echo ${newFileName} 
    """
} 

    stage('Upload') {
      bat label: 'Upload', script: 'C:\\Static\\BuildHelper\\BuildHelper.exe ${newFileName} "develop" "home" "${version}"'
}

Solution

powershell != groovy

You cannot run groovy inside of powershell block

powershell """

"""

and def newFileName is groovy, that is why you get the error:

The term 'newFileName' is not recognized as the name of a cmdlet...

As you can see, newFileName executable does not exist on windows.

variables on windows

If you just need to pass the version and newFileName variables to your powershell or bat code, you need to use the windows syntax %var% for variables, not the unix ${var} and use global variables if it is possible in your pipeline:

def version = "1.0.0";
def newFileName;

stage('Rename') {
    powershell """
        rename-item -Path "C:\\Users\\foo.exe" -NewName "OtherProject-%version%.exe"
    """
    newFileName = "C:\\Users\\OtherProject-${version}.exe"
} 

stage('Upload') {
    bat label: 'Upload', script: 'C:\\Static\\BuildHelper\\BuildHelper.exe %newFileName% "develop" "home" "%version%"'
}


Answered By - JRichardsz
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 9, 2022

[FIXED] How to dynamically find web element by XPath in Selenium using Katalon

 July 09, 2022     groovy, java, katalon, keyword, selenium     No comments   

Issue

driver.findElement(By.xpath("//*[contains(text(),'"+ ProjectName +"')]")).click();

I tried to use this code to find web element dynamically, but when I tried to call it on my test case seems that it cannot have an input value since this code is a part of my custom keyword code. Can someone help me try to find a way on how to do it. Thank you very much!


Solution

To click on element you can use following method:

public void clickOnElement(String xpath) {
    driver.findElement(By.xpath(xpath)).click();
}

To format a String according to passed parameter you can use this:

public String stringFormat(String template, String parameter){
    return String.format(template,parameter);
}

For the specific use like in your question the template can be defined like this:

String elementTextTmplt = "//*[contains(text(),'%s')]"


Answered By - Prophet
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home
View mobile version

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing