Home > Java > Embedding Jython script in Java with ScriptEngine…

Embedding Jython script in Java with ScriptEngine…

In an idle hour I did some more playing about with the Java ScriptEngine (see the earlier post on !Reinventing the Wheel) and decided to see just how easy it was to introduce another ScriptEngine into the mix. It was a toss-up between JRuby and Jython, but in the balance I went with Jython because it has certain benefits to work I frequently get engaged in relating to middleware, although I am altogether less familiar and comfortable with Jython/Python than JRuby/Ruby.

It was spectacularly easy, in fact depressingly so, not a technical challenge in sight. Download and classpath jar. Register Jython with ScriptEngine, run up a JUnit to test it’s available etc recycling the stringEval method outlined in the earlier post to test POC.

OK next up we want Java to be able to execute a Jython script proper. Here’s a simple Jython script to get the current directory (scarfed & modified from WebsphereTools):

import sys
import java.io as jio
currentdir = javaio.File (".")
print "Current directory : " + currentdir.getCanonicalPath()

Worked first time in standalone mode from Jython itself.

Next up is to see whether we can make it execute this script when embedded as a String in Java. Again depressingly easy.

static final private ScriptEngineManager sm = new ScriptEngineManager();
static final private ScriptEngine sEngine = sm.getEngineByName("jython");
static final String lsep = System.getProperty("line.separator");

public static void main(String[] args)
{
String a = "import sys" + lsep;
        a += "import java.io as javaio" + lsep;
        a+= "currentdir = javaio.File (\".\")" + lsep;
        a+= "print \"Current directory : \" + currentdir.getCanonicalPath()" + lsep;
       Object anon = runScript(a, "jython");
}

 public static Object runScript(String script, String engine) {
        Object res = "";
        if (engine.equals("jython")) {
            try {
                res = sEngine.eval(script);
            } catch (ScriptException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
return res;
}

Since I’m using NetBeans (can I say how much I love NetBeans again?) the answer this will print for me is:

Current directory : C:\Users\XXX\Documents\NetBeansProjects\TestEngineFactory (where XXX = my user base dir, names changed to protect the innocent for all the fairly obvious reasons).

The only real gotchas when doing something like this are to remember to ensure quotes are escaped correctly, that lines have a line separator and that you don’t trim or otherwise format incoming Jython script Strings when reading existing Jython scripts since Jython (being a Python superset) has those dull indentation rules etc.

Think I’ll stop blogging now and see how easy it is to do the same job with JRuby to access my arsenal of Ruby classes and mixins. I’ll let you know how I got on with an update later in the week.

  1. wiseimp
    May 8, 2010 at 12:14 pm | #1

    Usefull post. Thks.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: