Created
September 30, 2011 20:04
-
-
Save gimmi/1254822 to your computer and use it in GitHub Desktop.
Invoking Rhino Javascript from Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.gimmi.jsmake; | |
import org.mozilla.javascript.Context; | |
import org.mozilla.javascript.ContextAction; | |
import org.mozilla.javascript.ScriptableObject; | |
import org.mozilla.javascript.commonjs.module.Require; | |
import org.mozilla.javascript.tools.ToolErrorReporter; | |
import org.mozilla.javascript.tools.shell.Global; | |
import org.mozilla.javascript.tools.shell.QuitAction; | |
import org.mozilla.javascript.tools.shell.ShellContextFactory; | |
import java.io.File; | |
import java.net.MalformedURLException; | |
import java.util.Arrays; | |
import java.util.List; | |
public class Main { | |
public static void main(String[] commandArgs) { | |
final String jsmakeDirectory = commandArgs[0]; | |
final String currentDirectory = commandArgs[1]; | |
final String mainModuleId = commandArgs[2]; | |
final String[] scriptArgs = Arrays.copyOfRange(commandArgs, 3, commandArgs.length - 1); | |
ShellContextFactory shellContextFactory = new ShellContextFactory(); | |
final Global global = new Global(); | |
global.initQuitAction(new QuitAction() { | |
public void quit(Context cx, int exitCode) { | |
System.exit(exitCode); | |
} | |
}); | |
ToolErrorReporter errorReporter = new ToolErrorReporter(false, global.getErr()); | |
shellContextFactory.setErrorReporter(errorReporter); | |
global.init(shellContextFactory); | |
shellContextFactory.call(new ContextAction() { | |
public Object run(Context cx) { | |
List<String> moduleUrls = Arrays.asList(pathNameToUrl(jsmakeDirectory), pathNameToUrl(currentDirectory)); | |
Require require = global.installRequire(cx, moduleUrls, false); | |
Object[] array = new Object[scriptArgs.length]; | |
System.arraycopy(scriptArgs, 0, array, 0, scriptArgs.length); | |
global.defineProperty("arguments", cx.newArray(global, array), ScriptableObject.DONTENUM); | |
require.requireMain(cx, mainModuleId); | |
return null; | |
} | |
}); | |
} | |
private static String pathNameToUrl(String pathName) { | |
try { | |
return new File(pathName).toURI().toURL().toString(); | |
} catch (MalformedURLException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment