Groovy沙箱和Java:执行Groovy脚本

时间:2014-05-08 13:49:07

标签: java groovy sandbox

任务:使用Groovy沙箱执行groovy脚本:

要执行的Groovy脚本:

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

文件" GroovyScriptSandbox.groovy"应该获得两个参数(此脚本的脚本和值):

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

执行" GroovyScriptSandbox.groovy"的Java方法:

@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);
}

在这种情况下一切正常:

  • Java控制器获取脚本参数等于" query.reverse()"和查询参数等于" 0123"
  • Groovy文件执行脚本" query.reverse()"在沙箱中查询等于" 0123"
  • 结果等于" 3210"

问题: 我试图取代" GroovyScriptSandbox.groovy"文件包含" GroovyScriptSandbox.java"而且我不知道如何用Java编写相同的groovy代码。

1 个答案:

答案 0 :(得分:1)

终于找到了解决方案:

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();
}