How do I import Java package in script?

Here you can see how to import a Java class so that you can use the class, creates an instance of
it in the scripting environment. We want to print out the current date on the console. For this we
need to import the Date class that’s packaged under the java.util package.

In the script we can import the java.util package using the following script
importPackage(java.util).

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class ImportPackageExample {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        try {
            engine.eval(getScript());
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    private static String getScript() {
        StringBuilder sb = new StringBuilder();
        sb.append("importPackage(java.util);");
        sb.append("");
        sb.append("var today = new Date();");
        sb.append("println('Today is ' + today);");
        return sb.toString();
    }
}

This program prints the following line:

Today is Fri Sep 11 2009 17:03:02 GMT+0800 (CST)

How do I modified Java object in script?

This example show how to modified Java object from scripting environment. Below we manipulate a collection of string data. To pass data into the scripting engine we use a key-value binding to the script engine.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;

public class ModifiedJavaObjectFromScript {
    public static void main(String[] args) {
        //
        // Creating an array of five colors
        //
        List colors = new ArrayList();
        colors.add("White");
        colors.add("Black");
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");
        
        //
        // Obtain a ScriptEngine instance.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        //
        // Place the colors list into the engine using colorList key.
        // After setting the list into the engine our script will be
        // able to read it.
        //
        engine.put("colorList", colors);
        
        try {
            engine.eval(getScript());
            
            //
            // Redisplay the modified version of colors list object.
            //
            for (String color : colors) {
                System.out.println("Color = " + color);
            }
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }

    private static String getScript() {
        //
        // Below is our script to read the values of Java List that
        // contains string of colors. We also add some other colors
        // to the list object in the script environment.
        //
        String script =
                "var index; " +
                "var colors = colorList.toArray(); " +
                " " +
                "for (index in colors) { " +
                "    println(colors[index]); " +
                "}" +
                " " +
                "colorList.add("Yellow"); " +
                "colorList.add("Purple"); " +
                "colorList.add("Orange"); ";
        return script;
    }
}

How do I access Java object from a script?

This example demonstrate how you can access Java object from a script. We put Java object into the script engine by calling the ScriptEngine‘s put(String key, Object value) method. This value can later be read or access by our script. For example we pass an array of string and a date object for our script to display.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.Date;

public class AccessJavaObjectFromScript {
    public static void main(String[] args) {
        //
        // Creating an array of five colors
        //
        String[] colors = {"White", "Black", "Red", "Green", "Blue"};
        Date now = new Date();

        //
        // Below is our script to read the values of Java array that
        // contains string of colors.
        //
        String script =
                "var index; " +
                "var colors = colorArray; " +
                " " +
                "for (index in colors) { " +
                "    println(colors[index]); " +
                "}" +
                "println('----------'); " +
                "println('Today is ' + date); ";

        //
        // Obtain a ScriptEngine instance.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        //
        // Place the colors array into the engine using colorArray key.
        // After setting the array into the engine our script will be
        // able to read it.
        //
        engine.put("colorArray", colors);
        engine.put("date", now);

        try {
            engine.eval(script);
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

Our code will print as follow:

White
Black
Red
Green
Blue
----------
Today is Mon Jul 13 23:12:19 SGT 2009

How do I get a ScriptEngine by language name and version?

This example show you how you can obtain a script engine for a specific language name and specific language version. In the code below we try to obtain script engine instance for ECMAScript version 1.6.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.util.List;

public class ScriptEngineSearch {
    public static void main(String[] args) {
        String languageName = "ECMAScript";
        String languageVersion = "1.6";

        //
        // Creating a ScriptEngineManager and get the list of available
        // engine factories.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        List factories = manager.getEngineFactories();

        //
        // We obtain a ScriptEngine from the available factories where
        // the language name is ECMAScript and the version is 1.6.
        // ECMAScript is the standard name for JavaScript programming
        // language. If we found the desired language we then get the
        // ScriptEngine by calling factory's getScriptEngine() method.
        //
        ScriptEngine engine = null;
        for (ScriptEngineFactory factory : factories) {
            String language = factory.getLanguageName();
            String version = factory.getLanguageVersion();

            if (language.equals(languageName)
                    && version.equals(languageVersion)) {
                engine = factory.getScriptEngine();
                break;
            }
        }

        if (engine != null) {
            try {
                engine.eval("print('Hello There')");
            } catch (ScriptException e) {
                e.printStackTrace();
            }
        }
    }
}

How do I call a specific function of a script?

This code demonstrate the use of Invocable interface to invoke a specific function of a script. The Invocable.invokeFunction() takes the function name with or without a parameter as the function’s parameter. The parameter value can be passed as a varargs.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import javax.script.Invocable;

public class InvokingFunction {
    public static void main(String[] args) {
        String script =
            "function sayHello() {" +
            "   sayHello(null);" +
            "}" +
            " " +
            "function sayHello(name) {" +
            "   println('Hi there' + " +
            "       ((name == null) ? '!' : ' ' + name + '!'));" +
            "}";

        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByExtension("js");

        try {
            engine.eval(script);

            //
            // Convert / cast the engine into invocable engine.
            //
            Invocable invocableEngine = (Invocable) engine;

            //
            // Invoking sayHello function without parameter.
            //
            invocableEngine.invokeFunction("sayHello");

            //
            // Invoking sayHello function with a parameter.
            //
            invocableEngine.invokeFunction("sayHello", "Jude");
        } catch (ScriptException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}

How do I evaluate or execute a script file?

This example demonstrate how to evaluate script that stored on a file. As we know that the eval() method can also accept a Reader object we can then read the script file using FileReader and pass it as the parameter to the eval() method of the ScriptEngine for further evaluation.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.Reader;
import java.io.FileReader;
import java.io.FileNotFoundException;

public class EvalScriptFile {
    public static void main(String[] args) {
        //
        // Obtaining ECMAScript / JavaScript ScriptEngine.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine engine = manager.getEngineByName("ECMAScript");

        try {
            //
            // Create an instance of File object that point to our
            // scripting file. An create a FileReader to read the
            // file to be passed to the ScriptEngine.eval() method.
            //
            // The file need to be placed in the same folder with
            // our class so it enable to read it. We can define the
            // full path to the file also to make easier for the
            // Reader to find it.
            //
            File script = new File("helloworld.js");
            Reader reader = new FileReader(script);

            engine.eval(reader);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

How do I get the supported scripting engine?

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngineFactory;
import java.util.List;

public class GetSupportedScriptingEngine {
    public static void main(String[] args) {
        //
        // Creating an instance of ScriptEngineManager an get the list
        // of available ScriptEngineFactory.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        List factories = manager.getEngineFactories();

        for (ScriptEngineFactory factory : factories) {
            System.out.println(
                    "EngineName      = " + factory.getEngineName());
            System.out.println(
                    "EngineVersion   = " + factory.getEngineVersion());
            System.out.println(
                    "LanguageName    = " + factory.getLanguageName());
            System.out.println(
                    "LanguageVersion = " + factory.getLanguageVersion());
            System.out.println(
                    "Extensions      = " + factory.getExtensions());

            List names = factory.getNames();
            for (String name : names) {
                System.out.println("Engine Alias = " + name);
            }
        }
    }
}

The code above produces the following information.

EngineName      = Mozilla Rhino
EngineVersion   = 1.6 release 2
LanguageName    = ECMAScript
LanguageVersion = 1.6
Extensions      = [js]
Engine Alias = js
Engine Alias = rhino
Engine Alias = JavaScript
Engine Alias = javascript
Engine Alias = ECMAScript
Engine Alias = ecmascript

Currently, as you can see in the result of the program above, Mozilla Rhino is the only scripting engine provided in the JDK 6 libraries. You can also see that the factory provides many engine name aliases that help you to obtain an engine for the JavaScript programming language.

How do I get ScriptEngine by engine name?

This example shows how to get an instance of ScriptEngine by the engine name. Below we are trying to obtain the JavaScript ScriptEngine.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class GettingScriptEngineByName {
    public static void main(String[] args) {
        ScriptEngineManager manager = new ScriptEngineManager();

        //
        // Obtain an instance of ScriptEngine using the engine name. For
        // example we get a JavaScript ScriptEngine instance.
        //
        ScriptEngine engine = manager.getEngineByName("JavaScript");

        try {
            engine.eval("print('Hello World');");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

How do I evaluate a simple script?

The code below will evaluate a simple script that produces a Hello World message. The evaluate the script, the ScriptEngine provides us with some overloaded eval() method, that for instance accept the script in string or in Reader object.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;
import javax.script.ScriptException;

public class EvaluatingScript {
    public static void main(String[] args) {
        //
        // Obtaining JavaScript' ScriptEngine from the ScriptManager
        // using the engine extension.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine js = manager.getEngineByExtension("js");

        try {
            //
            // Evaluating a simple script
            //
            js.eval("print('Hello World')");
        } catch (ScriptException e) {
            e.printStackTrace();
        }
    }
}

How do I create a ScriptEngine for JavaScript?

This examples demonstrate how to create a JavaScript interpreter or the ScriptEngine for running JavaScript script. The classes related to scripting is packaged under the javax.script package.

Java is since version 6 allows us to script Java using a scripting language such as JavaScript. This allows us to let the user of our program to change or add behavior to the program through scripting language.

package org.kodejava.example.script;

import javax.script.ScriptEngineManager;
import javax.script.ScriptEngine;

public class GettingJavaScriptEngine {
    public static void main(String[] args) {
        //
        // Creating an instance of ScriptManager. With ScriptManager in hand we
        // can create an interpreter or ScriptEngine to run JavaScript.
        //
        ScriptEngineManager manager = new ScriptEngineManager();
        
        //
        // Calling manager.getEngineByExtension("js") returns a ScriptEngine
        // implementation for JavaScript. "js" is the standar extension for
        // JavaScript script file.
        //
        ScriptEngine engine = manager.getEngineByExtension("js");

        //
        // Do something with the script engine.
        //
    }
}