Wednesday, June 22, 2011

Scripting in Java

Did you know that you can compile and run scripting languages like JavaScript, Python, Ruby and many others directly from your Java code? API responsible for it has been created as a result of Java Specification Request 223 and sits in the javax.script package.
Let’s see on a minimalist example how to use the Java Scripting API to run a JavaScript command:

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

public class ScriptTest {
    public static void main(String[] args) throws ScriptException {
        // create a script engine manager
        ScriptEngineManager manager =
            new ScriptEngineManager();
        // create a JavaScript engine
        ScriptEngine javaScriptEngine =
            manager.getEngineByName("JavaScript");
        // evaluate JavaScript code from String
        javaScriptEngine.eval(
            "println('Hello World from JavaScript');");
    }
}

This code should compile and run without problems on Java 6. As a result you should get following output:
Hello World from JavaScript


Support for JavaScript comes included in the standard JRE in form of Rhino: JavaScript for Java ScriptEngine. But other languages are not included by default. Getting support for them is however very easy. Let’s see how you could get support for Python.
You will first need to get Jython, which is a Java implementation for Python. You can download it directly from this URL. If it does not work, go to http://www.jython.org/ and get the newest version from section ‘Download’.
Jython comes with a JAR installer (for example jython_installer-2.5.1.jar). Run it with command ‘java -jar jython_installer-2.5.1.jar’ and install in any directory. After the installation you will find file ‘jython.jar’ inside the directory where you installed Jython. You should include this file in the CLASSPATH when running the next example (You could do this in Eclipse by clicking right mouse button on your project, then Properties->Java Build Path->Libraries->Add External Library).
With jython.jar on the CLASSPATH, let’s run the next code:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineFactory;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class ScriptTestJython {
    public static void main(String[] args) throws ScriptException {
        // create a script engine manager
        ScriptEngineManager manager =
            new ScriptEngineManager();

        //Printing all available scripting languages
        for (ScriptEngineFactory factory :
            manager.getEngineFactories()) {
            System.out.println("Available language: " +
                factory.getLanguageName());
        }

        // create a Jython engine
        ScriptEngine jythonEngine =
            manager.getEngineByName("python");
        // evaluate Jython code from String
        jythonEngine.eval(
            "print \"Hello World from Jython\\n\"");
    }
}

This time on the beginning we print all the available scripting languages. We expect to see there JavaScript, which is always supported by default, and Jython because we included it in the classpath. After that we run a simple Python’s code. Let’s see what comes out:

Available language: ECMAScript
Available language: python
Hello World from Jython

(If you got, besides the lines above, also a lot of strange info lines in red, don’t be worried. Jython prints them once during initialization. You should not see them by the next run)
Some of you may be surprised by the first line ‘ECMAScript’. It is actually JavaScript engine for which ECMA is a base (you can read more about it here). On the next line you see that our Jython was properly loaded and the last line shows proper execution of Python’s code.
There is a pretty good tutorial showing many useful features of Java Scripting API like loading script from a file, exchanging variables, loading Java classes in the script and much more, available on this Sun’s site. You can see the list of available scripting languages and download JAR files for them on this site.

No comments:

Post a Comment

Chitika