Skip to content

Instantly share code, notes, and snippets.

@hhutch
Last active August 29, 2015 14:02
Show Gist options
  • Save hhutch/2b612973307de59a0029 to your computer and use it in GitHub Desktop.
Save hhutch/2b612973307de59a0029 to your computer and use it in GitHub Desktop.

References

maven quickstart

http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

installig rhino as a command line interpreter

http://joelinoff.com/blog/?p=783

you can run require.js under rhino

https://github.com/jrburke/r.js/

instructions on the github page

since rhino 1.7R3 release commonjs is built in

http://tschaub.net/blog/2011/05/17/commonjs-modules-with-rhino.html

really straightforward tutorial

Official Rhino examples

https://github.com/mozilla/rhino/tree/master/examples

Prerequesites

Maven

Java 1.7R4

unix-like OS

OS X, linux, bsd, etc

Create a new Maven Project

mvn archetype:generate -DgroupId=com.abe.app -DartifactId=abe-app -DarchetypeArtifactId=abe-quickstart -DinteractiveMode=false
cd abe-app

Add Rhino dependency to Maven

in the … section

<dependency>
  <groupId>org.mozilla</groupId>
  <artifactId>rhino</artifactId>
  <version>1.7R4</version>
</dependency>

By adding this dependency when compiling with maven, it will automatically be included in the compile call. The replaces the need to manipulate classpath and call javac manually.

Note: you can find any JAR on mvnrepository.com

http://mvnrepository.com/artifact/org.mozilla/rhino/1.7R4

notice that the Maven tab has the block filled out for you

Modify abe-script/src/main/java/com/abe/app/App.java

add import library

import org.mozilla.javascript.*;

replace body of main() method with

// Creates and enters a Context. The Context stores information
// about the execution environment of a script.
Context cx = Context.enter();
try {
    // Initialize the standard objects (Object, Function, etc.)
    // This must be done before scripts can be executed. Returns
    // a scope object that we use in later calls.
    Scriptable scope = cx.initStandardObjects();

    String s = "Math.cos(Math.PI);";

    // Now evaluate the string we've colected.
    Object result = cx.evaluateString(scope, s, "<cmd>", 1, null);

    // Convert the result to a string and print it.
    System.err.println(Context.toString(result));

} finally {
    // Exit from the context.
    Context.exit();
}

compile with maven

mvn package

run script

you must include the classpath manually in your java call, or modify the $CLASSPATH shell var

java -cp ~/.m2/repository/org/mozilla/rhino/1.7R4/rhino-1.7R4.jar:target/abe-app-1.0-SNAPSHOT.jar com.abe.app.App

note that ~/.m2 is the default location for Maven local class installations.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment