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