Create
Learn
Share

Groovy 3

rename
Updated 2006-10-28 00:38

Ant

Question Answer
<groovy>
println "hi"
</groovy>
run groovy code from ant
<groovyc destdir="classes"
srcdir="src"
listfiles="true" />
compile groovy code from ant
new AntBuilder().echo( "hi" )run ant echo (from groovy)
new AntBuilder().delete() { fileset( dir:".",
  includes:"**/*.abc" ) }
run ant delete (from groovy)
new AntBuilder().scp( file:"foo.txt",
  todir:"user:pass@server.com:.", trust:"true" )
run ant scp (from groovy)
memorize

Closures

Question Answer
c = { println "foo ${it}" }create a closure
c = { a, b -> println "foo ${a} ${b}" }create a closure (with 2 args)
c( "hey" )
c.call( "hey" )
call a closure
l.collect( { ... } )apply closure to list
m.each( { key, value ->
  println key + "=" + value } )
apply closure to map elements
"abc".replaceAll( "b", { ... } )Search and replace (using a closure)
"a aa".eachMatch( /a+/, {
  println "foo ${it[0]}" } )
processing multiple matches (using closure)
memorize

Misc advanced

Question Answer
sql = groovy.sql.Sql.newInstance(
  "jdbc:axiondb:foo", "", "",
  "org.axiondb.jdbc.AxionDriver" )
get db connection (works for all any jdbc driver)
sql.execute("insert into t values ('a')")insert db record
sql.eachRow("select * from t") { println "row ${it[0]}" }execute db select
new org.codehaus.groovy.scriptom.ActiveXProxy(
  "Shell.Application" ).MinimizeAll()
minimize all windows
new org.codehaus.groovy.scriptom.ActiveXProxy(
  "WScript.Shell" ).popup( "Groovy popup!!" )
popup dialog
http://groovy.codehaus.org/COM+Scriptingpage showing install instructions
memorize

More misc advanced

Question Answer
println "pwd".execute().textrun shell command
xml = new XmlSlurper().parseText(text)parse xml
xml.elementA.elementB.text()get element text from xml
for( e in xml.depthFirst() ) { ... }traverse xml deapth-first
groovy -l 1960 -e "println line.reverse()"listen on a port and run code on every line
memorize

See also

http://groovy.codehaus.org/Quick+Start

Recent badges