0

My question is pretty similar to How can I load a local file from embedded Rhino?.

Most of the suggestions I've have read suggested modifying java code, but I'm using Rhino that's embedded in vendor software (both Shibboleth and NetIQ IDM), so I don't have access to context in which Rhino exists (or the code that creates it), only the script engine that's been spawned in that context.

Corderer suggested doing something like...

eval("" + Packages.org.apache.commons.io.FileUtils.readFileToString( new java.io.File("/the/local/root", "script.js"); ));

...which works! Like Corderer, though, I was hoping for a less ugly solution (maybe actually being able to use load()). Is eval() the best / easiest option to do this?

Liam

Community
  • 1
  • 1
uglycat5
  • 81
  • 5

2 Answers2

0

Maybe I'm missing something but from what I understand, you just want to read a file on disk from within JavaScript. If so, you can do this:

var fileObj = new java.io.File("/the/local/root/somefile.txt");

This will basically give you access to a Java file object, which then you can manipulate to your heart's content. See the documentation for the java.io.File class to see what methods are available.

Edit: After further review of the question, it seems that you want to load a JavaScript source file from within JavaScript. If so, then you can use Rhino's built-in load command like so:

load("/the/local/root/script.js");
Sid
  • 1,134
  • 10
  • 21
  • 1
    load() only works from the rhino shell, not when you're running in embedded mode. – uglycat5 Jul 27 '14 at 21:48
  • @uglycat5 Can you point to any reference to back that statement? I've worked on a product that shipped with Rhinojs embedded and `load` worked fine for us. – Sid Jul 27 '14 at 21:57
  • 1
    [How can I load a local file from embedded Rhino?](http://stackoverflow.com/questions/12461648/how-can-i-load-a-local-file-from-embedded-rhino); [Rhino load() function available in JavaScript provided by javax.script?](http://stackoverflow.com/questions/3539624/rhino-load-function-available-in-javascript-provided-by-javax-script?rq=1); [Including a JavaScript file during Rhino eval](http://stackoverflow.com/questions/12357334/including-a-javascript-file-during-rhino-eval) – uglycat5 Jul 28 '14 at 13:22
  • I'm using Rhino 1.7r4. The JS is invoked by rhino embedded in Shibboleth. The error returned is `javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "load" is not defined. (#10) in at line number 10` – uglycat5 Jul 28 '14 at 13:26
0

Years later, here's my take: Create a Global object that has the missing load function.

g = new Packages.org.mozilla.javascript.tools.shell.Global(Packages.org.mozilla.javascript.Context.getCurrentContext());
this.load = g.load;

The g variable now holds the global object used in Rhino scripts.

Jochen Bedersdorfer
  • 3,968
  • 23
  • 25