Created
May 3, 2013 03:39
-
-
Save aadnk/5507053 to your computer and use it in GitHub Desktop.
A read-eval print loop in Java using Rhino.
This file contains 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.comphenix.testing; | |
import java.io.PrintStream; | |
import java.util.Scanner; | |
import javax.script.ScriptEngine; | |
import javax.script.ScriptEngineManager; | |
import javax.script.ScriptException; | |
public class REP { | |
private boolean running = false; | |
public static void main(String args[]) throws ScriptException { | |
Test test = new Test(); | |
test.start(); | |
} | |
private void start() { | |
final ScriptEngineManager manager = new ScriptEngineManager(); | |
final ScriptEngine engine = manager.getEngineByName("js"); | |
final Scanner input = new Scanner(System.in); | |
final PrintStream output = System.out; | |
StringBuilder builder = new StringBuilder(); | |
int lines = 0; | |
engine.put("program", this); | |
// Start the loop | |
running = true; | |
while (running) { | |
// Aquire a line | |
builder.append(input.nextLine()); | |
if (evaluate(engine, output, builder.toString(), ++lines)) { | |
// Current input has been completed | |
lines = 0; | |
builder.setLength(0); | |
} | |
} | |
// Clean up | |
input.close(); | |
} | |
/** | |
* Evaulate the given statements. | |
* @param engine - the current engine. | |
* @param output - output stream. | |
* @param statements - statements to evaluate. | |
* @param lines - number of statements. | |
* @return TRUE if we successfully evaluated the statement, FALSE if we need more lines. | |
*/ | |
private boolean evaluate(ScriptEngine engine, PrintStream output, String statements, int lines) { | |
try { | |
output.println("> " + engine.eval(statements)); | |
return true; | |
} catch (ScriptException e) { | |
if (e.getLineNumber() != lines) { | |
// An error ocured in the | |
e.printStackTrace(output); | |
return true; | |
} | |
} | |
return false; | |
} | |
public void exit() { | |
running = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment