interactiveshell.java
来自「Groovy动态语言 运行在JVM中的动态语言 可以方便的处理业务逻辑变化大的业」· Java 代码 · 共 570 行 · 第 1/2 页
JAVA
570 行
/*
$Id: InteractiveShell.java 3948 2006-08-01 09:50:46Z glaforge $
Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
Redistribution and use of this software and associated documentation
("Software"), with or without modification, are permitted provided
that the following conditions are met:
1. Redistributions of source code must retain copyright
statements and notices. Redistributions must also contain a
copy of this document.
2. Redistributions in binary form must reproduce the
above copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
3. The name "groovy" must not be used to endorse or promote
products derived from this Software without prior written
permission of The Codehaus. For written permission,
please contact info@codehaus.org.
4. Products derived from this Software may not be called "groovy"
nor may "groovy" appear in their names without prior written
permission of The Codehaus. "groovy" is a registered
trademark of The Codehaus.
5. Due credit should be given to The Codehaus -
http://groovy.codehaus.org/
THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
THE CODEHAUS OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package groovy.ui;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.codehaus.groovy.control.CompilationFailedException;
import org.codehaus.groovy.control.SourceUnit;
import org.codehaus.groovy.runtime.InvokerHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;
import org.codehaus.groovy.sandbox.ui.Prompt;
import org.codehaus.groovy.sandbox.ui.PromptFactory;
import org.codehaus.groovy.tools.ErrorReporter;
/**
* A simple interactive shell for evaluating groovy expressions
* on the command line
*
* @author <a href="mailto:james@coredevelopers.net">James Strachan</a>
* @author <a href="mailto:cpoirier@dreaming.org" >Chris Poirier</a>
* @author Yuri Schimke
* @author Brian McCallistair
* @author Guillaume Laforge
* @author Dierk Koenig, include the inspect command, June 2005
* @version $Revision: 3948 $
*/
public class InteractiveShell {
private final GroovyShell shell;
private final Prompt prompt;
private final InputStream in;
private final PrintStream out;
private final PrintStream err;
private Object lastResult;
/**
* Entry point when called directly.
*/
public static void main(String args[]) {
try {
final InteractiveShell groovy = new InteractiveShell();
groovy.run(args);
}
catch (Exception e) {
System.err.println("Caught: " + e);
e.printStackTrace();
}
}
/**
* Default constructor.
*/
public InteractiveShell() {
this(System.in, System.out, System.err);
}
public InteractiveShell(final InputStream in, final PrintStream out, final PrintStream err) {
this(null,new Binding(), in, out, err);
}
/**
* Constructs a new InteractiveShell instance
*
* @param binding The binding instance
* @param in The input stream to use
* @param out The output stream to use
* @param err The error stream to use
*/
public InteractiveShell(Binding binding, final InputStream in, final PrintStream out, final PrintStream err) {
this(null,binding,in,out,err);
}
/**
* Constructs a new InteractiveShell instance
*
* @param parent The parent ClassLoader
* @param binding The binding instance
* @param in The input stream to use
* @param out The output stream to use
* @param err The error stream to use
*/
public InteractiveShell(ClassLoader parent,Binding binding, final InputStream in, final PrintStream out, final PrintStream err) {
this.in = in;
this.out = out;
this.err = err;
prompt = PromptFactory.buildPrompt(in, out, err);
prompt.setPrompt("groovy> ");
if(parent!= null) {
shell = new GroovyShell(parent,binding);
}
else {
shell = new GroovyShell(binding);
}
Map map = shell.getContext().getVariables();
if (map.get("shell") != null) {
map.put("shell", shell);
}
}
//---------------------------------------------------------------------------
// COMMAND LINE PROCESSING LOOP
/**
* Reads commands and statements from input stream and processes them.
*/
public void run(String[] args) throws Exception {
final String version = InvokerHelper.getVersion();
out.println("Let's get Groovy!");
out.println("================");
out.println("Version: " + version + " JVM: " + System.getProperty("java.vm.version"));
out.println("Type 'exit' to terminate the shell");
out.println("Type 'help' for command help");
out.println("Type 'go' to execute the statements");
boolean running = true;
while (running) {
// Read a single top-level statement from the command line,
// trapping errors as they happen. We quit on null.
final String command = read();
if (command == null) {
close();
break;
}
reset();
if (command.length() > 0) {
// We have a command that parses, so evaluate it.
try {
lastResult = shell.evaluate(command, "CommandLine.groovy");
out.println("\n===> " + lastResult);
} catch (CompilationFailedException e) {
err.println(e);
} catch (Throwable e) {
if (e instanceof InvokerInvocationException) {
InvokerInvocationException iie = (InvokerInvocationException) e;
e = iie.getCause();
}
filterAndPrintStackTrace(e);
}
}
}
}
/**
* Filter stacktraces to show only relevant lines of the exception thrown.
*
* @param e the throwable whose stacktrace needs to be filtered
*/
private void filterAndPrintStackTrace(Throwable e) {
err.println("Caught: " + e);
StackTraceElement[] stackTrace = e.getStackTrace();
for (int i = 0; i < stackTrace.length; i++) {
StackTraceElement element = stackTrace[i];
String fileName = element.getFileName();
if ((fileName==null || (!fileName.endsWith(".java")) && (!element.getClassName().startsWith("gjdk")))) {
err.println("\tat " + element);
}
}
}
protected void close() {
prompt.close();
}
//---------------------------------------------------------------------------
// COMMAND LINE PROCESSING MACHINERY
private StringBuffer accepted = new StringBuffer(); // The statement text accepted to date
private String pending = null; // A line of statement text not yet accepted
private int line = 1; // The current line number
private boolean stale = false; // Set to force clear of accepted
private SourceUnit parser = null; // A SourceUnit used to check the statement
private Exception error = null; // Any actual syntax error caught during parsing
/**
* Resets the command-line processing machinery after use.
*/
protected void reset() {
stale = true;
pending = null;
line = 1;
parser = null;
error = null;
}
/**
* Reads a single statement from the command line. Also identifies
* and processes command shell commands. Returns the command text
* on success, or null when command processing is complete.
* <p/>
* NOTE: Changed, for now, to read until 'execute' is issued. At
* 'execute', the statement must be complete.
*/
protected String read() {
reset();
out.println("");
boolean complete = false;
boolean done = false;
while (/* !complete && */ !done) {
// Read a line. If IOException or null, or command "exit", terminate
// processing.
try {
pending = prompt.readLine();
}
catch (IOException e) {
}
if (pending == null || (COMMAND_MAPPINGS.containsKey(pending) && ((Integer) COMMAND_MAPPINGS.get(pending)).intValue() == COMMAND_ID_EXIT)) {
return null; // <<<< FLOW CONTROL <<<<<<<<
}
// First up, try to process the line as a command and proceed accordingly.
if (COMMAND_MAPPINGS.containsKey(pending)) {
int code = ((Integer) COMMAND_MAPPINGS.get(pending)).intValue();
switch (code) {
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?