Groovy build a list from two lists - groovy

I have two array list in that form:
def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = [C:\Temp\Media\Media.c2v, C:\Temp\Media\Media.V2C, C:\Temp\Media\toto\test\巨塔の終わり.mp4, C:\Temp\Media\toto\toto.mxf]
I'm trying to build a new list mySelectedPath from myPaths only if it matches one of the extensions from AllowedExtensions
I'm looking for the groovy way to do it but can't get it working correctly.
AllowedExtensions.each { mySelectedPath = myPaths.findAll { it }}
Here is my expected result:
[C:\Temp\MediaNavigator\toto\toto.mxf, C:\Temp\MediaNavigator\toto\test\巨塔の終わり.mp4]
Thank you for any input !

Another solution is to use findResults
allowedExtensions.findResults { ext -> myPaths.find { it.endsWith ext } }
If you want multiple results per extension, try:
allowedExtensions.findResults { ext -> myPaths.findAll { it.endsWith ext } }.flatten()

def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = [
'C:\\Temp\\Media\\Media.c2v',
'C:\\Temp\\Media\\Media.V2C',
'C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4',
'C:\\Temp\\Media\\toto\\toto.mxf'
]
println myPaths.findAll { it.toLowerCase()[it.lastIndexOf('.')..-1] in AllowedExtensions }

Or regex-based:
def AllowedExtensions = [ '.mxf', '.mov', '.mp4']
def myPaths = ['C:\\Temp\\Media\\Media.c2v', 'C:\\Temp\\Media\\Media.V2C', 'C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4', 'C:\\Temp\\Media\\toto\\toto.mxf']
def regex = /^.*\.(${AllowedExtensions.join( '|' ).replace( '.', '' )})$/
def res = myPaths.grep{ it ==~ regex }
assert res.toString() == '[C:\\Temp\\Media\\toto\\test\\巨塔の終わり.mp4, C:\\Temp\\Media\\toto\\toto.mxf]'

Related

Groovy append to json file

I have a jenkins pipeline script, where I am collecting the data as json format. I want all the data to be updated in a string and finally write to a json file. But in my script, the value is over written.
for(String item: jsonObj.devices) {
os = item.os
if(!os.contains("\\.")) {
osV = os + ".0"
} else{
osV = os
}
def osValues = osV.split('\\.')
if(values[0].toInteger() <= osValues[0].toInteger()) {
name = item.name
def data = [
name: "$name",
os: "$os",
]
def json_str = JsonOutput.toJson(data)
def json_beauty = JsonOutput.prettyPrint(json_str)
writeJSON(file: 'message1.json', json: json_beauty)
}
}
I want all the data to be collected and finally write to sample.json. Please let me know where I am wrong.

convert string output of for loop into a single array in Groovy

I need to take my output from the for loop below and add it to a single array. The list object can either be ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"] or ["envName-inactive-2", "", "", "envName-active-2"]
My code:
if (appendVersion) {
for (elements in list) {
test = (elements + "-" + branch)
println(test)
}
} else {
println(list)
}
output:
envName-inactive-1-v2
active-1-v2
inactive-1-v2
envName-active-1-v2
and
envName-inactive-2-v2
-v2
-v2
envName-active-2-v2
desired output:
["envName-inactive-1-v2", "active-1-v2", "inactive-1-v2", "envName-active-1-v2"]
and
["envName-inactive-2-v2", "", "", "envName-active-2-v2"]
You desired format seems to be json. In Jenkins you have option to use writeJSON to convert list to json format.
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = writeJSON returnText: true, json: versionedList
println json
the same in plain groovy:
def branch = "v2"
def list = ["envName-inactive-1", "active-1", "inactive-1", "envName-active-1"]
def versionedList = list.collect{it ? it+'-'+branch : ''}
def json = new groovy.json.JsonBuilder(versionedList).toString()
println json
result:
["envName-inactive-1-v2","active-1-v2","inactive-1-v2","envName-active-1-v2"]

Groovy Script with XmlSlurper

I have an XML file that I am trying to parse through with Groovy.
<?xml version = '1.0' encoding = 'UTF-8'?>
<ServerList>
<Server>server1.me.com</Server>
<CleanUpTest>TESTING</CleanUpTest>
<Server>server2.me.com</Server>
</ServerList>
This code works and gives me the output Result: [server1.me.com]:
def serverList = new XmlSlurper().parse("E:\\Program Files(x86)\\Jenkins\\jobs\\first_servers.xml")
def output = []
serverList.Server.find { it == 'server1.me.com' }.each{
output.add(it)
}
return output
But when I try to get the value in CleanUpTest it is not working.
def serverList = new XmlSlurper().parse("E:\\Program Files(x86)\\Jenkins\\jobs\\first_servers.xml")
def output = []
serverList.Server.find { it == 'server1.me.com' }.CleanUpTest.each{
output.add(it)
}
return output
What do I have wrong? I am expecting Result: [TESTING]

how i use groovy to insert a node which has attribute and value

there is a simple xml, for example:
def rootNode = new XmlSlurper().parseText(
'<root>
<one a1="uno!"/>
<two>Some text!</two>
</root>' )
how can i insert a node
<three type='c'>2334</three>
into root?
i have use this way to insert
rootNode.appendNode{three(type:'c') 2334}
rootNode = new XmlSlurper().parseText(rootNode)
but it return exception.
Below script should give you desired result:
change from yours: three (type:'c', 2334)
import groovy.xml.*
def rootNode = new XmlSlurper().parseText('<root><one a1="uno!"/><two>Some text!</two></root>' )
rootNode.appendNode {
three (type:'c', 2334)
}
def newRootNode = new StreamingMarkupBuilder().bind {mkp.yield rootNode}.toString()
println newRootNode
Output:
<root><one a1='uno!'></one><two>Some text!</two><three type='c'>2334</three></root>

How to assert json response content using groovy?

in the response of a request i have this content:
"comp":[
{
"type":"header",
"version":1,
"settings":
{"logo":"mylogo",
"logoPosition":"left",
"inverseLogosPosition":false,
"headerTitle":"My Report",
"headerTitlePosition":"left",
"pageBreak":false
}
},
I want to assert the content of settings.
i try this for example to assert the logoPosition = "left"
assert json.components.settings[0].logoPosition[0] == "left"
it's not working
This part is working well:
assert json.comp.type[0] == "header"
assert json.comp.version[0] == 1
Any help please, thank you
The json provided is invalid. You can use both paths:
assert slurped.comp.settings.logoPosition[0] == "left"
assert slurped.comp[0].settings.logoPosition == "left"
Full example:
import groovy.json.JsonSlurper
def json = '''{
"comp":[
{
"type":"header",
"version":1,
"settings": {
"logo":"mylogo",
"logoPosition":"left",
"inverseLogosPosition":false,
"headerTitle":"My Report",
"headerTitlePosition":"left",
"pageBreak":false
}
}
]}'''
def slurped = new JsonSlurper().parseText(json)
assert slurped.comp.settings.logoPosition[0] == "left"
assert slurped.comp[0].settings.logoPosition == "left"
It will just be logoPosition, not logoPosition[0]
Why not have some expected json as a string, convert it to a map with JsonSlurper, then compare these?

Resources