Creating a Groovy Class
Version 20.1 by Vincent Massol on 2012/03/29
This tutorial illustrates the XWiki.parseGroovyFromPage API method. This method allow you to instantiate a groovy class from both velocity and groovy code.
Create a groovy class
- Create a new page, for example Groovy.HelloWorldClass containing :/* Groovy Class #* */
class groovyClass {
def xwiki;
def context;
void setObjects(xwiki, context) {
setXWiki(xwiki);
setContext(context);
}
void setXWiki(xwiki) {
this.xwiki = xwiki;
}
void setContext(context) {
this.context = context;
}
String helloWorld() {
return "Hello World";
}
}
/* *# */
Notice the trick of putting a Velocity comment in the Groovy comment so that the code is not parsed by Velocity.
Instantiate and use your class from velocity
- Create a new page, for example "Main.HelloWorldFromVelocity" containing :#set($groovyObject = $xwiki.parseGroovyFromPage("Groovy.HelloWorldClass"))
$groovyObject.setObjects($xwiki, $context)
$groovyObject.helloWorld()
- See the result, feeling groovy ?
Instantiate and use your class from groovy
- Create a new page, for example "Groovy.HelloWorldClass" containing :{{groovy}}
groovyObject = xwiki.parseGroovyFromPage("Groovy.HelloWorldClass")
groovyObject.setObjects(xwiki, context)
print(groovyObject.helloWorld())
{{/groovy}}
- See the result, feeling groovy ?
More documentation
Do search around for Groovy language, it's pretty rich.
A cute feature is, for example, how it can access XML
Many tools are equipped to edit Groovy, among others IntelliJ IDEA and Eclipse. For both Velocity and Groovy, IntelliJ IDEA can be enriched with the type of predefined variables thanks to intentions or dynamic properties (e.g. xwiki, doc, context).