POM

  1. <!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy-all -->
  2. <dependency>
  3. <groupId>org.codehaus.groovy</groupId>
  4. <artifactId>groovy-all</artifactId>
  5. <version>2.4.7</version>
  6. </dependency>
  7. <!-- https://mvnrepository.com/artifact/org.codehaus.groovy/groovy -->
  8. <dependency>
  9. <groupId>org.codehaus.groovy</groupId>
  10. <artifactId>groovy</artifactId>
  11. <version>2.4.7</version>
  12. </dependency>
  13. <dependency>
  14. <groupId>org.kohsuke</groupId>
  15. <artifactId>groovy-sandbox</artifactId>
  16. <version>1.6</version>
  17. </dependency>

Java

  1. public class GroovyTest {
  2. /**
  3. * 语法校验
  4. */
  5. @Test
  6. public void grammarCheck() {
  7. try {
  8. String expression = "if(a==1) return 1;";
  9. new GroovyShell().parse(expression);
  10. } catch(MultipleCompilationErrorsException cfe) {
  11. ErrorCollector errorCollector = cfe.getErrorCollector();
  12. System.out.println("Errors: "+errorCollector.getErrorCount());
  13. }
  14. }
  15. class NoSystemExitSandbox extends GroovyInterceptor {
  16. @Override
  17. public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable {
  18. if (receiver==System.class && method=="exit")
  19. throw new SecurityException("No call on System.exit() please");
  20. return super.onStaticCall(invoker, receiver, method, args);
  21. }
  22. }
  23. class NoRunTimeSandbox extends GroovyInterceptor {
  24. @Override
  25. public Object onStaticCall(GroovyInterceptor.Invoker invoker, Class receiver, String method, Object... args) throws Throwable {
  26. if (receiver==Runtime.class)
  27. throw new SecurityException("No call on RunTime please");
  28. return super.onStaticCall(invoker, receiver, method, args);
  29. }
  30. }
  31. /**
  32. * 沙盒运行
  33. */
  34. @Test
  35. public void sandboxRun() {
  36. final GroovyShell sh = new GroovyShell(new CompilerConfiguration()
  37. .addCompilationCustomizers(new SandboxTransformer()));
  38. new NoSystemExitSandbox().register();
  39. new NoRunTimeSandbox().register();
  40. sh.evaluate("System.exit(0)");
  41. }
  42. }