Work in progress, only a snippet for the moment

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 tags (don't put {
    {groovy}} and
    {{/groovy}} on the page)

    /* 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. 

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 :
    #set($groovyObject = $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 

    {{groovy}}
    groovyObject = xwiki.parseGroovyFromPage("Groovy.HelloWorldClass")
    groovyObject.setObjects(xwiki, context)
    print(groovyObject.helloWorld())
    {{/groovy}}
  • See the result, feeling groovy ? emoticon_wink

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).

Tags:
   

Get Connected