groovy语法校验主要解决脚本在编写时能实时检查语法是否正确,类似IDE的功能,沙盒运行主要解决系统若嵌入System.exit(0),会导致整个应用停掉的问题
需要引用的依赖包如下:
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.7</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy -->
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>2.4.7</version>
</dependency>
<dependency>
<groupId>org.kohsuke</groupId>
<artifactId>groovy-sandbox</artifactId>
<version>1.6</version>
</dependency>
方法很简单,test类如下:
import groovy.lang.GroovyShell;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.codehaus.groovy.control.ErrorCollector;
import org.codehaus.groovy.control.MultipleCompilationErrorsException;
import org.junit.Test;
import org.kohsuke.groovy.sandbox.GroovyInterceptor;
import org.kohsuke.groovy.sandbox.SandboxTransformer;
/**
* @author wulongtao
*/
public class GroovyTest {
/**
* 语法校验
*/
@Test
public void grammarCheck() {
try {
String expression = "if(a==1) return 1;";
new GroovyShell().parse(expression);
} catch(MultipleCompilationErrorsException cfe) {
ErrorCollector errorCollector = cfe.getErrorCollector();
System.out.println("Errors: "+errorCollector.getErrorCount());
}
}
class NoSystemExitSandbox extends GroovyInterceptor {
@Override
public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable {
if (receiver==System.class && method=="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);
}
}
/**
* 沙盒运行
*/
@Test
public void sandboxRun() {
final GroovyShell sh = new GroovyShell(new CompilerConfiguration()
.addCompilationCustomizers(new SandboxTransformer()));
new NoSystemExitSandbox().register();
new NoRunTimeSandbox().register();
sh.evaluate("System.exit(0)");
}
}