目录

一、概述

二、pom文件

三、ScriptEngineManager

四、GroovyShell

五、GroovyClassLoader

六、GroovyScriptEngine

七、SecureASTCustomizer

八、SandboxTransformer

九、DSL(Json转换)


一、概述

Groovy is a multi-faceted language for the Java platform.

Apache Groovy是一种强大的、可选的类型化和动态语言,具有静态类型和静态编译功能,用于Java平台,目的在于通过简洁、熟悉和易于学习的语法提高开发人员的工作效率。它可以与任何Java程序顺利集成,并立即向您的应用程序提供强大的功能,包括脚本编写功能、特定于域的语言编写、运行时和编译时元编程以及函数式编程。

Groovy是基于java虚拟机的,执行文件可以是简单的脚本片段,也可以是一个完整的groovy class,对于java程序员来说,学习成本低,可以完全用java语法编写。下面总结下我的学习笔记,java整合Groovy的四种调用方式。

二、pom文件

添加groovy-all jar包,以及groovy-sanbox提供groovy安全的沙盒环境

<dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.4.16</version>
        </dependency>
        <dependency>
            <groupId>org.kohsuke</groupId>
            <artifactId>groovy-sandbox</artifactId>
            <version>1.7</version>
        </dependency>

三、ScriptEngineManager

groovy遵循JSR 223标准,可以使用jdk的标准接口ScriptEngineManager调用。

@Test
    public void testScriptEngine() throws ScriptException, NoSuchMethodException {
        ScriptEngineManager factory = new ScriptEngineManager();
        // 每次生成一个engine实例
        ScriptEngine engine = factory.getEngineByName("groovy");
        System.out.println(engine.toString());
        // javax.script.Bindings
        Bindings binding = engine.createBindings();
        binding.put("date", new Date());
        // 如果script文本来自文件,请首先获取文件内容
        engine.eval("def getTime(){return date.getTime();}", binding);
        engine.eval("def sayHello(name,age){return 'Hello,I am ' + name + ',age' + age;}");
        Long time = (Long) ((Invocable) engine).invokeFunction("getTime", null);
        System.out.println(time);
        String message = (String) ((Invocable) engine).invokeFunction("sayHello", "zhangsan", 12);
        System.out.println(message);
    }

四、GroovyShell

直接使用GroovyShell,执行groovy脚本片段,GroovyShell每一次执行时代码时会动态将代码编译成java class,然后生成java对象在java虚拟机上执行,所以如果使用GroovyShell会造成class太多,性能较差。

@Test
    public void testGroovyShell() {
        final String script = "Runtime.getRuntime().availableProcessors()";

        Binding intBinding = new Binding();
        GroovyShell shell = new GroovyShell(intBinding);

        final Object eval = shell.evaluate(script);
        System.out.println(eval);
    }

五、GroovyClassLoader

groovy官方提供GroovyClassLoader从文件,url或字符串中加载解析Groovy class

@Test
    public void testGroovyClassLoader() throws IllegalAccessException, InstantiationException {
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
        String hello = "package com.szwn.util\n" + "\n" + "class GroovyHello {\n" + "    String sayHello(String name) {\n"
                        + "        print 'GroovyHello call '\n" + "        name\n" + "    }\n" + "}";
        Class aClass = groovyClassLoader.parseClass(hello);
        GroovyObject object = (GroovyObject) aClass.newInstance();
        Object o = object.invokeMethod("sayHello", "zhangsan");
        System.out.println(o.toString());
    }

六、GroovyScriptEngine

GroovyScriptEngine可以从url(文件夹,远程协议地址,jar包)等位置动态加装resource(script或则Class),同时对
编译后的class字节码进行了缓存,当文件内容更新或者文件依赖的类更新时,会自动更新缓存。

@Test
    public void testGroovyScriptEngine() throws IOException, ResourceException, groovy.util.ScriptException {

        String url = "D:\\groovy\\util";
        GroovyScriptEngine engine = new GroovyScriptEngine(url);
        for (int i = 0; i < 5; i++) {
            Binding binding = new Binding();
            binding.setVariable("index", i);

            // 每一次执行获取缓存Class,创建新的Script对象
            Object run = engine.run("GroovyHello.groovy", binding);
            System.out.println(run);
        }
    }

GroovyHello.groovy代码如下

String sayHello(name) {
    print "GroovyHello to 中文"
    name
}

sayHello(name)

七、SecureASTCustomizer

Groovy会自动引入java.util,java.lang包,方便用户调用,但同时也增加了系统的风险。为了防止用户调用System.exit或Runtime等方法导致系统宕机,以及自定义的groovy片段代码执行死循环或调用资源超时等问题,Groovy提供了SecureASTCustomizer安全管理者和SandboxTransformer沙盒环境。

@Test
    public void testAST() {
        final String script = "import com.alibaba.fastjson.JSONObject;JSONObject object = new JSONObject()";

        // 创建SecureASTCustomizer
        final SecureASTCustomizer secure = new SecureASTCustomizer();
        // 禁止使用闭包
        secure.setClosuresAllowed(true);
        List<Integer> tokensBlacklist = new ArrayList<>();
        // 添加关键字黑名单 while和goto
        tokensBlacklist.add(Types.KEYWORD_WHILE);
        tokensBlacklist.add(Types.KEYWORD_GOTO);
        secure.setTokensBlacklist(tokensBlacklist);
        // 设置直接导入检查
        secure.setIndirectImportCheckEnabled(true);
        // 添加导入黑名单,用户不能导入JSONObject
        List<String> list = new ArrayList<>();
        list.add("com.alibaba.fastjson.JSONObject");
        secure.setImportsBlacklist(list);

        // statement 黑名单,不能使用while循环块
        List<Class<? extends Statement>> statementBlacklist = new ArrayList<>();
        statementBlacklist.add(WhileStatement.class);
        secure.setStatementsBlacklist(statementBlacklist);

        // 自定义CompilerConfiguration,设置AST
        final CompilerConfiguration config = new CompilerConfiguration();
        config.addCompilationCustomizers(secure);
        Binding intBinding = new Binding();
        GroovyShell shell = new GroovyShell(intBinding, config);

        final Object eval = shell.evaluate(script);
        System.out.println(eval);
    }

执行结果

java 集成spring java 集成 groovy_java 集成spring

八、SandboxTransformer

用户调用System.exit或调用Runtime的所有静态方法都会抛出SecurityException

@Test
    public void testGroovySandbox() {
        // 自定义配置
        CompilerConfiguration config = new CompilerConfiguration();

        // 添加线程中断拦截器,可拦截循环体(for,while)、方法和闭包的首指令
        config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt.class));

        // 添加线程中断拦截器,可中断超时线程,当前定义超时时间为3s
        Map<String, Object> timeoutArgs = ImmutableMap.of("value", 3);
        config.addCompilationCustomizers(new ASTTransformationCustomizer(timeoutArgs, TimedInterrupt.class));

        // 沙盒环境
        config.addCompilationCustomizers(new SandboxTransformer());
        GroovyShell sh = new GroovyShell(config);
        // 注册至当前线程
        new NoSystemExitSandbox().register();
        new NoRunTimeSandbox().register();

        // 确保在每次更新缓存Class<Script>对象时候,采用不同的groovyClassLoader
        // Script groovyScript = sh.parse("System.exit(1)");
        // Script groovyScript = sh.parse("Runtime.getRuntime().availableProcessors()");
        Script groovyScript = sh.parse("System.exit(1)");

        Object run = groovyScript.run();
        System.out.println(run);
    }

    class NoSystemExitSandbox extends GroovyInterceptor {
        @Override
        public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable {
            if (receiver == System.class && method.equals("exit")) {
                throw new SecurityException("No call on System.exit() please");
            }
            return super.onStaticCall(invoker, receiver, method, args);
        }
    }

    class NoRunTimeSandbox extends GroovyInterceptor {
        @Override
        public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable {
            if (receiver == Runtime.class) {
                throw new SecurityException("No call on RunTime please");
            }
            return super.onStaticCall(invoker, receiver, method, args);
        }
    }

九、DSL(Json转换)

Groovy支持元数据编程,会将所有groovy代码编译成java对象,如果是groovy代码片段则会动态编译成groovy.lang.Script对象,如果是class类,则会动态编译类实现groovy.lang.GroovyObject接口。编译后对象方法的调用,都会调用GroovyObject接口的invokeMethod方法,下面是我重写invokeMethod方法实现json自动转换的dsl代码。

def invokeMethod(String name, Object args) {
    Object[] objArgs = (Object[]) args
    JSONObject currentJson = (JSONObject) this.getProperty("current_json")
    if (objArgs.size() == 1) {
        Object arg = objArgs[0]
        if (arg instanceof Closure) {
            JSONObject newJson = new JSONObject()
            currentJson.put(name, newJson)
            this.setProperty("current_json", newJson)
            arg.delegate = this
            arg.resolveStrategy = Closure.DELEGATE_ONLY
            arg.run()
            this.setProperty("current_json", currentJson)
        } else {
            currentJson.put(name, arg)
        }
    } else if (objArgs.size() == 2) {
        Object it = objArgs[0]
        Closure single = (Closure) objArgs[1]
        JSONObject newJson = new JSONObject()
        currentJson.put(name, newJson)
        this.setProperty("current_json", newJson)
        single.setProperty("it", it)
        single.call(it)
        this.setProperty("current_json", currentJson)
    } else if (objArgs.size() == 3) {
        Closure eachCl = (Closure) objArgs[2]
        int rule = (int) objArgs[1]
        if (rule == 2) {
            JSONArray array = new JSONArray()
            currentJson.put(name, array)
            objArgs[0].each {
                JSONObject newJson = new JSONObject()
                array.add(newJson)
                eachCl.setProperty("it", it)
                this.setProperty("current_json", newJson)
                eachCl.call(it)
            }
        } else if (rule == 1) {
            JSONObject newJson = new JSONObject()
            currentJson.put(name, newJson)
            objArgs[0].each {
                eachCl.setProperty("it", it)
                this.setProperty("current_json", newJson)
                eachCl.call(it)
            }
        } else if (rule == 3) {
            objArgs[0].each {
                eachCl.setProperty("it", it)
                eachCl.call(it)
            }
        }
        this.setProperty("current_json", currentJson)
    }
}