欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java調(diào)用groovy實現(xiàn)原理代碼實例

 更新時間:2020年12月02日 08:38:32   作者:小白菜aaa  
這篇文章主要介紹了Java調(diào)用groovy實現(xiàn)原理代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

一、概述

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

Apache Groovy是一種強大的、可選的類型化和動態(tài)語言,具有靜態(tài)類型和靜態(tài)編譯功能,用于Java平臺,目的在于通過簡潔、熟悉和易于學習的語法提高開發(fā)人員的工作效率。它可以與任何Java程序順利集成,并立即向您的應(yīng)用程序提供強大的功能,包括腳本編寫功能、特定于域的語言編寫、運行時和編譯時元編程以及函數(shù)式編程。

Groovy是基于java虛擬機的,執(zhí)行文件可以是簡單的腳本片段,也可以是一個完整的groovy class,對于java程序員來說,學習成本低,可以完全用java語法編寫。

二、java項目執(zhí)行g(shù)roovy必要環(huán)境

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

三、java項目執(zhí)行g(shù)roovy方式

3.1 ScriptEngineManager

groovy遵循JSR 223標準,可以使用jdk的標準接口ScriptEngineManager調(diào)用。

@org.junit.Test
public void scriptEngineManager() 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文本來自文件,請首先獲取文件內(nèi)容
 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);
}

((Invocable) engine).invokeFunction(方法名,…參數(shù))

3.2 GroovyShell

直接使用GroovyShell,執(zhí)行g(shù)roovy腳本片段,GroovyShell每一次執(zhí)行時代碼時會動態(tài)將代碼編譯成java class,然后生成java對象在java虛擬機上執(zhí)行,所以如果使用GroovyShell會造成class太多,性能較差。

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

3.3 GroovyClassLoader

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

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

3.4 GroovyScriptEngine

GroovyScriptEngine可以從url(文件夾,遠程協(xié)議地址,jar包)等位置動態(tài)加裝resource(script或則Class),同時對

編譯后的class字節(jié)碼進行了緩存,當文件內(nèi)容更新或者文件依賴的類更新時,會自動更新緩存。

@org.junit.Test
public void testGroovyScriptEngine() throws IOException, ResourceException, groovy.util.ScriptException {
 String url = "...(文件地址)";
 GroovyScriptEngine engine = new GroovyScriptEngine(url);
 for (int i = 0; i < 5; i++) {
  Binding binding = new Binding();
  binding.setVariable("index", i);
  // 每一次執(zhí)行獲取緩存Class,創(chuàng)建新的Script對象
  Object run = engine.run("HelloWorld.groovy", binding);
  System.out.println(run);
 }
}

四、安全

4.1 SecureASTCustomizer

Groovy會自動引入java.util,java.lang包,方便用戶調(diào)用,但同時也增加了系統(tǒng)的風險。為了防止用戶調(diào)用System.exit或Runtime等方法導(dǎo)致系統(tǒng)宕機,以及自定義的groovy片段代碼執(zhí)行死循環(huán)或調(diào)用資源超時等問題,Groovy提供了SecureASTCustomizer安全管理者和SandboxTransformer沙盒環(huán)境。

@org.junit.Test
public void testAST() {
 final String script = "import com.alibaba.fastjson.JSONObject;JSONObject object = new JSONObject()";
 // 創(chuàng)建SecureASTCustomizer
 final SecureASTCustomizer secure = new SecureASTCustomizer();
 // 禁止使用閉包
 secure.setClosuresAllowed(true);
 List<Integer> tokensBlacklist = new ArrayList<>();
 // 添加關(guān)鍵字黑名單 while和goto
 tokensBlacklist.add(Types.**KEYWORD_WHILE**);
 tokensBlacklist.add(Types.**KEYWORD_GOTO**);
 secure.setTokensBlacklist(tokensBlacklist);
 // 設(shè)置直接導(dǎo)入檢查
 secure.setIndirectImportCheckEnabled(true);
 // 添加導(dǎo)入黑名單,用戶不能導(dǎo)入JSONObject
 List<String> list = new ArrayList<>();
 list.add("com.alibaba.fastjson.JSONObject");
 secure.setImportsBlacklist(list);
 // statement 黑名單,不能使用while循環(huán)塊
 List<Class<? extends Statement>> statementBlacklist = new ArrayList<>();
 statementBlacklist.add(WhileStatement.class);
 secure.setStatementsBlacklist(statementBlacklist);
 // 自定義CompilerConfiguration,設(shè)置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);
}

SecureASTCustomizer :屬性

tokensBlacklist 關(guān)鍵字黑名單

ImportsBlacklist 導(dǎo)入黑名單

statementBlacklist statement 黑名單

如果代碼塊中出現(xiàn)黑名單限制的內(nèi)容,則會拋出異常

4.2 SandboxTransformer

用戶調(diào)用System.exit或調(diào)用Runtime的所有靜態(tài)方法都會拋出SecurityException

@org.junit.Test
 public void testGroovySandbox() {
  // 自定義配置
  CompilerConfiguration config = new CompilerConfiguration();
  // 添加線程中斷攔截器,可攔截循環(huán)體(for,while)、方法和閉包的首指令
  config.addCompilationCustomizers(new ASTTransformationCustomizer(ThreadInterrupt.class));
  // 添加線程中斷攔截器,可中斷超時線程,當前定義超時時間為3s
  Map<String, Object> timeoutArgs = new HashMap<>();
  timeoutArgs.put("value", 3);
  config.addCompilationCustomizers(new ASTTransformationCustomizer(timeoutArgs, TimedInterrupt.class));
  // 沙盒環(huán)境
  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)");
  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);
  }
 }

五、groovy代碼塊調(diào)用java代碼注意事項

5.1 java代碼行/代碼塊

Java代碼可以直接放在groovy方法體/代碼塊中運行

def hello = {name ->
System.out.println(name)
}

等同于

def helli = {name ->
println(name)
}

5.2 獲取java對象

5.2.1 new

直接通過new 來獲取

def newJavaObject(){
 DpDeptCopyInfo deptCopyInfo = new DpDeptCopyInfo();
 println(deptCopyInfo)
}
newJavaObject();

5.2.2 spring bean

不能使用@Autowired(autowired是在spring啟動后注入的,此時還未加載groovy代碼,故無法注入)

建議實現(xiàn)ApplicationContextAware接口的工具(組件)來獲取spring bean

@Component
public final class SpringUtils implements BeanFactoryPostProcessor
{
 /** Spring應(yīng)用上下文環(huán)境 \*/
 private static ConfigurableListableBeanFactory beanFactory;

 @Override
 public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException
 {
  SpringUtils.beanFactory = beanFactory;
 }
 @SuppressWarnings("unchecked")
 public static <T> T getBean(String name) throws BeansException
 {
  return (T) beanFactory.getBean(name);
 }
 public static <T> T getBean(Class<T> clz) throws BeansException
 {
  T result = (T) beanFactory.getBean(clz);
  return result;
 }
}

例:

被調(diào)用的groovy代碼

def springTransfer = {name ->
  println("==============================開始groovy====================================")
  QueryDataDaoService daoService = SpringUtils.getBean(QueryDataDaoService.class);
  println("對象:" + daoService)
  println("==============================結(jié)束groovy====================================")
  println("==============================返回傳入?yún)?shù)====================================")
  return name
}
springTransfer(name)

Java代碼:

  @Test
  public void testGroovySpringTransfer() throws IOException, ResourceException, ScriptException {
    //獲取 groovy腳本文件的絕對路徑
    String filePath = "文件路徑";
    GroovyScriptEngine engine = new GroovyScriptEngine(filePath);
    //執(zhí)行獲取緩存Class,創(chuàng)建新的Script對象
    Object run = engine.run("SpringTransfer.groovy", "ladq");
    System.out.println("執(zhí)行g(shù)roovy結(jié)果:" + run);
  }

執(zhí)行結(jié)果

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論