javax.script package: How to import JavaScript files?

8.5k views Asked by At

I'm using javax.script package for running external JavaScript files within Java application.

How can I import one JavaScript file into another JavaScript file, without using Java code?

1

There are 1 answers

3
Nicholas On BEST ANSWER

When you say without using java code, I am not completely sure what you mean, but this is a pure javascript that works (although it is calling java):

importPackage(java.io);
function loadJs(name, user) {
    println("Loading " + name);
    var f = new File(name);
    var br = new BufferedReader(new FileReader(f));
    var line = null;
    var script = "";
    while((line = br.readLine())!=null) {
        script += line;
    }
    println(script);
    eval(script);
    hello(user);
}

...proivided, of course, that I have the file named (say c:/temp/hellouser.js) with something like:

function hello(name) { print('Hello, ' + name); }

I tested the script using a groovy script:

import javax.script.*;

sem = new ScriptEngineManager();
engine = sem.getEngineByExtension("js");
script1 = """
importPackage(java.io);
function loadJs(name, user) {
    println("Loading " + name);
    var f = new File(name);
    var br = new BufferedReader(new FileReader(f));
    var line = null;
    var script = "";
    while((line = br.readLine())!=null) {
        script += line;
    }
    println(script);
    eval(script);
    hello(user);
}
""";

engine.eval(script1);
Object obj = engine.get("obj");
Invocable inv = (Invocable) engine;
inv.invokeFunction("loadJs", "c:/temp/hellouser.js", "Nicholas");

and the output was:

Loading c:/temp/hellouser.js

function hello(name) { print('Hello, ' + name); }

Hello, Nicholas

I hope this is approximately what you were looking for....

=========================== UPDATE ===========================

Here's a cleaned up version that extends the Rhino script engine factory (because the engine itself is final):

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

import com.sun.script.javascript.RhinoScriptEngineFactory;

/**
 * <p>Title: LoadEnabledRhinoEngineFactory</p>
 * <p>Description: Adding a loadJs function to the standard JS engine</p> 
 * <p>Company: Helios Development Group LLC</p>
 * @author Whitehead (nwhitehead AT heliosdev DOT org)
 * <p><code>org.helios.apmrouter.js.LoadEnabledRhinoEngineFactory</code></p>
 */

public class LoadEnabledRhinoEngineFactory extends RhinoScriptEngineFactory {

    /** The load script source */
    public static final String LOAD_JS = 
        "importPackage(java.io); " +
        "var script = ''; " +
        "var ctx = null; " +
        "function loadScript(name) { " +
            "var f = new File(name); " +
            "var br = new BufferedReader(new FileReader(f)); " +
            "var line = null; " +           
            "while((line = br.readLine())!=null) { " +
                "    script += line; " +
            "} " +
            "_e_ngine.eval(script);" + 
        "} ";
    
    /**
     * {@inheritDoc}
     * @see com.sun.script.javascript.RhinoScriptEngineFactory#getScriptEngine()
     */
    @Override
    public ScriptEngine getScriptEngine() {
        ScriptEngine se = super.getScriptEngine();
        Bindings b = se.createBindings();
        b.put("_e_ngine", se);
        se.setBindings(b, ScriptContext.GLOBAL_SCOPE);
        try {
            se.eval(LOAD_JS);
        } catch (ScriptException e) {
            throw new RuntimeException(e);
        }
        return se;
    }
    

Now, loadScript(fileName) is part of the engine and you can cleanly call it with JS like:

loadScript('c:/temp/hellouser.js'); 
hello('Nicholas');"

or as I tested in Java:

ScriptEngine se = new LoadEnabledRhinoEngineFactory().getScriptEngine();
try {
    se.eval("loadScript('c:/temp/hellouser.js'); hello('Nicholas');");
} catch (Exception e) {
    e.printStackTrace(System.err);
}

Cheers.