Using groovy, how can I substitute the value of an array in another array variable?
For eg.:
def Env = [
'Env1',
'Env2',
'Env3'
]
def Job = [
[
name: "Job1",
label: "<$Env>",
action: #!/usr/bin/bash
blah
blah
],
[
name: "Job2",
label: "<$Env>",
action: #!/usr/bin/bash
blah
blah
]
]
I want the label field in the second array Job to be populated by every item in Env
If the code isn't dynamic you can just do:
def Env = ['Env1','Env2', 'Env3']
def Job = [
[
name: "Job1",
label: "<${Env[0]}>",
action: '#!/usr/bin/bash'
],
[
name: "Job2",
label: "<${Env[1]}>",
action: '#!/usr/bin/bash'
]
]
If it's dynamic you can do:
Job.eachWithIndex{ obj, idx ->
obj.label = Env[idx]
}
Related
I have Cascade choice parameter 'mount_name' which is to form its value from referencing two other parameters. I tried -
choice(name: "project_name", choices: ["xxx", "null", "yyy"], description: "choose the appropriate project"),
choice(name: "environment", choices: ["dev", "qa", "pre-prod", "prod"], description: "choose the appropriate environment"),
[$class: 'CascadeChoiceParameter',
name: 'mount_name_name', choiceType: 'PT_SINGLE_SELECT', description: 'Choose the appropriate name',
filterLength: 1, filterable: false, referencedParameters: 'environment',
script: [$class: 'GroovyScript',
script: [
classpath: [],
sandbox: true,
script: """
if (environment == 'prod' || environment == 'pre-prod') {
return["efs-${params.project_name.replace('-','')}-prod"]
} else if (environment == 'dev') {
return["efs-${params.project_name.replace('-','')}-dev"]
} else {
return["efs-${params.project_name.replace('-','')}"]
}
""".stripIndent()
]
]
],
Expected result : environment = 'prod' , project_name='b2b-srv' then mount_name = 'efs-b2bsrv-prod'
Current result : environment = 'prod' , project_name='b2b-srv' then mount_name = nothing
I have an object list-
List<Person> personList = [
{name: "a" , age:20 },
{name: "b" , age:24 },
{name: "c" , age:25 },
{name: "d" , age:26 },
]
Now, what is the shortest way to remove age from each object?
Final list will be:
personList = [
{name: "a" },
{name: "b" },
{name: "c" },
{name: "d" },
]
With a bit syntax lift up your example works using findAll
def x = [
[name: "a" , age:20 ],
[name: "b" , age:24 ],
[name: "c" , age:25 ],
[name: "d" , age:26 ]
]
println x.collect {it.findAll {it.key != 'age'}}
[[name:a], [name:b], [name:c], [name:d]]
First of all you should not create a List with type of Person (unknown class) and fill it with Maps without cast.
With Maps you have at least 2 simple options.
Option 1 - create a new List:
personList = personList.collect{ [ name:it.name ] }
Option 2 - mutate the existing List:
personList*.remove( 'age' )
This is the URL I'm trying to hit:
/example/?fields=*&filter[platform][eq]=111&order=date:asc&filter[date][gt]=1500619813000&expand=yes
My code:
get("/release_dates",
query: [
fields: "*",
order: "date:desc",
expand: "games",
filter: %{
date: %{gt: unix_now},
version_parent: %{not_exists: 1}
}
]
)
I'm trying to perform a Tesla GET request that has those filter[date][gt]=123123123123 type query param.
Appreciate the help!
If I understand you correctly, you want to generate a URI with a filter for "greater than" timestamps which are variable.
According to your inital example, this can be done like this:
Tesla.get("/example/",
fields: "*",
filter: [
platform: [
eq: 111
]
],
order: "date:asc",
filter: [
date: [
gt: unix_now
]
],
expand: "yes"
)
Note that /example is a relative reference and can only be resolved with a base URI. Better provide a complete URI.
If you want to experiment with the URI generator in an iex console, you can use iex -S mix in your project directory and then use the following functions:
Tesla.build_url("/example/",
fields: "*",
filter: [
platform: [
eq: 111
]
],
order: "date:asc",
filter: [
date: [
gt: 123123123123
]
],
expand: "yes"
) |> URI.decode()
I have a ruby script that I need to convert to Groovy, its a simple case of removing a collection if key: value.
So in my setup I make a request to the github api
def jsonParse(def json) {
new groovy.json.JsonSlurperClassic().parseText(json)
}
def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
return list
This returns output like so
[
[prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
[prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]
In Ruby i would do the following
array.delete_if { |key| key['prerelease'] == true }
How would I approach this with Groovy, if an explanation could be provided that would also be great so i can learn from it
Update
Using the approach from #Rao my list is exactly the same
def request = sh script: """curl https://api.github.com/repos/org/${repo}/releases?access_token=${env.TOKEN}""", returnStdout: true
def list = jsonParse(request)
list.removeAll(list.findAll{it.prerelease == 'true'})
return list
Raw response
[
{"prerelease": true, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"],
{"prerelease": false, "author": [ {"surname": "surname", "book": "title"}, "surname": "surname"]
]
e. g. with
array = array.findAll { it.prerelease != 'true' }
I guess you don't need anymore explanation?
The sample data is list of maps.
Need to remove the items from the list by filtering prerelease is equal to true. Hope this is string only as embedded between the quotes.
Here is the script which results filtered list.
def list = [
[prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
[prerelease: 'true', author: [surname: 'surname', book: 'title'], surname: 'surname'],
[prerelease: 'false', author: [surname: 'surname', book: 'title'], surname: 'surname']
]
//Remove all those elements(map) from list if matching the condition
list.removeAll(list.findAll{it.prerelease == 'true'})
//Show the updated list
println list
You can quickly try it online Demo
EDIT: based on OP comment.
Isn't this below output what you want?
EDIT2: Based on OP changed response as Json
def json = """[
{"prerelease": true, "author": [ {"surname": "surname", "book": "title"}]},
{"prerelease": false, "author": [ {"surname": "surname", "book": "title"}]}
]"""
list = new groovy.json.JsonSlurper().parseText(json)
println new groovy.json.JsonBuilder(list.findAll{ it.prerelease != true }).toPrettyString()
Does anyone have any sample Groovy code to convert a JSON document to CSV file? I have tried to search on Google but to no avail.
Example input (from comment):
[ company_id: '1',
web_address: 'vodafone.com/',
phone: '+44 11111',
fax: '',
email: '',
addresses: [
[ type: "office",
street_address: "Vodafone House, The Connection",
zip_code: "RG14 2FN",
geo: [ lat: 51.4145, lng: 1.318385 ] ]
],
number_of_employees: 91272,
naics: [
primary: [
"517210": "Wireless Telecommunications Carriers (except Satellite)" ],
secondary: [
"517110": "Wired Telecommunications Carriers",
"517919": "Internet Service Providers",
"518210": "Web Hosting"
]
]
More info from an edit:
def export(){
def exportCsv = [ [ id:'1', color:'red', planet:'mars', description:'Mars, the "red" planet'],
[ id:'2', color:'green', planet:'neptune', description:'Neptune, the "green" planet'],
[ id:'3', color:'blue', planet:'earth', description:'Earth, the "blue" planet'],
]
def out = new File('/home/mandeep/groovy/workspace/FirstGroovyProject/src/test.csv')
exportCsv.each {
def row = [it.id, it.color, it.planet,it.description]
out.append row.join(',')
out.append '\n'
}
return out
}
Ok, how's this:
import groovy.json.*
// Added extra fields and types for testing
def js = '''{"infile": [{"field1": 11,"field2": 12, "field3": 13},
{"field1": 21, "field4": "dave","field3": 23},
{"field1": 31,"field2": 32, "field3": 33}]}'''
def data = new JsonSlurper().parseText( js )
def columns = data.infile*.keySet().flatten().unique()
// Wrap strings in double quotes, and remove nulls
def encode = { e -> e == null ? '' : e instanceof String ? /"$e"/ : "$e" }
// Print all the column names
println columns.collect { c -> encode( c ) }.join( ',' )
// Then create all the rows
println data.infile.collect { row ->
// A row at a time
columns.collect { colName -> encode( row[ colName ] ) }.join( ',' )
}.join( '\n' )
That prints:
"field3","field2","field1","field4"
13,12,11,
23,,21,"dave"
33,32,31,
Which looks correct to me