Groovy convert sql.eachRow results to List - groovy

def List_Sftp = sql.eachRow(SftpQuery){ row ->
if(row[4]=="SFTP") {
def names= row.collect{ "${row[0]},${row[1]} ${row[3]} ,${row[4]},${row[5]},${row[6]},${row[7]}" }
println names
}
if(row[4]=="ROSETTANET"){
def names= row.collect{ "${row[0]},${row[1]},${row[2]},${row[4]},${row[5]},${row[6]},${row[7]}" }
println names
}
}
Output above code is
[2.01.00,SAMSUNG,123,XYZ,7C7,file1.xml,zzzz]
[2.01.00,SAMSUNG,123,XYZ,7C7,file2.xml,yyyy]
I can't iterate this out as a list. Suggest how to convert this output to
[2.01.00,SAMSUNG,123,XYZ,7C7,file1.xml,zzzz,2.01.00,SAMSUNG,123,XYZ,7C7,file2.xml,yyyy]

def all = []
sql.eachRow(SftpQuery){ row ->
all.addAll row
}
println all
In all you will have all results in a single iterateble list

Related

Groovy: Get index of all occurences of sublist from arraylist

I am new to groovy and trying to find the indexes of all sublists in a list.
I am trying to use something like Collections.indexOfSubList like in java but it gives exception saying it applies on Lists and not ArrayLists.
So I am trying to define my own function. I am finding all the indices of all the elements in the smaller list existing in the longer list and then subtracting the indices of the result array. If it comes to 1 then I am considering that index to a sublist.
I know that I have the logic a little twisted. Can somebody guide with a better and efficient way of doing this.
Below is my code:
List list1 = [1,2,3,4,5,6,1,2,3]
List list2 = [1,2]
index1 = list1.findIndexValues {
it == list2[0];
}
index2 = list1.findIndexValues {
it == list2[1];
}
println index1
println index2
result = []
for (int i = 0; i < index1.size(); i++) {
result.add(index2[i]-index1[i]);
}
println result
Edit: no longer uses Collections due to new issue re: Elastic Search.
The following code traverses along the source list, creating a sublist. It checks the sublist to see if it starts with the target list. See the asserts below (e.g. the indexes are 0-based):
def listStartsWithSubList = { source, target ->
def result = false
if (source.size() >= target.size()) {
result = true
target.eachWithIndex { item, index ->
result = result && (item == source[index])
}
}
result
}
def indexOfSubLists = { source, target ->
def results = []
source.eachWithIndex { item, index ->
def tmpList = source[index..source.size()-1]
if (listStartsWithSubList(tmpList, target)) {
results << index
}
}
results
}
assert [1] == indexOfSubLists([1,2,3], [2,3])
assert [2] == indexOfSubLists([1,2,3], [3])
assert [] == indexOfSubLists([1,2,3], [4])
assert [0,6] == indexOfSubLists([1,2,3,4,5,6,1,2,3], [1,2])

storing standard output into list groovy

I cannot manage to store the standard output from a shell command into a list using the following code. It seems to store each character as a list element instead of the entire string produced on each line.
def implementedBranchName = []
def getImplementedBranches() {
def cmd = "/usr/bin/tool search status Pending"
Process process = cmd.execute()
def output= process .in.text;
implementedBranchName = output.each{ println it }
def size = implementedBranchName.size()
for ( int i = 0; i < size; i++) {
println(implementedBranchName[i])
}
}
Current Output:
F
O
O
B
A
R
Desired Output:
FOO
BAR
You could just change
implementedBranchName = output.each{ println it }
To:
implementedBranchName = output.split()
There is also "eachLine" in Groovy.
def getImplementedBranches() {
def cmd = "/usr/bin/tool search status Pending"
Process process = cmd.execute()
process.in.eachLine { line ->
println(line)
}
}

How to change variables with in a string into a Map

I have let's say 100 variables in a string , my requirement is to automatically create a Map out of the string:
String str = "$$test$$ $$test2$$ $$test$$ $$test3$$"
Expected Result:
["test":test, "test2":test2, "test3":test3];
EDIT (for dsharew)
This is the last version of my code
def list = queryText.findAll(/\$\$(.*?)\$\$/)
def map = [:]
list.each{
log.debug(it)
it = it.replace("\$\$", "")
log.debug(it)
map.putAt(it, it)
}
log.debug(list)
log.debug(map)
queryText = queryText.replaceAll(/\$\$(.*?)\$\$/) { k -> map[k[1]] ?: k[0] }
log.debug(queryText)
And the logs print the following result:
$$test$$
test
$$test2$$
test2
$$test$$
test
$$test3$$
test3
[$$test$$, $$test2$$, $$test$$, $$test3$$]
{test=test, test2=test2, test3=test3}
test test2 test test3
This should do what you want:
def queryText = "\$\$test\$\$ \$\$test2\$\$ \$\$test\$\$ \$\$test3\$\$"
toMap(queryText.findAll(/\$\$(.*?)\$\$/));
def toMap(list){
def map = [:]
list.each{
it = it.replace("\$\$", "")
map.putAt(it, it)
};
println map;
return map;
}
Following #dsharew answer, I've reduced it a little bit more:
​def queryText = "\$\$test\$\$ \$\$test2\$\$ \$\$test\$\$ \$\$test3\$\$"
def resultMap = queryText
.findAll(/\$\$(.*?)\$\$/)
.collectEntries { String next ->
[next.replace("\$\$", "")] * 2
}
collectEntries can be used to return a map from a collection if it returns a map or a tuple for every entry in the collection.
If you multiply a list by n, you are creating a bigger list with n times its content
BTW cool problem!
This is what I came up with
String str = '$$test$$ $$test2$$ $$test$$ $$test3$$'
str.replaceAll('\\$\\$', '').split(' ').collectEntries { [(it):it] }

groovy map operation not giving expected value

I am trying to find duplicate tags in an xml file. and i wrote the following:
def xml = new XmlSlurper(false,false).parse('myfile.xml')
List<String> intNames = xml.depthFirst().findAll {
it.name() == 'InternalName'
}
println "Total:" + intNames.size()
// println "Unique:" + intNames.unique().size()
def map = [:]
for(itm in intNames){
if(map.get(itm) == null)
map.put(itm, 1)
else{
def val = map.get(itm)
map.put(itm, val + 1)
println itm
}
}
println "map size: ${map.size()}"
The result shows as:
Total:13811
map size: 13811
if i uncomment the line
// println "Unique:" + intNames.unique().size()
then it looks like
Total:13811
Unique:13792
map size: 13792
So, if unique has less number of values then why else clause is not able to print anything?

Create comma separated string from 2 lists the groovy way

What I have so far is:
def imageColumns = ["products_image", "procuts_subimage1", "products_subimage2", "prodcuts_subimage3", "products_subimage4"]
def imageValues = ["1.jpg","2.jpg","3.jpg"]
def imageColumnsValues = []
// only care for columns with values
imageValues.eachWithIndex { image,i ->
imageColumnsValues << "${imageColumns[i]} = '${image}'"
}
println imageColumnValuePair.join(", ")
It works but I think it could be better. Wish there was a collectWithIndex ... Any suggestions?
There's no collectWithIndex, but you can achieve the same result with a little effort:
def imageColumns = ["products_image", "procuts_subimage1", "products_subimage2", "prodcuts_subimage3", "products_subimage4"]
def imageValues = ["1.jpg","2.jpg","3.jpg"]
def imageColumnsValues = [imageValues, 0..<imageValues.size()].transpose().collect { image, i ->
"${imageColumns[i]} = '${image}'"
}
println imageColumnsValues.join(", ")
This takes the list of items and a range of numbers from 0 size(list) - 1, and zips them together with transpose. Then you can just collect over that result.

Resources