Monday, June 23, 2014

How to call js code/file in Java?

Found this interesting part which could possible used in a number of ways like a rule engine. If I would have known this before might have considered this approach over Jexl, or would have evaluated for its performance compared to JEXL. 

But for sure have other use cases like testing, data crawling, etc.

Calling into Javascript scripts from Java code:
Calling Java objects from a script is only half of the story: The Java scripting environment also provides the ability to invoke scripts from within Java code. Doing so just requires instantiating a ScriptEngine, then loading the script in and evaluating it, as shown in Listing 5:

Listing 5. Scripting on the Java platform
import java.io.*;
import javax.script.*;

public class App
{
    public static void main(String[] args)
    {
        try
        {
            ScriptEngine engine = 
                new ScriptEngineManager().getEngineByName("javascript");
            for (String arg : args)
            {
                FileReader fr = new FileReader(arg);
                engine.eval(fr);
            }
        }
        catch(IOException ioEx)
        {
            ioEx.printStackTrace();
        }
        catch(ScriptException scrEx)
        {
            scrEx.printStackTrace();
        }
    }
}


The eval() method can also operate against a straight String, so the script needn't come from a file on the filesystem — it can come from a database, the user, or even be manufactured within the application based on circumstance and user action.