If I am using Groovy String Template:
http://docs.groovy-lang.org/latest/html/documentation/template-engines.html#markuptemplate-gotchas
I have a variable $name1,name2 and I want to says something like:
${name1? name1:''} ${name2? 'name2 was here, too': ''}
Is there a cleaner way to write expression like this.
Given I don't know if $name1, $name2 is null or not. If they are, printing empty or not printing anything is fine. I just don't want 'null' as the text.
There is such thing as an Elvis operator:
def foo = bar?:baz
Which is equal to calling:
def foo = bar ? bar : baz
In your case, you can use it like this:
${name1?:''}
${name1 ?: ''} ${name2 ? 'name2 was here, too' : ''}
Related
I have string that looks like this : 'Foo dooo kupa trooo bar'.
I know the start and end point of word kupa and I need to wrap it with this : <span> </span>.
After this operation i want my string to like like this : Foo dooo <span>kupa</span> trooo bar
I cannot find any good built-in methods that can help so any help would be nice.
basically there are two options:
import re
strg = 'Foo dooo kupa trooo bar'
match = re.search('kupa', strg)
print('{}<span>{}</span>{}'.format(strg[:match.start()], strg[match.start():match.end()], strg[match.end():]))
or (the first expressioin would be a regex, if the pattern were a little more complicated):
print(re.sub('kupa', '<span>kupa</span>', strg))
The output string and the input string are the same.....
Anyway I think you want to replace part of your string, so have a look at this answers:
https://stackoverflow.com/a/10037749/4827890
https://stackoverflow.com/a/12723785/4827890
I'm struggling to find examples of findAll with groovy. I've got a very
simple code snippet that gets the property of a node and outputs it's
value. Except I'm only getting the last value when I'm looping through
a series of properties. Is there something I'm doing wrong here, this
seems really simple.
JcrUtils.getChildNodes("footer").findAll{
selectFooterLabel = it.hasProperty("footerLabel") ? it.getProperty("footerLabel").getString() : ""
}
In my jsp I'm just printing the property:
<%=selectFooterLabel%>
Thanks for the help!
findAll returns a List containing all the items in the original list for which the closure returns a Groovy-true value (boolean true, non-empty string/map/collection, non-null anything else). It looks like you probably wanted collect
def footerLabels = JcrUtils.getChildNodes("footer").collect{
it.hasProperty("footerLabel") ? it.getProperty("footerLabel").getString() : ""
}
which will give you a List of the values returned by the closure. If you then want only the subset of those that are not empty you can use findAll() with no closure parameter, which gives you the subset of values from the list that are themselves Groovy-true
def footerLabels = JcrUtils.getChildNodes("footer").collect{
it.hasProperty("footerLabel") ? it.getProperty("footerLabel").getString() : ""
}.findAll()
I have an interesting problem in Groovy. Hope someone can help me.
Basically I am using Groovy Sql. I need to select multiple tables in different databases. My second query depends on other query's, for example: "select * from table1-in-db1 where key = ${result-of-other-query1}. Groovy works fine if I hardcode this in the function. However, my problem is the sql is defined in a xml file and after I retriev passed in into the the funciton as a string. it doesn't interperate the inline varialbe anymore, even I do have a variable called result-of-other-query1 in the scope.
Here is a piece of sudo code:
doQuery(String squery, String tquery) {
//query db1.
//squery = "select key1 from table1"
db1.rows(squery).each {row->
//query db2.
//tquery ="select * where myKey ='${row.key1}'"
println tquery
tdb.rows(tquery).each { row1 ->
.... // get error here, coz groovy did not replace ${row.key1}
}
}
}
Is there any way that I can tell Groovy to replace the inline variable even it is a passed in as a string?
Thanks a lot for your help in advance
Try
tquery = 'select * where myKey =:foo'
tdb.rows(tquery,[foo:"$row.key1"]).each
you may also want to consider using eachRow as opposed to rows.(query).each
I think what you need is the simple template engine. Sorry I am on my phone so can't give you an example. ..
OK - here is an example of what I mean. I was talking about the SimpleTemplateEngine (http://groovy.codehaus.org/api/groovy/text/SimpleTemplateEngine.html).
If you load a string from a file it will not be a gstring, it will be a String, but you can use the SimpleTemplateEngine to do a GString type substitution e.g.:
def clause='test'
String testString='this is a ${clause}'
println "As a string: " + testString
// Get an instance of the template engine
def engine = new groovy.text.SimpleTemplateEngine()
def template = engine.createTemplate(testString).make([clause:clause])
println template.toString()
I'm fairly new to groovy, looking at some existing code, and I see this:
def timestamp = event.timestamp[]
I don't understand what the empty square brackets are doing on this line. Note that the timestamp being def'd here should receive a long value.
In this code, event is defined somewhere else in our huge code base, so I'm not sure what it is. I thought it was a map, but when I wrote some separate test code using this notation on a map, the square brackets result in an empty value being assigned to timestamp. In the code above, however, the brackets are necessary to get correct (non-null) values.
Some quick Googling didn't help much (hard to search on "[]").
EDIT: Turns out event and event.timestamp are both zero.core.groovysupport.GCAccessor objects, and as the answer below says, the [] must be calling getAt() on these objects and returning a value (in this case, a long).
The square brackets will invoke the underlying getAt(Object) method of that object, so that line is probably invoking that one.
I made a small script:
class A {
def getAt(p) {
println "getAt: $p"
p
}
}
def a = new A()
b = a[]
println b.getClass()
And it returned the value passed as a parameter. In this case, an ArrayList. Maybe that timestamp object has some metaprogramming on it. What does def timestamp contains after running the code?
Also check your groovy version.
Empty list, found this. Somewhat related/possibly helpful question here.
Not at a computer, but that looks like it's calling the method event.timestamp and passing an empty list as a parameter.
The same as:
def timestamp = event.timestamp( [] )
The example on this page only shows Groovy assertions without parentheses.
assert a != null, 'First parameter must not be null'
What would this look like if I wanted to include the parentheses? I presume that this is the closest equivalent to Perl's die() function (print error message and exit in one statement)?
The answer is:
assert(a != null), "First parameter must not be null"