Groovy: Get a specific value in a file - groovy

I'm quite new in Groovy.
Basically I load a text file, then I need to get a specific value at one line (actually the 6th).
The line is like:
STATIC_ASSERT(VERSION == 888888, "blablabla");
I need to get the 888888 value.
I found a way using multiple split but it's ugly.
I also think of using something like:
line.substring(ind+"VERSION ==".length(), line.length()-10).trim();
But the "blablabla" length can change..
Thank you.
Edit: It works using an hardcoded string like this.
But when I try to run it from the file I get this error:
test' is failed: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
script1516208488151762512206.groovy: 4: expecting '}', found '' # line 4, column 69.
ne.contains('VERSION ==')
^
1 error
Here is my code:
${groovy:
String Ver
def file = new File("C:\\test.cpp")
def data = file.filterLine { line ->
line.contains('VERSION ==')
}
Ver = data.split("==")[1].split(",")[0].trim()
logger.info(Ver)
}
--
I also tried something like this:
${groovy:
String Ver
def file = new File("C:\\test.cpp")
while ((line = file.readLine())!=null)
{
int ind = line.indexOf("VERSION ==")
if (ind >= 0)
{
Ver = line.split("==")[1].split(",")[0].trim()
}
}
logger.info(Ver)
}
But I get same kind of weird error:
expecting '}', found '' # line 9, column 58.
("==")[1].split(",")[0].trim()
^
1 error
:(

You do as shown below:
def line = 'STATIC_ASSERT(VERSION == 888888, "blablabla");'
println line.split('==')[1].split(',')[0].trim()

Related

jmeter - how to creat new csv from original csv with groovy

I have a csv file (UTF-8 with BOM) like this
NAME,F1,F2,
test1,field1,field2
test2,field1,field2
test3,field1,field2
test4,field1,field2
test5,field1,field2
test6,field1,field2
I would like to discard the first three lines and create new csv (UTF-8 with BOM)
NAME,F1,F2,
test4,field1,field2
test5,field1,field2
test6,field1,field2
I get some idea from the page and code this in JSR223 PreProcessor
def originalCsvFile = new File('g:/Workspace/1.csv')
def newCsvFile = new File('g:/Workspace/2.csv')
originalCsvFile.readLines().take(5).each {line ->
newCsvFile.withWriter('UTF-8') { writer ->
writer.writeLine line
}
}
The above code does not work.
It is better to put the new csv path to the variable, I want to get the variable in jmeter CSV Data Set Config
Do you realize that:
take(5) function returns 5 first lines of the list
newCsvFile.withWriter function overwrites the file with the new data each time it's being called
So I believe you're looking for copying and pasting something like this:
originalCsvFile.readLines().eachWithIndex { line, index ->
if (index == 0 || index > 3) {
newCsvFile.withWriterAppend('UTF-8') { writer ->
writer.writeLine line
}
}
}
More information on Groovy scripting in JMeter: Apache Groovy - Why and How You Should Use It
Not as elegant, perhaps, but this is how I would do it:
List li = originalCsvFile.readLines()
newCsvFile.append(li[0] + "\n", 'UTF-8') //headers
li[4..-1].each { newCsvFile.append(it + "\n", 'UTF-8') }

md5(str.encode(var1)).hexdigest() giving hex value as 382fbe213f159eecf85facb256f265d0 - how to know the var1?

While running the test case, my code is failing as the expected value in hex is different then my answer.
for example, my ws_std value is 13.06 i.e. var1
md5(str.encode(var1)).hexdigest() giving hex value as 382fbe213f159eecf85facb256f265d0
But I am not sure if it matches with the hex value.
Getting error in below code :-
variables = ["ws_std", "p_range", "corr", "dew_month", "max_gust_month", "max_gust_value", "avg_temp", "temp_range", "max_p_range_day", "num_days_std", "median_b_days"]
answers = [ws_std, p_range, corr, dew_month, max_gust_month, max_gust_value, avg_temp, temp_range, max_p_range_day, num_days_std, median_b_days]
answer_dict = dict()
for var, ans in zip(variables, answers):
answer_dict[var] = md5(str.encode(ans)).hexdigest()
with open('test_files/hash.pk', 'rb') as file:
hash_dict = pickle.load(file)
def test_ws_std():
assert hash_dict["ws_std"] == answer_dict["ws_std"]
Error Code:-
========================================================== FAILURES ==========================================================
________________________________________________________ test_ws_std _________________________________________________________
def test_ws_std():
> assert hash_dict["ws_std"] == answer_dict["ws_std"]
E AssertionError: assert 'c8cc550afa85...2c6946c238f36' == '382fbe213f159...facb256f265d0'
E - c8cc550afa85496c4ee2c6946c238f36
E + 382fbe213f159eecf85facb256f265d0
test.py:40: AssertionError
see comments below .
output required : ws_std

Groovy File Traverse behavior when parsing file

I have a closure working properly on traverse, but another of the same kind is failing. I'm suspecting scope or timing is causing this to fail. The working code sums the size of files in the file system. The code not working is inspecting the content of the file and only prints one match. Running these with Grails 2.3.7
working code:
def groovySrcDir = new File('.', 'plugins/')
def countSmallFiles = 0
def postDirVisitor = {
if (countSmallFiles > 0) {
println "Found $countSmallFiles files with small filenames in ${it.name}"
}
countSmallFiles = 0
}
groovySrcDir.traverse(type: FILES, postDir: postDirVisitor, nameFilter: ~/.*\.groovy$/) {
if (it.name.size() < 15) {
countSmallFiles++
}
}
problem code:
def datamap = [:]
def printDomainFound = {
//File currentFile = new File(it.canonicalPath)
def fileText = it.text
if(fileText.indexOf("#Table ") > 0){
//println "Found a Table annotation in ${it.name} "
datamap.put(it.name, it.name)
}
}
groovySrcDir.traverse type: FILES, visit: printDomainFound, nameFilter: filterGroovyFiles
datamap.each {
println it.key
}
I tested your code and worked fine.
Which behaviour are you expecting?
I find a couple of suspicious things:
If fileText begins with "#Table " then indexOf will return 0 and the condition if(fileText.indexOf("#Table ") > 0) will not be satisfied.
"#Table " has a trailing space, then a file containing, for example: "#Table(", will not be printed.
You can also check that filterGroovyFiles has the appropiate value.
I hope it'll help.
-- EDIT --
Running the code with def filterGroovyFiles = ~/.*\.groovy$/ and this file tree:
plugins
|--sub1
| |-dum.groovy
| |-dum2.groovy
dum3.groovy
And all three groovy files containing the (but not starting with!!) "#Table " (with trailing space!!). I get the expected output:
dum3.groovy
dum.groovy
dum2.groovy
(Note both dum.groovy and dum2.groovy from the same folder sub1 are appearing).
I'm using groovy 2.0.5.
Please recheck your files :
Have the correct extension
Contain but not at the begining (index==0) the String "#Table "

Why can't I directly assign to object properties using multiple return values from a method?

Based on this question I've coded the following which throws a compilation time error:
Here is the code:
43. Currency currency = new Currency()
44. (currency.rate_one, currency.time_one) = getDateAndRate()
My method with two return values:
def getDateAndRate(){
Date date = new Date()
double rate = getRate();
return [rate, date]
}
Error thrown
expecting '}', found ',' # line 44, column 26.
(currency.rate_one, currency.time_one) = getDateAndRate()
^
Try this instead
def (rate, time) = getDateAndRate()
currency.rate_one = rate
currency.time_one = time
There is a trick I learned only recently myself and that is to combine multiple assignment and with:
with (currency) {
(rate_one, time_one) = getDateAndTime()
}

how to fix expecting anything but ''\n''; got it anyway

I have the following line in my code
def genList = (args[]?.size() >=4)?args[3]: "
when I run my whole code I get the following error
expecting anything but ''\n''; got it anyway at line: 9, column: 113
here I am adding the whole code so you can see what I am doing
def copyAndReplaceText(source, dest, targetText, replaceText){
dest.write(source.text.replaceAll(targetText, replaceText))
}
def dire = new File(args[0])
def genList = (args[]?.size() >=4)?args[3]: " // check here if argument 4 is provided, and generate output if so
def outputList = ""
dire.eachFile {
if (it.isFile()) {
println it.canonicalPath
// TODO 1: copy source file to *.bak file
copy = { File src,File dest->
def input = src.newDataInputStream()
def output = dest.newDataOutputStream()
output << input
input.close()
output.close()
}
//File srcFile = new File(args[0])
//File destFile = new File(args[1])
//File srcFile = new File('/geretd/resume.txt')
//File destFile = new File('/geretd/resumebak.txt')
File srcFile = it
File destFile = newFile(srcFile + '~')
copy(srcFile,destFile)
// search and replace to temporary file named xxxx~, old text with new text. TODO 2: modify copyAndReplaceText to take 4 parameters.
if( copyAndReplaceText(it, it+"~", args[1], args[2]) ) {
// TODO 3: remove old file (it)
it.delete()
// TODO 4: rename temporary file (it+"~") to (it)
// If file was modified and parameter 4 was provided, add modified file name (it) to list
if (genList != null) {
// add modified name to list
outputList += it + "\n\r"
}
}
}
}
// TODO 5: if outputList is not empty (""), generate to required file (args[3])
if (outputList != ""){
def outPut = new File(genList)
outPut.write(outputList)
}
Thank you
Just close your double quotes
def genList = (args?.size() >=4)?args[3]: ""
The specific OP question was already answered, but for those who came across similar error messages in Groovy, like:
expecting anything but '\n'; got it anyway
expecting '"', found '\n'
It could be caused due to multi-line GString ${content} in the script, which should be quoted with triple quotes (single or double):
''' ${content} ''' or """ ${content} """
Why do you have a single " at the end of this line: def genList = (args[]?.size() >=4)?args[3]: "?
You need to make it: def genList = (args[]?.size() >=4)?args[3]: ""
You need to add a ; token at the end of def outputList = ""
Also get rid of the " at the end of def genList = (args[]?.size() >=4)?args[3]: "

Resources