Adding Java Classes to Rhino JavaScript

In the post LibreOffice Javascript, I wrote about Rhino Javascript, which is a Javascript interpreter written in Java. This tool has been developed by Mozilla. With this tool you can instantiate Java classes and to access them via Javascript commands ‘importClass’ and ‘importPackage’.

How to ass classes and packages you can load ?

This is not too hard: the ‘rhino’ command is a shell script. In linux, you can find it using the command:

which rhino

You’ll see the response:

/usr/bin/rhino

Then you can look into the file with a text editor or the ‘more’ command, and see that this is a script that performs a Java class. Jar files and classes that a Java programs uses are found in the environment variable ‘CLASSPATH” or after the directive ‘-classpath’. In this script you’ll find that the class path the content of the variable ‘JAVA_CLASSPATH’.

I decided to add the ‘Tidy’ package. In my computer the path of this package is ‘/usr/share/maven-repo/net/sf/jtidy/jtidy/debian/jtidy-debian.jar’, so the script looks like:

#!/bin/sh

JAVA_CMD=”/usr/bin/java”
JAVA_OPTS=””
JAVA_CLASSPATH=”/usr/share/java/js.jar:/usr/share/java/jline.jar:/usr/share/maven-repo/net/sf/jtidy/jtidy/debian/jtidy-debian.jar
JAVA_MAIN=”org.mozilla.javascript.tools.shell.Main”
export LD_LIBRARY_PATH=/home/amity/myWs
##
## Remove bootclasspath overriding for OpenJDK since
## it now use a mangled version of Rhino (in sun.org.mozilla.rhino package)
##
## References:
## <https://bugs.launchpad.net/ubuntu/+source/openjdk-6/+bug/255149&gt;
## <http://icedtea.classpath.org/bugzilla/show_bug.cgi?id=179&gt;
## <http://www.openoffice.org/issues/show_bug.cgi?id=91641&gt;
##

$JAVA_CMD $JAVA_OPTS -classpath $JAVA_CLASSPATH $JAVA_MAIN “$@”

BTW, in Window, environment variables are enclosed by ‘%’ signes. For example: ‘%JAVA_CLASSPATH%’.

Advertisements