Naive, but functional interactive javascript shell with Java 6.

[code lang=”java”]
package org.kari.test.script;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;

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

import org.apache.log4j.Logger;
import org.kari.log.LogUtil;

/**
* Test interactive javascript shell
*
* @author kari
*/
public class ScriptShell {
public static final Logger LOG = LogUtil.getLogger(”script.shell”);

private final ScriptEngine mEngine;
private InputStream mIn = System.in;
private PrintStream mOut = System.out;
private PrintStream mErr = System.err;

private ScriptShell() {
ScriptEngineManager manager = new ScriptEngineManager();
mEngine = manager.getEngineByName(”js”);
}

public void run()
throws Exception
{
BufferedReader in = new BufferedReader(new InputStreamReader(mIn));
StringBuilder sb = new StringBuilder();
while (true) {
if (sb.length() == 0) {
mOut.print(”\njs> ”);
mOut.flush();
}

String line = in.readLine();
if (line == null) {
break;
}
sb.append(line);
sb.append(’\n’);

String expr = sb.toString();

try {
mEngine.put(”javax.script.filename”, ””);
Object result = mEngine.eval(expr);
if (result != null) {
printOut(result);
}
sb.setLength(0);
} catch (Exception e) {
String msg = e.getMessage();
boolean missing = false;
if (e instanceof ScriptException) {
missing = msg.indexOf(”missing”) != -1
|| msg.indexOf(”Unexpected end of file”) != -1;
if (expr.endsWith(”;;\n”)) {
missing = false;
}
}

if (!missing) {
sb.setLength(0);
LOG.error(”Failed”, e);
printErr(msg);
}
} finally {
flushOutErr();
}
}
}

private void printErr(String msg) {
flushOutErr();
mErr.println(”FAIL: ” + msg);
flushOutErr();
}

private void printOut(Object result) {
flushOutErr();
mOut.println(result);
flushOutErr();
}

private void flushOutErr() {
mOut.flush();
mErr.flush();
}

public static void main(String[] args) {
try {
ScriptShell shell = new ScriptShell();
shell.run();
} catch (Exception e) {
LOG.error(”failed”, e);
}
}
}
[/code]

Sample session from the shell:

[code]
js> function bar(arg) {
return arg * arg
}

js> for (i = 0; i < 10; i++) { println(bar(i)) } 0 1 4 9 16 25 36 49 64 81 js>
[/code]

/ java

Vastaa

Sähköpostiosoitettasi ei julkaista. Pakolliset kentät on merkitty *

This site uses Akismet to reduce spam. Learn how your comment data is processed.