How to append comma separated value dynamically in groovy - groovy

I've comma separated values which I want to iterate and append the value dynamically like below:
def statusCode = '1001,1002,1003'
Output should look like this:
[item][code]=1001|[item][code]=1002|[item][code]=1003
If statusCode has only two value. For example:
def statusCode = '1001,1002'
Then output should be
[item][code]=1001|[item][code]=1002
I tried something like below since I'm new to groovy not sure how can achieve this with some best approach:
def statusCode= '1001,1002,1003'
String[] myData = statusCode.split(",");
def result
for (String s: myData) {
result <<= "[item][code]="+s+"|"
}
System.out.println("result :" +result);

You can use collect and join to simplify the code:
def result = statusCode.split(',').collect{"[item][code]=$it"}.join('|')
That returns [item][code]=1001|[item][code]=1002|[item][code]=1003

Related

groovy saving lines from file into collection

Hi I want do save collection from textfile in groovy and save only chosen lines.
I have a file contains that plaintext:
!!file-number1:
!!123.sql
!!123.jpeg
!!333.jpeg
!!texttextext.jpeg
and I want to save it to collection with that result
collection = ['123.jpeg', '333.jpeg', 333.jpeg', 'textextex.jpeg']
Only .jpeg and without "!!"
String filePath = "path/to/file.txt"
File myFile = new File(filePath)
def collection = myFile.collect().retainAll {it == '*.jpeg'}
println collection
And my question is how to remove or ignore things like "!!" and how to print that collection, because i got only output "true".
You can use findResults to "filter" and "map" in one go. e.g.
def lines = """!!file-number1:
!!123.sql
!!123.jpeg
!!333.jpeg
!!texttextext.jpeg"""
println lines.readLines().findResults{ def m = it =~ /!!(.*\.jpeg)/; m ? m[0][1] : null }
// → [123.jpeg, 333.jpeg, texttextext.jpeg]
Or a little bit easier to read, without using the Matcher object:
String filePath = "path/to/file.txt"
def lines = new File(filePath)
.collect()
.findAll { it ==~ /.*jpeg/ }
.collect { it[2..-1] }
println lines
In your example, retainAll() modifies the initial collection and returns a boolean value. See here: https://docs.groovy-lang.org/latest/html/groovy-jdk/java/util/Collection.html

How to create a new variable using old variable and assiging it some value in groovy

I am trying to create a new variable using the name of old variable (appending old variable with some string) and assign that new variable with some value as in example below in jenkinsfile using groovy:
def var1= "value1"
def var1 + "_someval"= 50 // creating a new variable which will have name value1_someval and it will have value 50
print( "value for value1_someval is" + value1_someval)
// expected output is that new variable value1_someval is created with value 50 assigned to it.
Whatyou want to do is possible, but it's messy and can cause problems. I strongly suggest that you use a list instead:
List li = []
li[0] = "value1"
li[1] = 50
I got this working by using quoted identifies in following way:
def map = [:]
def lastchar = "_someval"
map."val1${lastchar}" = 50
//assert map.'val1_someval' == 50
print map.VA_REPOSITORY_VERSION
prints out 50 as output

Splitting name using hyphen and iteration

I wish to make a function which would split a name using hyphens("-")
def tag(name):
for word in list(name):
*something*
return variable
print(tag('Richard'))
desired output
'R-i-c-h-a-r-d-'
you want to use the join function on a string, which operates on the 'joiner' (in your case, '-') and accepts either a list, or another string.
So, you could have '-'.join('Richard'),
or
def tag(name):
return '-'.join(name)
Try this below :
def tag(name):
output = name[0]
for i in name[1:]:
output += '-' + i
return output
print(tag('Richard'))
OR
def tag(name):
return '-'.join("Richard")

Groovy : datetime delta and JsonOutput.toJson

I'm trying to return some data from the database. When I call the method JsonOutput.toJson() with the provided data, it automatically changes the delta of my datatime.
This is my code :
def result = groovy.json.JsonOutput.toJson(data)
println(data)
println(result)
response.setContentType("application/json");
The first prints the following:
[[ DateStart:2019-01-14 09:34:51.0, DateEnd:2019-01-14 10:27:22.68]]
And the second after the json formatting show another date (hours - 1) :
[{"DateStart":"2019-01-14T08:34:51+0000","DateEnd":"2019-01-14T09:27:22+0000"}]
Any tips to format to JSON without changing any date/delta?
Based on the data.toString() output format:
[[ DateStart:2019-01-14 09:34:51.0, DateEnd:2019-01-14 10:27:22.68]]
it looks like you are dealing with JSON serialization of thejava.sql.Timestamp type. If you want to prevent the default timestamp serializer from being used, you will have to format timestamps manually before JSON serialization happens.
Consider the following example:
import groovy.json.JsonOutput
import java.sql.Timestamp
def format = "yyyy-MM-dd'T'hh:mm:ss.S"
def date = new Date().parse(format, "2019-01-14T09:34:51.0")
def dateStart = new Timestamp(date.time)
def dateEnd = new Timestamp((date + 20).time)
def data = [[DateStart: dateStart, DateEnd: dateEnd]]
println "Raw data:"
println data
println "\nJSON without formatting:"
println JsonOutput.toJson(data)
data = data.collect { el -> el.collectEntries { k,v ->
def value = v instanceof Timestamp ? v.format(format) : v
return [(k): value]
}}
println "\nJSON after formatting:"
println JsonOutput.toJson(data)
The output:
Raw data:
[[DateStart:2019-01-14 09:34:51.0, DateEnd:2019-02-03 09:34:51.0]]
JSON without formatting:
[{"DateStart":"2019-01-14T08:34:51+0000","DateEnd":"2019-02-03T08:34:51+0000"}]
JSON after formatting:
[{"DateStart":"2019-01-14T09:34:51.0","DateEnd":"2019-02-03T09:34:51.0"}]
The most important part (formatting timestamp value to its string representation) happens in the following part:
data = data.collect { el -> el.collectEntries { k,v ->
def value = v instanceof Timestamp ? v.format(format) : v
return [(k): value]
}}
It assumes that your list of maps may contain other key-value pairs which don't hold the timestamp value. If we deal with a timestamp, we format it using yyyy-MM-dd'T'hh:mm:ss.S format, and we return a not-modified value otherwise.

How to Trim the first two characters of a column in csv using groovy

<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy"/>
<groovy>
newFile("C://RxBen//exports//Control_Exception__c_Exportupdated.csv").withWriter {
new File("C://RxBen//exports//Control_Exception__c_Export.csv").splitEachLine(",(?=(?:[^\"]*\"[^\"]*\")*[^\"]*\$)") { ID, Don_t_Work__c,Forwarding_fax_number__c, No_Go__c ->
it.println "${ID},${Forwarding_fax_number__c}AAA,${s}"
}
}
</groovy>
You can use a substring on the String in the column with the argument of 2, this will take all the characters from third character to the end of the string in the target String.
Example:
def s = "AATestString"
def newString = s.substring(2)
assert newString == "TestString"
Updated:
Try with this code: which Ozsaffer approached ...
#Grab('com.xlson.groovycsv:groovycsv:1.1')
import static com.xlson.groovycsv.CsvParser.parseCsv
df = new FileReader('filename.csv')
def data = parseCsv(df, readFirstLine: false)
for (def row : data){
println row.values[0].substring(2) //row.values[0] means first column
}

Resources