Java Tutorial/Development/Script Engines — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
м (1 версия)
 
(нет различий)

Текущая версия на 15:28, 31 мая 2010

Any script have to be compiled into intermediate code.

This compilation takes a relatively large amount of CPU cycles.

With the Invocable interface you can save time by storing the compiled intermediate code for reuse.



import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class InvocableDemo {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.eval("function add (a, b) {c = a + b; return c; }");
    Invocable jsInvoke = (Invocable) engine;
    Object result1 = jsInvoke.invokeFunction("add", new Object[] { 10, 5 });
    System.out.println(result1);
    Adder adder = jsInvoke.getInterface(Adder.class);
    int result2 = adder.add(10, 5);
    System.out.println(result2);
  }
}
interface Adder {
  int add(int a, int b);
}





Call a JavaScript function three times

import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class CompileTest {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("counter", 0);
    if (engine instanceof Compilable) {
      Compilable compEngine = (Compilable) engine;
      try {
        CompiledScript script = compEngine.rupile("function count(){counter=counter+1;return counter;}; count();");
        System.out.println(script.eval());
        System.out.println(script.eval());
        System.out.println(script.eval());
      } catch (ScriptException e) {
        System.err.println(e);
      }
    } else {
      System.err.println("Engine can"t compile code");
    }
  }
}
/**/



1.0
2.0
3.0


Catch ScriptException

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class BindingDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.put("a", 1);
    engine.put("b", 5);
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    Object a = bindings.get("a");
    Object b = bindings.get("b");
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    Object result;
    try {
      result = engine.eval("c = aaaa + bbbb;");
      System.out.println("a + b = " + result);
    } catch (ScriptException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}



a = 1
b = 5
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "aaaa" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
  at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:110)
  at com.sun.script.javascript.RhinoScriptEngine.eval(RhinoScriptEngine.java:124)
  at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:247)
  at BindingDemo.main(BindingDemo.java:22)


Execute Javascript script in a file

import java.io.FileReader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class RunScriptFileDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    try {
      FileReader reader = new FileReader("yourFile.js");
      engine.eval(reader);
      reader.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}
/* File: yourFile.js
 * 
 function add(a, b) {
    c = a + b;
    return c;
}
result = add (10, 5);
print ("Result = " + result);
*/





Executing Scripts from Java Programs

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class ScriptExecutionDemo {
  public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine jsEngine = manager.getEngineByExtension("js");
    jsEngine.eval("println ("Hello! JavaScript executed from a Java program.")");
  }
}





Get a ScriptEngine by MIME type

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class GetEngineByMimeDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    /* Retrieve a ScriptEngine that supports the text/javascript MIME type */
    ScriptEngine jsEngine = manager.getEngineByMimeType("text/javascript");
    if (!(jsEngine == null)) {
      System.out.println("text/javascript MIME type retrieved:" + jsEngine);
    }
    ScriptEngine jsEngine2 = manager.getEngineByMimeType("text/vbscript");
    if (jsEngine2 == null)
      System.out.println("\nNo supported script engine found for text/vbscript MIME type.");
  }
}





Get Script engine by extension name

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class GetEngineByExtensionDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    /* Retrieve a ScriptEngine that supports scripts with .js extension */
    ScriptEngine jsEngine = manager.getEngineByExtension("js");
    System.out.println(jsEngine);
  }
}





Get the value in JavaScript from Java Code by reference the variable name

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunJavaScript {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
      engine.put("name", "abcde");
      engine.eval("var output = "";for (i = 0; i <= name.length; i++) {"
          + "  output = name.charAt(i)+"-" + output" + "}");
      String name = (String) engine.get("output");
      System.out.println(name);
    } catch (ScriptException e) {
      System.err.println(e);
    }
  }
}
//



-e-d-c-b-a-


Invoke an function

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InvocableTest {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
      engine.eval("function myFunction(name){var output = "";"
          + "  for (i = 0; i <= name.length; i++) {output = name.charAt(i)+"-"+ output"
          + "  } return output;}");
      Invocable invokeEngine = (Invocable) engine;
      Object o = invokeEngine.invokeFunction("myFunction", "abcde");
      System.out.println(o);
    } catch (NoSuchMethodException e) {
      System.err.println(e);
    } catch (ScriptException e) {
      System.err.println(e);
    }
  }
}





Java Language Binding with JavaScript

The Rhino scripting engine of Java SE 6 allows you to use the Java programming language in scripts.



importPackage(javax.swing);
importPackage(java.lang);
importPackage(java.awt.event);
jFrame1 = new JFrame("Greeting");
jLabel1 = new JLabel("Name:");
jTextField1 = JTextField();
jLabel2 = new JLabel();
jButton1 = new JButton("Click");
jFrame1.setSize(400, 400);
listener1 = {
  actionPerformed:function(e)
  {
    jLabel2.setText("Hello "+jTextField1.getText()+ " !");
  }
}
alistener = new ActionListener(listener1);
jButton1.addActionListener(alistener);
jFrame1.getContentPane().setLayout(null);
jFrame1.getContentPane().add(jLabel1);
jFrame1.getContentPane().add(jTextField1);
jFrame1.getContentPane().add(jLabel2);
jFrame1.getContentPane().add(jButton1); 
jLabel1.setBounds(10, 50, 40, 20);
jTextField1.setBounds(50, 50, 220, 20);
jLabel2.setBounds(10, 100, 220, 20);
jButton1.setBounds(280, 50, 120, 23);
jFrame1.setDefaultCloseOperation(jFrame1.EXIT_ON_CLOSE);
jFrame1.setVisible(true);
for(;;)
{
}





Listing All Script Engines

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ListEngineFactoryDemo {
  public static void main(String[] args) {
    // create ScriptEngineManager
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factoryList = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factoryList) {
      System.out.println(factory.getEngineName());
      System.out.println(factory.getLanguageName());
    }
  }
}



Mozilla Rhino
ECMAScript


List the script engines

import java.util.List;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ListEngines {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factories) {
      System.out.println(factory.getEngineName());
      System.out.println(factory.getEngineVersion());
      System.out.println(factory.getLanguageName());
      System.out.println(factory.getLanguageVersion());
      System.out.println(factory.getExtensions());
      System.out.println(factory.getMimeTypes());
      System.out.println(factory.getNames());
    }
  }
}
/*
*/



Mozilla Rhino
1.6 release 2
ECMAScript
1.6
[js]
[application/javascript, application/ecmascript, text/javascript, text/ecmascript]
[js, rhino, JavaScript, javascript, ECMAScript, ecmascript]


Pass parameter to JavaScript through Java code

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunJavaScript {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
      engine.put("name", "abcde");
      engine.eval("var output = "";for (i = 0; i <= name.length; i++) {"
          + "  output = name.charAt(i)+"-" + output" + "}");
      String name = (String) engine.get("output");
      System.out.println(name);
    } catch (ScriptException e) {
      System.err.println(e);
    }
  }
}
//



-e-d-c-b-a-


Read and execute a script source file

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class ScriptExecutionReaderDemo {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine jsEengine = manager.getEngineByExtension("js");
    Reader reader = new InputStreamReader(new FileInputStream("yourJavaScript.js"));
    jsEengine.eval(reader);
  }
}
//File yourJavaScript.js
/*
importPackage(java.lang);
function getName(name)
{
  if ((name != "")&&(name !=null))
  {  
    System.out.println("Hello "+name+"!")
  }
  else
  {   
    System.out.println("Hello!")
  }
}
getName("TOM");
*/





Retrieving Script Engines by Name

A script engine registers alias names with the scripting framework.

For example, the built-in Rhino scripting registers the following names with the scripting framework:

  1. js
  2. rhino
  3. JavaScript
  4. javascript
  5. ECMAScript
  6. ecmascript



import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class GetEngineByName {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    /* Retrieve a ScriptEngine registered with the rhino name */
    ScriptEngine jsEngine = manager.getEngineByName("rhino");
    if (!(jsEngine == null)) {
      System.out.println(jsEngine);
    } else {
      System.out.println("\nNo supported script engine foundregistered as Rhino.");
    }
  }
}





Retrieving the Metadata of Script Engines

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class MetadataDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factories) {
      System.out.println("Full name = " + factory.getEngineName());
      System.out.println("\nVersion = " + factory.getEngineVersion());
      System.out.println("\nSupported language version = " + factory.getLanguageVersion());
    }
  }
}
/*
*/



Full name = Mozilla Rhino
Version = 1.6 release 2
Supported language version = 1.6


Retrieving the Registered Name of a Scripting Engine

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class RegisteredNameDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factories) {
      List<String> regNames = factory.getNames();
      for (int i = 0; i < regNames.size(); i++) {
        System.out.printf("Registered name " + i + " " + (String) regNames.get(i) + "\n");
      }
    }
  }
}





Retrieving the Supported File Extensions of a Scripting Engine

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;

public class FileExtensionsDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factories) {
      List<String> ext = factory.getExtensions();
      for (int i = 0; i < ext.size(); i++) {
        System.out.printf("Supported file extension: " + (String) ext.get(i) + "\n");
      }
    }
  }
}





Retrieving the Supported Mime Types of a Scripting Engine

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class MimeTypesDemo {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factories) {
      List<String> mimeTypes = factory.getMimeTypes();
      for (int i = 0; i < mimeTypes.size(); i++) {
        System.out.printf("Supported MIME type " + i + " " + (String) mimeTypes.get(i) + "\n");
      }
    }
  }
}





Run JavaScript and get the result by using Java

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunJavaScript {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    try {
      Double hour = (Double) engine.eval("var date = new Date();" + "date.getHours();");
      String msg;
      if (hour < 10) {
        msg = "Good morning";
      } else if (hour < 16) {
        msg = "Good afternoon";
      } else if (hour < 20) {
        msg = "Good evening";
      } else {
        msg = "Good night";
      }
      System.out.println(hour);
      System.out.println(msg);
    } catch (ScriptException e) {
      System.err.println(e);
    }
  }
}
/*
*/



10.0
Good afternoon


Running Scripts with Java Script Engine

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class RunScriptDemo {
    public static void main (String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager ();
        ScriptEngine engine = manager.getEngineByName ("js");
        String script = "print ("www.jexp.ru")";
        try {
            engine.eval (script);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}
//



www.jexp.ru


Save the compiled JavaScript to CompiledScript object

import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class CompileTest {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("counter", 0);
    if (engine instanceof Compilable) {
      Compilable compEngine = (Compilable) engine;
      try {
        CompiledScript script = compEngine.rupile("function count(){counter=counter+1;return counter;}; count();");
        System.out.println(script.eval());
        System.out.println(script.eval());
        System.out.println(script.eval());
      } catch (ScriptException e) {
        System.err.println(e);
      }
    } else {
      System.err.println("Engine can"t compile code");
    }
  }
}





Use jrunscript to execute JavaScript scripts

You can use jrunscript in interactive or batch mode to execute scripts.

In interactive mode, you can type and execute scripts from the jrunscript prompt.

In batch mode, you can load and execute script files using jrunscript.

By default, jrunscript executes scripts developed using the JavaScript scripting language.

To specify a different language, you can use the �l option while executing jrunscript.

jrunscript [options]

OptionDescription-classpath pathSpecifies the path to the Java class files.-l languageSpecifies the scripting language.-e scriptEvaluates the given script.-encoding encodingSpecifies the character encoding used while reading script files.-f script-fileEvaluates a script file.-fReads and evaluates a script from the console. This is called interactive mode.-qLists all available script engines.

jrunscript -e "print("hello world")"


Using Java Objects in JavaScript

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class JavaObjectDemo
{  
  public static void main(String[] args) throws Exception
  {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine jsEngine;  
    jsEngine = manager.getEngineByExtension("js");
    jsEngine.eval("importPackage(javax.swing);var optionPane =JOptionPane.showMessageDialog(null, "Hello!);");
  }
}





Using thread to run JavaScript by Java

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class InterfaceTest {
  public static void main(String args[]) throws Exception{
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
      engine.eval("function run() {print("www.jexp.ru");}");
      Invocable invokeEngine = (Invocable) engine;
      Runnable runner = invokeEngine.getInterface(Runnable.class);
      Thread t = new Thread(runner);
      t.start();
      t.join();
  }
}





Variables bound through ScriptEngine

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class BindingDemo {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    engine.put("a", 1);
    engine.put("b", 5);
    Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
    Object a = bindings.get("a");
    Object b = bindings.get("b");
    System.out.println("a = " + a);
    System.out.println("b = " + b);
    Object result = engine.eval("c = a + b;");
    System.out.println("a + b = " + result);
  }
}





With Compilable interface you store the intermediate code of an entire script

import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class CompilableDemo {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("js");
    Compilable jsCompile = (Compilable) engine;
    CompiledScript script = jsCompile.rupile("function hi () {print ("www.jexp.ru !"); }; hi ();");
    for (int i = 0; i < 5; i++) {
      script.eval();
    }
  }
}
//



www.jexp.ru !www.jexp.ru !www.jexp.ru !www.jexp.ru !www.jexp.ru !


Working with Compilable Scripts

import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class CompileTest {
  public static void main(String args[]) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("javascript");
    engine.put("counter", 0);
    if (engine instanceof Compilable) {
      Compilable compEngine = (Compilable) engine;
      try {
        CompiledScript script = compEngine.rupile("function count(){counter=counter+1;return counter;}; count();");
        System.out.println(script.eval());
        System.out.println(script.eval());
        System.out.println(script.eval());
      } catch (ScriptException e) {
        System.err.println(e);
      }
    } else {
      System.err.println("Engine can"t compile code");
    }
  }
}
/**/



1.0
2.0
3.0