Warning: Work in progress, only a snippet for the moment

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 ("<%%>")

/* 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 ? ;)

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

<%

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

%>

  • See the result, feeling groovy ? ;)
Version 2.1 last modified by VincentMassol on 10/12/2007 at 15:56

Comments 2

cardenizen | 19.06.2007 at 05:37 PM
The velocity snippet works: $groovyObject.setObjects($xwiki, $context) $groovyObject.helloWorld()

but the groovy snippet does not.


DengXun | 19.09.2007 at 02:45 AM
How to add programming rights?

Attachments 0

No attachments for this document

Creator: jvdrean on 2007/02/15 21:50
This wiki is licensed under a Creative Commons license
1.4.1.10194