Lugaru
Lugaru

Reputation: 1460

Groovy sandbox and Java: execute Groovy script

Task: execute groovy script with Groovy sandbox:

Groovy Script to execute:

query.reverse(); // QUERY is a some string that should be reversed

File "GroovyScriptSandbox.groovy" should get two parameters(script and values for this script):

package test.my.groovy.sandbox

import org.codehaus.groovy.control.CompilerConfiguration
import org.codehaus.groovy.control.customizers.ImportCustomizer
import org.codehaus.groovy.control.customizers.SecureASTCustomizer
import org.springframework.stereotype.Component


@Component
class GroovyScriptSandbox {

def config
def shell


    public String runScript(final String script, final String query) {
        final ImportCustomizer imports = new ImportCustomizer()
                                                .addStarImports('groovyx.net.http')
                                                .addStaticStars('groovyx.net.http.ContentType', 'groovyx.net.http.Method')
        config = new CompilerConfiguration()
        config.addCompilationCustomizers(imports)
        def newScript = "{ query -> " + script + "}"

        shell = new GroovyShell(config)
        def clos = shell.evaluate(newScript)
        return clos.call(query)
    }
}

Java method that executes "GroovyScriptSandbox.groovy":

@Resource
private GroovyScriptSandbox groovyScriptSandbox;

@RequestMapping(value = "/run", method = RequestMethod.POST)
@ResponseBody
public String runScript(@RequestParam("script") final String script, 
                       @RequestParam("query") final String query) {
    return groovyScriptSandbox.runScript(script, query);
}

In that case all works fine:

Question: I'm trying to replace "GroovyScriptSandbox.groovy" file with "GroovyScriptSandbox.java" and I don't know how to write the same groovy code in Java.

Upvotes: 3

Views: 3546

Answers (1)

Lugaru
Lugaru

Reputation: 1460

Finally found solution:

public String scriptRunner(final String script, final String query) {
    final ImportCustomizer imports = new ImportCustomizer();
    imports.addStaticStars("java.lang.Math");
    imports.addStarImports("groovyx.net.http");
    imports.addStaticStars("groovyx.net.http.ContentType", "groovyx.net.http.Method");

    final SecureASTCustomizer secure = new SecureASTCustomizer();
    secure.setClosuresAllowed(true);

    final CompilerConfiguration config = new CompilerConfiguration();
    config.addCompilationCustomizers(imports, secure); 

    final Binding intBinding = new Binding(); // alow parameters in the script
    intBinding.setVariable("query", query);

    final GroovyShell shell = new GroovyShell(intBinding, config); // create shall

    // code execution
    final Object clos = shell.evaluate(script);  

    if (clos == null) {
        return "No result avalible!";
    }
    return clos.toString();
}

Upvotes: 2

Related Questions