groovy saving lines from file into collection - groovy

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

Related

groovy input into file iterate over map

Hi I got the map and loop iterate over the map.
def map = [file.txt : file2.txt,
file3.txt : fil4.txt,
file5.txt : file6.txt]
map.each { k,v ->
collection = new file("k").readLines()
collection2 = new file("v").readLines.findResult()
def commons = collection.intersect(collection2)
}
I want every "commons" collection save into a file, not overwriting this file over the next iterations.
Is there a possibility to do such a thing in the loop?
Suppose you already have your list of files to merge, then the only thing you need to do is to write the lines of each file into the output file, you can do something like this:
def files = ['file1.txt', 'file3.txt', 'file2.txt']
def file = new File('output.txt')
def outputFile = file.newPrintWriter()
def mergeFile = { fileName ->
File sourceFile = new File(fileName)
sourceFile.eachLine{ line ->
outputFile.println(line)
}
}
files.each(mergeFile)
out.close()
This will merge the contents of all your files, there is another thing, you may need to specify the folder of the files, so I suggest to use the constructor that receives the folder.
File output = new File(folder, filename)

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 append comma separated value dynamically in 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

How to Read the csv file data one by one and put into variable Using Groovy

Here i am facing One problem that. i want to read the csv file data and one by one put it into a variable and that variable i want to assign a next Http Request let say ids.csv file which consisting of values like this
23333
23334
23335
22336
23336
I am using Jsr223 PreProcessor code:
def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.each { String line ->
vars.put('Id_value', line.toString())
}
If it is wrong, how to do this with simple code?
You can emulate JMeter CSV data set which add variables with different suffixes, example in tutorial:
String Filename = vars.get("GETfile");
String fileContents = new File(Filename).getText('UTF-8');
def lines = 0 ;
fileContents.eachLine { line ->
lines++;
vars.put("CSVLine_" + lines, line);
}
vars.put("GETfileLength",lines.toString()) ;
and then loop the variables using ForEach Controller:
You need to add a some form of counter to your JMeter Variables reference names, your current code will create only one Id_value variable with the value of 23336, you need to amend it like:
def csvfile = new File('D:/datas/id/ids.csv')
def lines =csvfile.readLines()
lines.eachWithIndex {line, idx ->
vars.put('Id_value_' + idx, line)
}
And you will get:
Id_value_0=23333
Id_value_1=23334
Id_value_2=23335
Id_value_3=22336
Id_value_4=23336
More information:
Groovy Collection.eachWithIndex()
Groovy is the New Black

groovy replace data from file with space

i want to replace string from a file.
i have a line like this:
qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz
i want to replace all string starting from data to login with spaces
i try this i can only replace the string, is there a way to replace with a starting and endpoint for string?
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
def fileText = source.text
def filedest = dest.text
for ( index in 1..9 ) {
fileText = (fileText =~ /data/).replaceFirst("")
This code has an anchored version (to {) of the regex:
def fileText = '''\
qwe{data:"dede-dddd-ssss",login:"user",display:"screen1"},abc,xyz
...
qwe{data:"data2",login:"user2",display:"screen2"},abc,xyz
...
qwe{data:"data3",login:"user3",display:"screen3"},abc,xyz\
'''
fileText = fileText.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '')
println fileText
Output:
qwe{display:"screen1"},abc,xyz
...
qwe{display:"screen2"},abc,xyz
...
qwe{display:"screen3"},abc,xyz
Try also in the online groovy web console
UPDATE
If a understand correctly your request: this following code read the input text from source (c:\\sq\\file1.txt) and put the modified text into destination file dest (c:\\sq\\file2.txt):
def source = new File("c:\\sq\\file1.txt")
def dest = new File("c:\\sq\\file2.txt")
dest.write(source.text
.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '') )
If you want it in the files, then you can try below, and find the updated data in test2.txt:
note:please update the file paths as per your environment
Courtesy #GsusRecovery for regex
def fileContent = new File('/tmp/test.txt').text
def replacedContent = fileContent.replaceAll(/(?<=\{)\s*data:[^,]+,\s*login:[^,]+,/ , '')
def newFile = new File('/tmp/test2.txt')
newFile.write(replacedContent)
I'm not entirely clear on what your desired outcome is. If you want to remove the "data" and "login" fields and the corresponding values from the input strings, such that your example of:
qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz
becomes:
qwe{display:"screen"},abc,xyz then you can easily use a regex to do this.
The following code:
​String str = """qwe{data:"dede-dddd-ssss",login:"user",display:"screen"},abc,xyz"​​""
str = str.replaceFirst("​​​​​​​​​​​​​data.*login:\".+?\",", '')
println str​
Prints qwe{display:"screen"},abc,xyz

Resources