Instantiating Rhinoscript Native Objects from Java/Scala
Asked Answered
T

1

1

I'm trying to improve the performance of a javascript snippet evaluator. These script snippets can reference any number of variables that exist in a string-keyed map of json-like object graphs (IE: Json AST). I'm using JDK 1.6 and the embedded Rhinoscript engine (v1.6R2).

Currently, processing takes the form:

  1. Snippet is parsed to discover the names of referenced variables
  2. Variables are retrieved from the map and serialized to a json string
  3. Json string is assigned to a similarly named variable at the start of the script
  4. Evaluate augmented script

I'm trying to figure out how to skip the json serializing stage and create direct Rhinoscript native objects to place in the 'bindings' for the script. The desired steps would then be:

  1. Snippet is parsed to discover the names of referenced variables
  2. Variables are retrieved from the map and converted to native Rhinoscript equivalents
  3. Native objects are placed in bindings
  4. Evaluation of original script with said bindings

Do you know where I could find documentation or examples of how to instantiate native rhinoscript objects?

My scala learning project might be of some use if you want to tinker. And any answer I come up with should appear there too...

http://subversion.assembla.com/svn/freshcode_public/learn_scala/datastore/src/test/scala/pkg/script

Thanks in advance.

Tacklind answered 19/12, 2011 at 7:42 Comment(3)
i am sorry if i am missing something important, but why use rhino and not the scala interpreter directly?Highway
I'm evaluating the javascript at runtime in a servlet container. This is not a development exercise but a feature of our product and the scala interpreter is not available. But thanks for asking.Tacklind
FYI, similar issue regarding access to Maps/ListsTacklind
T
2

So after much fiddling I've come up with an adequate solution although it did not yield the performance increase I had hoped for (only 10% faster).

The solution is specific to Scala / Lift / Json and is contained in the ScriptingUtil.scala file.

To summarise:

  1. Context.javaToJs() does not seem to work in all cases. (java.lang.RuntimeException: No Context associated with current Thread)
  2. A 'scope' object of type Scriptable is needed. The solution I came up with isn't pretty but it works.
  3. To create a NativeArray:

    val na = new NativeArray(arr)
    na.setPrototype(ScriptableObject.getClassPrototype(scope, "Array"))
    
Tacklind answered 22/12, 2011 at 2:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.