KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > kohsuke > stapler > jelly > groovy > GroovyScript


1 package org.kohsuke.stapler.jelly.groovy;
2
3 import groovy.lang.Closure;
4 import org.apache.commons.jelly.JellyContext;
5 import org.apache.commons.jelly.JellyTagException;
6 import org.apache.commons.jelly.Script;
7 import org.apache.commons.jelly.XMLOutput;
8 import org.codehaus.groovy.runtime.InvokerHelper;
9
10 /**
11  * Wraps a Groovy-driven Jelly script into {@link Script}
12  * (so that it can be called from other Jelly scripts.)
13  *
14  * @author Kohsuke Kawaguchi
15  */

16 public class GroovyScript implements Script {
17     /**
18      * Compiled Groovy class.
19      */

20     private final Class JavaDoc clazz;
21
22     public GroovyScript(Class JavaDoc clazz) {
23         this.clazz = clazz;
24     }
25     
26     public Script compile() {
27         return this;
28     }
29
30     public void run(JellyContext context, XMLOutput output) throws JellyTagException {
31         final JellyBuilder builder = new JellyBuilder(context, output);
32
33         // there seems to be no way to run a script with the delegate set,
34
// Groovy script needs to put the entire code into the "jelly {...}" block
35
// to run the code inside JellyBuilder.
36

37         JellyBinding binding = new JellyBinding(context,output);
38         binding.setProperty("jelly",new Closure(builder) {
39             public Object JavaDoc call(Object JavaDoc[] args) {
40                 Closure closure = (Closure) args[0];
41                 closure.setDelegate(builder);
42                 return closure.call();
43             }
44         });
45
46         InvokerHelper.createScript(clazz,binding).run();
47     }
48 }
49
Popular Tags