Java Tutorial/Development/ScriptEngines

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

Bindings And Scopes

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class GetToKnowBindingsAndScopes {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    manager.put("global", "global bindings");
    dumpBindings(manager.getBindings());
    ScriptEngine engine = manager.getEngineByExtension("js");
    engine.put("engine", "engine bindings");
    dumpBindings(engine.getBindings(ScriptContext.GLOBAL_SCOPE));
    dumpBindings(engine.getBindings(ScriptContext.ENGINE_SCOPE));
    try {
      Bindings bindings = engine.createBindings();
      bindings.put("engine", "overridden engine bindings");
      bindings.put("app", new GetToKnowBindingsAndScopes());
      bindings.put("bindings", bindings);
      engine.eval("app.dumpBindings (bindings);", bindings);
    } catch (ScriptException se) {
      System.err.println(se.getMessage());
    }
    ScriptEngine engine2 = manager.getEngineByExtension("js");
    engine2.put("engine2", "engine2 bindings");
    dumpBindings(engine2.getBindings(ScriptContext.GLOBAL_SCOPE));
    dumpBindings(engine2.getBindings(ScriptContext.ENGINE_SCOPE));
    dumpBindings(engine.getBindings(ScriptContext.ENGINE_SCOPE));
  }
  public static void dumpBindings(Bindings bindings) {
    if (bindings == null)
      System.out.println("  No bindings");
    else
      for (String key : bindings.keySet())
        System.out.println("  " + key + ": " + bindings.get(key));
    System.out.println();
  }
}





Enumerate ScriptEngines

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class EnumerateScriptEngines {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factories) {
      System.out.println("Engine name (full): " + factory.getEngineName());
      System.out.println("Engine version: " + factory.getEngineVersion());
      System.out.println("Supported extensions:");
      List<String> extensions = factory.getExtensions();
      for (String extension : extensions)
        System.out.println("  " + extension);
      System.out.println("Language name: " + factory.getLanguageName());
      System.out.println("Language version: " + factory.getLanguageVersion());
      System.out.println("Supported MIME types:");
      List<String> mimetypes = factory.getMimeTypes();
      for (String mimetype : mimetypes)
        System.out.println("  " + mimetype);
      System.out.println("Supported short names:");
      List<String> shortnames = factory.getNames();
      for (String shortname : shortnames)
        System.out.println("  " + shortname);
      System.out.println();
    }
  }
}





Function Evaluator

import java.io.FileReader;
import java.io.IOException;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class FuncEvaluator {
  public static void main(String[] args) {
    if (args.length != 2) {
      System.err
          .println("usage: java FuncEvaluator scriptfile " + "script-exp");
      return;
    }
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("rhino");
    try {
      System.out.println(engine.eval(new FileReader(args[0])));
      System.out.println(engine.eval(args[1]));
    } catch (ScriptException se) {
      System.err.println(se.getMessage());
    } catch (IOException ioe) {
      System.err.println(ioe.getMessage());
    }
  }
}
//////////////
function combinations (n, r)
{
   return fact (n)/(fact (r)*fact (n-r))
}
function fact (n)
{
   if (n == 0)
       return 1;
   else
       return n*fact (n-1);
}





Obtain ScriptEngine

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class ObtainScriptEngine {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine1 = manager.getEngineByExtension("js");
    System.out.println(engine1);
    ScriptEngine engine2 = manager
        .getEngineByMimeType("application/javascript");
    System.out.println(engine2);
    ScriptEngine engine3 = manager.getEngineByName("rhino");
    System.out.println(engine3);
  }
}





Pass value and get return value from script

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class MonthlyPayment {
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension("js");
    String calcMonthlyPaymentScript = "intrate = intrate/1200.0;"
        + "payment = principal*intrate*(Math.pow (1+intrate, months)/"
        + "                            (Math.pow (1+intrate,months)-1));";
    engine.put("principal", 20000.0);
    System.out.println("Principal = " + engine.get("principal"));
    engine.put("intrate", 6.0);
    System.out.println("Interest Rate = " + engine.get("intrate") + "%");
    engine.put("months", 360);
    System.out.println("Months = " + engine.get("months"));
    engine.eval(calcMonthlyPaymentScript);
    System.out.printf("Monthly Payment = %.2f\n", engine.get("payment"));
  }
}





Temperature Conversion with script

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class TemperatureConversion {
  public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("rhino");
    String script = "function c2f(degrees){return degrees*9.0/5.0+32;}";
        + "function f2c(degrees){return (degrees-32)*5.0/9.0;}" + " "
        + "function convertTemperature (degrees, toCelsius){"
        + "   if (toCelsius)" + "return f2c (degrees);elsereturn c2f (degrees);}";
    engine.eval(script);
    Invocable invocable = (Invocable) engine;
    TempConversion tc = invocable.getInterface(TempConversion.class);
    if (tc == null)
      System.err.println("Unable to obtain TempConversion interface");
    else {
      System.out.println("212 degrees Fahrenheit = "
          + tc.convertTemperature(212.0, true) + " degrees Celsius");
    }
  }
}
interface TempConversion {
  double convertTemperature(double degrees, boolean toCelsius);
}





Test Compilation Speed

import javax.script.rupilable;
import javax.script.rupiledScript;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class TestCompilationSpeed {
  final static int MAX_ITERATIONS = 10000;
  public static void main(String[] args) throws Exception {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("JavaScript");
    String fact = "function fact (n){if (n == 0)return 1; else return n*fact (n-1);};";
    long time = System.currentTimeMillis();
    for (int i = 0; i < MAX_ITERATIONS; i++)
      engine.eval(fact);
    System.out.println(System.currentTimeMillis() - time);
    Compilable compilable = null;
    if (engine instanceof Compilable) {
      compilable = (Compilable) engine;
      CompiledScript script = compilable.rupile(fact);
      time = System.currentTimeMillis();
      for (int i = 0; i < MAX_ITERATIONS; i++)
        script.eval();
      System.out.println(System.currentTimeMillis() - time);
    }
  }
}





Threading Behavior

import java.util.List;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
public class ThreadingBehavior {
  public static void main(String[] args) {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory factory : factories)
      System.out.println("Threading behavior: "
          + factory.getParameter("THREADING"));
  }
}