GroovyClassHelloWorldTutorial

Version 3.1 by JeromeVelociter on 2009/03/21

Work in progress, only a snippet for the moment

.code {
 width: auto;
}

Creating a Groovy Class

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 :

This page must have been saved by a user with programming rights to be executed When creating a page to access via "parseGroovyFromString", make sure you do not have opening and closing groovy identifiers ("<%%>")

/{pre}*{/pre} {pre}Groovy Class{/pre} {pre}#{/pre}* {pre}*{/pre}/

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";
  }
}

{pre}/{/pre}* *{pre}#{/pre} {pre}*{/pre}/

Notice the trick of putting a Velocity comment in the Groovy comment so that the code is not parsed by Velocity. Notice the ";" - this identifies a new instruction line, and although not mandatory, avoids potential problems if linefeeds are lost. As you can see, we can get and store the xwiki and context objects in the class to be able to use them; Their use is not illustrated in this tutorial.

Instantiate and use your class from velocity

  • Create a new page, for example "Main.HelloWorldFromVelocity" containing :
{pre}#{/pre}set($groovyObject = {pre}${/pre}xwiki.parseGroovyFromPage("Groovy.HelloWorldClass"))
$groovyObject.setObjects($xwiki, $context)
$groovyObject.helloWorld()
  • See the result, feeling groovy ? emoticon_wink

Instantiate and use your class from groovy

  • Create a new page, for example "Groovy.HelloWorldClass" containing :

This page must have been saved by a user with programming rights to be executed

{pre}<{/pre}%

groovyObject = xwiki.parseGroovyFromPage("Dev.HelloWorldGroovyClass")
groovyObject.setObjects(xwiki, context)
print(groovyObject.helloWorld())

%{pre}>{/pre}
  • See the result, feeling groovy ? emoticon_wink

Get Connected