Previous Topic

Next Topic

Book Contents

Book Index

OSGi Script Engine

Overview

The OSGi Script Engine interface (com.prosyst.mbs.services.scripting.OSGiScriptEngine) is wrapper of javax.script.ScriptEngine for executing script in OSGi environment. Instances of OSGiScriptEngine are created through OSGi Script Engine Manager service.

See also javax.script.ScriptEngine.

Evaluating Scripts

OSGi Script Engine has methods for evaluating scripts from String and URL sources. Scripts can be evaluated with the engine default ScriptContext and Bindings or custom ones can be specified for the particular execution. All eval methods return the result (if any) of the script execution. Below is a Script Engine example:

OSGiScriptEngine engine = ...

Object result = engine.eval("1+2");

Bindings bindings = engine.createBindings();
bindings.put("name", "John");

engine.eval("print(name)", bindings);

Writer errorWriter = ..;
Writer outputWriter = ..;

ScriptContext context =  new SimpleScriptContext();
context.setErrorWriter(errorWriter);
context.setWriter(outputWriter);

URL scriptURL = ...;
engine.eval(scriptURL, context);

Execution Arguments

Arguments can be passed to scripts by using OSGiScriptEngine.put(String key, Object value) method and variables assigned in scripts can be read through OSGiScriptEngine.get(String key). An example of some script arguments is provided:

engine.put("a", 1);
engine.put("b", 2);

engine.eval("var c = a + b");

System.out.println(engine.get("c"));

These methods write (and read) variables in ScriptContext.ENGINE_SCOPE, so these variables will be available to other scripts executed by the same Script Engine. If this is not desired – for example if the Script Engine is used to execute script for independent threads, which should not share state – separate Bindings object, created with OSGiScriptEngine.createBindings() methods, can be used for each execution as shown in this Create Bindings example:

Bindings bindings = engine.createBindings();

bindings.put("a", 1);
bindings.put("b", 2);

engine.eval("var c = a + b", bindings);

System.out.println(bindings.get("c"));

Invocable and Compilable

If the underlying ScriptEngine implements the Invocable interface the OSGiScriptEngine.asInvocable() method can be used to obtain an Invocable representation of the engine. The OSGiScriptEngine.isInvocable() method can be used to check if the Script Engine supports the Invocable interface:

if (engine.isInvocable()) {
  Invocable invocable = engine.asInvocable();
      
  invocable.invokeFunction("someMethod");
}

Similarly, the OSGiScriptEngine.isCompilable() method can be used to check if the Script Engine supports the Compilable interface and OSGiScriptEngine.asCompilable() method can be used to get its Compilable representation:

if (engine.isCompilable()) {
  Compilable compilable = engine.asCompilable();

  CompiledScript compiled = compilable.compile("a + b");
}