2013年9月26日 星期四

[ Java 文章收集 ] Java SE 6.0 內建 Javascript 引擎測試

來源自 這裡 
Preface: 
Java SE 6.0 採納 JSR 223 建議,使得 Java 能夠與眾多 Script 語言協同運作,透過 Java 定義的標準 API,能夠讓 Script 直接存取和控制 Java 的物件,而Java 應用程式當中也能夠直接內嵌 Script 環境。Java SE 6 的 javax.script package 定義了 Script API,裡面共實作了六個介面和六個類別,如下: 
- 介面 
Bindings: A mapping of key/value pairs, all of whose keys are Strings.
Compilable: The optional interface implemented by ScriptEngines whose methods compile scripts to a form that can be executed repeatedly without recompilation.
Invocable: The optional interface implemented by ScriptEngines whose methods allow the invocation of procedures in scripts that have previously been executed.
ScriptContext: The interface whose implementing classes are used to connect Script Engines with objects, such as scoped Bindings, in hosting applications.
ScriptEngine: ScriptEngine is the fundamental interface whose methods must be fully functional in every implementation of this specification.
ScriptEngineFactory: ScriptEngineFactory is used to describe and instantiate ScriptEngines.

- 類別 
AbstractScriptEngine: Provides a standard implementation for several of the variants of the eval method.
CompiledScript: Extended by classes that store results of compilations.
ScriptEngineManager:
The ScriptEngineManager implements a discovery and instantiation mechanism for ScriptEngine classes and also maintains a collection of key/value pairs storing state shared by all engines created by the Manager.
SimpleBindings:A simple implementation of Bindings backed by a HashMap or some other specified Map.
SimpleScriptContext: Simple implementation of ScriptContext.

範例01:第一個 Hello World 程式 
  1. package test.scripts;  
  2.   
  3. import javax.script.ScriptEngine;  
  4. import javax.script.ScriptEngineManager;  
  5. import javax.script.ScriptException;  
  6.   
  7. public class JSDemo1 {  
  8.     public static void main(String args[])  
  9.     {  
  10.         ScriptEngineManager mgr = new ScriptEngineManager(); // 建立一個 Script 管理員  
  11.         ScriptEngine jsEngine = mgr.getEngineByName("JavaScript"); // 取得 Javascript 引擎  
  12.         try {  
  13.           jsEngine.eval("print('Hello, world!')"); // 透過 Javascript 引擎解譯 print('hello, world') 命令  
  14.         } catch (ScriptException ex) {  
  15.             ex.printStackTrace();  
  16.         }   
  17.     }  
  18. }  
範例02:列舉 Java 環境支援的 Script 引擎 
  1. package test.scripts;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.script.ScriptEngineFactory;  
  6. import javax.script.ScriptEngineManager;  
  7.   
  8. public class JSDemo2 {  
  9.   
  10.     /** 
  11.      * BD: 範例02:列舉 Java 環境支援的 Script 引擎 
  12.      * @param args 
  13.      */  
  14.     public static void main(String[] args) {  
  15.         ScriptEngineManager mgr = new ScriptEngineManager();  
  16.         List factories = mgr.getEngineFactories();  
  17.         for (ScriptEngineFactory factory : factories) {  
  18.             System.out.println("ScriptEngineFactory Info");  
  19.   
  20.             String engName = factory.getEngineName(); // 引擎名稱  
  21.             String engVersion = factory.getEngineVersion(); // 引擎版本  
  22.             String langName = factory.getLanguageName(); // Script 語言  
  23.             String langVersion = factory.getLanguageVersion(); // 語言版本  
  24.   
  25.             System.out.printf("\tScript Engine: %s (%s)\n", engName, engVersion);  
  26.             List engNames = factory.getNames();  
  27.             for (String name : engNames) {  
  28.                 System.out.printf("\t\tEngine Alias: %s\n", name);  
  29.             }  
  30.   
  31.             System.out.printf("\tLanguage: %s (%s)\n", langName, langVersion);  
  32.         }  
  33.     }  
  34. }  
執行結果: 
ScriptEngineFactory Info
Script Engine: Mozilla Rhino (1.6 release 2)
Engine Alias: js
Engine Alias: rhino
Engine Alias: JavaScript
Engine Alias: javascript
Engine Alias: ECMAScript
Engine Alias: ecmascript
Language: ECMAScript (1.6)

範例03:搜尋指定的 Script 引擎 
  1. package test.scripts;  
  2.   
  3. import java.util.List;  
  4.   
  5. import javax.script.ScriptEngine;  
  6. import javax.script.ScriptEngineFactory;  
  7. import javax.script.ScriptEngineManager;  
  8.   
  9. public class JSDemo3 {  
  10.   
  11.     /** 
  12.      * BD: 範例03:搜尋指定的 Script 引擎 
  13.      * @param args 
  14.      */  
  15.     public static void main(String[] args) {  
  16.         ScriptEngineManager mgr = new ScriptEngineManager();  
  17.         List scriptFactories = mgr.getEngineFactories();  
  18.         for (ScriptEngineFactory factory : scriptFactories) {  
  19.             String langName = factory.getLanguageName();  
  20.             String langVersion = factory.getLanguageVersion();  
  21.             if (langName.startsWith("ECMAScript") && langVersion.startsWith("1.6")) { // 比對指定的與名稱和版本  
  22.                 ScriptEngine engine = factory.getScriptEngine();  
  23.                 System.out.printf("Engine:%s\n", engine);  
  24.                 break;  
  25.             }  
  26.         }  
  27.     }  
  28. }  
範例04:執行外部 javasript 檔案 
考慮有如下的 js 檔案: 
- hellp.js 
  1. var str="Hello world, welcome to the universe.";  
  2. var n=str.indexOf("welcome");  
  3. print(str+" "+n);  
接著你可以如下執行該 js 檔案: 
  1. package test.scripts;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.InputStream;  
  5. import java.io.InputStreamReader;  
  6. import java.io.Reader;  
  7.   
  8. import javax.script.ScriptEngine;  
  9. import javax.script.ScriptEngineManager;  
  10. import javax.script.ScriptException;  
  11.   
  12. public class JSDemo4 {  
  13.   
  14.     /** 
  15.      * BD: 範例04:執行外部 javasript 檔案 
  16.      * @param args 
  17.      */  
  18.     public static void main(String[] args) throws Exception {  
  19.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  20.         ScriptEngine engine = engineMgr.getEngineByName("ECMAScript");  
  21.         InputStream is = new FileInputStream("hello.js");  
  22.         try {  
  23.             Reader reader = new InputStreamReader(is);  
  24.             engine.eval(reader);  
  25.         } catch (ScriptException ex) {  
  26.             ex.printStackTrace();  
  27.         }  
  28.     }  
  29. }  
執行結果: 
Hello world, welcome to the universe. 13

範例05:透過 Invocable 介面喚起 Javascript 函數 
  1. package test.scripts;  
  2.   
  3. import javax.script.Invocable;  
  4. import javax.script.ScriptEngine;  
  5. import javax.script.ScriptEngineManager;  
  6. import javax.script.ScriptException;  
  7.   
  8. public class JSDemo5 {  
  9.   
  10.     /** 
  11.      * BD: 範例05:透過 Invocable 介面喚起 Javascript 函數 
  12.      * @param args 
  13.      */  
  14.     public static void main(String[] args) {  
  15.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  16.         ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");  
  17.         try {  
  18.             jsEngine.eval("function sayHello() {" +  
  19.                         "  println('Hello, world!');" +  
  20.                         "}");  
  21.             Invocable invocableEngine = (Invocable) jsEngine;  
  22.             invocableEngine.invokeFunction("sayHello");  
  23.         } catch (ScriptException ex) {  
  24.             ex.printStackTrace();  
  25.         } catch (NoSuchMethodException nsme){  
  26.             nsme.printStackTrace();  
  27.         }  
  28.     }  
  29. }  
執行結果: 
Hello, world!

範例06:Script 直接存取 Java 物件 
  1. package test.scripts;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.script.ScriptEngine;  
  7. import javax.script.ScriptEngineManager;  
  8. import javax.script.ScriptException;  
  9.   
  10. public class JSDemo6 {  
  11.     /** 
  12.      * BD: 範例06:Script 直接存取 Java 物件  
  13.      * @param args 
  14.      */  
  15.     public static void main(String args[]) {  
  16.         List namesList = new ArrayList();  
  17.         namesList.add("Jill");  
  18.         namesList.add("Bob");  
  19.         namesList.add("Laureen");  
  20.         namesList.add("Ed");  
  21.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  22.         ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");  
  23.         jsEngine.put("namesListKey", namesList); // 將 java 變數指定給 javascript 環境中的 nameListKey 變數  
  24.         System.out.println("Executing in script environment…");  
  25.         try {  
  26.             // 列印 Java 的 nameList 變數內容,並新增一個 Dana 字串資料到 List 尾端  
  27.             jsEngine.eval("var x;" + "var names = namesListKey.toArray();"  
  28.                     + "for(x in names) {" + "  println(names[x]);" + "}"  
  29.                     + "namesListKey.add(\"Dana\");");  
  30.         } catch (ScriptException ex) {  
  31.             ex.printStackTrace();  
  32.         }  
  33.         System.out.println("Executing in Java environment…");  
  34.         for (String name : namesList) {  
  35.             System.out.println(name);  
  36.         }  
  37.     }  
  38. }  
執行結果: 
Executing in script environment…
Jill
Bob
Laureen
Ed
Executing in Java environment…
Jill
Bob
Laureen
Ed
Dana

範例07:透過 Invocable 將參數值傳遞給 Javascript 中的函數 
  1. package test.scripts;  
  2.   
  3. import java.util.ArrayList;  
  4. import java.util.List;  
  5.   
  6. import javax.script.Invocable;  
  7. import javax.script.ScriptEngine;  
  8. import javax.script.ScriptEngineManager;  
  9. import javax.script.ScriptException;  
  10.   
  11. public class JSDemo7 {  
  12.   
  13.     /** 
  14.      * BD: 範例07:透過 Invocable 將參數值傳遞給 Javascript 中的函數 
  15.      * @param args 
  16.      */  
  17.     public static void main(String[] args) {  
  18.         List namesList = new ArrayList();  
  19.         namesList.add("Jill");  
  20.         namesList.add("Bob");  
  21.         namesList.add("Laureen");  
  22.         namesList.add("Ed");  
  23.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  24.         ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");  
  25.         Invocable invocableEngine = (Invocable) jsEngine;  
  26.         try {  
  27.             System.out.printf("\t[Info] Execute in JS:\n");  
  28.             jsEngine.eval("function printNames1(namesList) {" + "  var x;"  
  29.                     + "  var names = namesList.toArray();"  
  30.                     + "  for(x in names) {" + "    println(names[x]);" + "  }"  
  31.                     + "}" + "function addName(namesList, name) {"  
  32.                     + "  namesList.add(name);" + "}");  
  33.             invocableEngine.invokeFunction("printNames1", namesList);  
  34.             invocableEngine.invokeFunction("addName", namesList, "Dana");  
  35.             System.out.printf("\t[Info] Execute in Java:\n");  
  36.             for(String name:namesList) System.out.println(name);  
  37.         } catch (ScriptException ex) {  
  38.             ex.printStackTrace();  
  39.         } catch (NoSuchMethodException ex) {  
  40.             ex.printStackTrace();  
  41.         }  
  42.     }  
  43. }  
執行結果: 
[Info] Execute in JS:
Jill
Bob
Laureen
Ed
[Info] Execute in Java:
Jill
Bob
Laureen
Ed
Dana

範例08:script 使用 Java 的 package 
  1. package test.scripts;  
  2.   
  3. import javax.script.ScriptEngine;  
  4. import javax.script.ScriptEngineManager;  
  5. import javax.script.ScriptException;  
  6.   
  7. public class JSDemo8 {  
  8.   
  9.     /** 
  10.      * BD: 範例08:script 使用 Java 的 package 
  11.      * @param args 
  12.      */  
  13.     public static void main(String[] args) {  
  14.         ScriptEngineManager engineMgr = new ScriptEngineManager();  
  15.         ScriptEngine jsEngine = engineMgr.getEngineByName("ECMAScript");  
  16.         try {  
  17.             jsEngine.eval("importPackage(javax.swing);" + "var optionPane = "  
  18.                     + "  JOptionPane.showMessageDialog(null, 'Hello, world!');");  
  19.         } catch (ScriptException ex) {  
  20.             ex.printStackTrace();  
  21.         }  
  22.     }  
  23. }  
Supplement: 
W3Schools.com > JavaScript tutorial 
jrunscript - command line script shell 
Wiki > Rhino (JavaScript engine)

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...