Groovy String and datestamp - groovy

I am new to Groovy and wonder following is possible?
I have a file generated automatically with datestamp, example saledata20180429
Is it possible to code this with Groovy and convert the filename to saledata-2018-04-29.txt

Simple substring calls can get that done:
def name = 'saledata20180429'
def newname = "saledata-${name[8..11]}-${name[12..13]}-${name[14..15]}.txt"
newname evaluates to 'saledata-2018-04-29.txt'

Related

Cannot replace string text in Groovy script

I am trying to replace a test in pom.xml using a groovy script. These are my two approaches. The text should be replaced is {env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}
Approach one
File mainPomXml = new File(rootDir,'/pom.xml')
mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
Approach two
def mainPomXml = new File(rootDir,'/pom.xml')
def mainPom = mainPomXml.text.replace('{env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}','${env.AM_$environment.toUpperCase()_SERVER_CREDS_USR}');
mainPomXml.write(mainPom);
But none of these approaches work. That means both executes but the test is not get replaced. How to fix this issue?
Change the mainPom part as below.
def mainPomXml = new File(rootDir, '/pom.xml')
def mainPom = mainPomXml.text.replace('AM_SERVER_CREDS_USR', '${env.AM_'+ env.toUpperCase() +'_SERVER_CREDS_USR}')
mainPomXml.write(mainPom)

How to append multiple strings in Groovy?

I am parsing an XML file in Groovy and later I need to append the variables returned.
def lmList = slurperResponse.LastGlobal.HeatMap
String appendedString = lmList.country + lmList.ResponseTime + lmList.timeset
This doesn't work to append the 3 strings. It just assigns the first string to the right. How to properly implement it in Groovy? I tried concat and it threw the following error:
groovy.lang.MissingMethodException: No signature of method: groovy.util.slurpersupport.NodeChildren.concat() is applicable for argument types: (groovy.util.slurpersupport.NodeChildren) values: [4468]
Possible solutions: toFloat(), collect(), collect(groovy.lang.Closure)
at
Yor code shall look like:
String appendedString = "${lmList.country}${lmList.ResponseTime}${lmList.timeset}"
The exception you are getting means, that you are trying to invoke the plus()/concat() method which is not provided by NodeChildren
As an alternative to injecteer -
def lmList = slurperResponse.LastGlobal.HeatMap
String appendedString = lmList.country.toString() + lmList.ResponseTime.toString() + lmList.timeset.toString()
You weren't trying to add strings, you were trying to add nodes the happen to contain strings.
Assuming the xml looks like:
def xml = '''
<Root>
<LastGlobal>
<HeatMap>
<Country>USA</Country>
<ResponseTime>20</ResponseTime>
<TimeSet>10</TimeSet>
</HeatMap>
</LastGlobal>
</Root>
'''
Below should give what is expected:
def slurped = new XmlSlurper().parseText(xml)
assert slurped.LastGlobal.HeatMap.children()*.text().join() == 'USA2010'

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>
"""

Groovy shell concatenate Strings

I am trying to concatenate two strings using groovy shell but it's not working
groovy.shell("def name = 'MyName'; def fname = 'firstName'; println name+fname" );
But for single string this is working
groovy.shell("def name ='MyName'; println name");
Any idea about this?
You can Use StringBuilder as below
Object value = shell.evaluate("def name= new StringBuilder('James'); def fname= new StringBuilder('abd'); println name.append(fname) ;");

Groovy remove part of string within < >

Hi In Groovy I need to remove part of string
the string.
<Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>
should look like " Updated User id:nish.test11
how can i do that?
As the content looks like an XML,
def xml = """
<Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>
"""
it's better to use XmlSlurper than parsing/extracting strings by hand
def result = new XmlSlurper().parseText(xml)
println result.toString()
this gives the desired result (the content of the Result)
If I run the code:
""" <Results xsi:type="xsd:string"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">Updated User
id:nish.test11</Results>""".replaceAll( /<\/?[^<>]>/, '' ).replaceAll( /[\n\s]+/, ' ' )
it gives me
Updated User id:nish.test11
as output

Resources