use of jline.console.UserInterruptException in project graal by oracle.
the class MultiLanguageShell method readEvalPrint.
public int readEvalPrint() throws IOException {
ConsoleReader console = new ConsoleReader(in, out);
console.setHandleUserInterrupt(true);
console.setExpandEvents(false);
console.setCopyPasteDetection(true);
console.println("GraalVM MultiLanguage Shell " + context.getEngine().getVersion());
console.println("Copyright (c) 2013-2018, Oracle and/or its affiliates");
List<Language> languages = new ArrayList<>();
Set<Language> uniqueValues = new HashSet<>();
for (Language language : context.getEngine().getLanguages().values()) {
if (language.isInteractive()) {
if (uniqueValues.add(language)) {
languages.add(language);
}
}
}
languages.sort(Comparator.comparing(Language::getName));
Map<String, Language> prompts = new HashMap<>();
StringBuilder promptsString = new StringBuilder();
for (Language language : languages) {
String prompt = createPrompt(language).trim();
promptsString.append(prompt).append(" ");
prompts.put(prompt, language);
console.println(" " + language.getName() + " version " + language.getVersion());
}
if (languages.isEmpty()) {
throw new Launcher.AbortException("Error: No Graal languages installed. Exiting shell.", 1);
}
printUsage(console, promptsString, false);
int maxNameLength = 0;
for (Language language : languages) {
maxNameLength = Math.max(maxNameLength, language.getName().length());
}
String startLanguage = defaultStartLanguage;
if (startLanguage == null) {
startLanguage = languages.get(0).getId();
}
Language currentLanguage = context.getEngine().getLanguages().get(startLanguage);
if (currentLanguage == null) {
throw new Launcher.AbortException("Error: could not find language '" + startLanguage + "'", 1);
}
assert languages.indexOf(currentLanguage) >= 0;
Source bufferSource = null;
String id = currentLanguage.getId();
// console.println("initialize time: " + (System.currentTimeMillis() - start));
String prompt = createPrompt(currentLanguage);
console.getKeys().bind(String.valueOf((char) 12), new ActionListener() {
public void actionPerformed(ActionEvent e) {
throw new ChangeLanguageException(null);
}
});
console.getKeys().bind(String.valueOf((char) 10), new ActionListener() {
public void actionPerformed(ActionEvent e) {
throw new RuntimeIncompleteSourceException();
}
});
// initializes the language
context.initialize(currentLanguage.getId());
boolean verboseErrors = false;
for (; ; ) {
String input = null;
Source source = null;
try {
input = console.readLine(bufferSource == null ? prompt : createBufferPrompt(prompt));
if (input == null) {
break;
} else if (input.trim().equals("")) {
continue;
}
Language switchedLanguage = null;
String trimmedInput = input.trim();
if (trimmedInput.equals("-usage")) {
printUsage(console, promptsString, true);
input = "";
} else if (trimmedInput.equals("-verboseErrors")) {
verboseErrors = !verboseErrors;
if (verboseErrors) {
console.println("Verbose errors is now on.");
} else {
console.println("Verbose errors is now off.");
}
input = "";
} else if (prompts.containsKey(trimmedInput)) {
switchedLanguage = prompts.get(input);
input = "";
}
NonBlockingInputStream nonBlockIn = ((NonBlockingInputStream) console.getInput());
while (nonBlockIn.isNonBlockingEnabled() && nonBlockIn.peek(10) != -2 && switchedLanguage == null) {
String line = console.readLine(createBufferPrompt(prompt));
String trimmedLine = line.trim();
if (prompts.containsKey(trimmedLine)) {
switchedLanguage = prompts.get(trimmedLine);
break;
} else {
input += "\n" + line;
}
}
if (!input.trim().equals("")) {
source = Source.newBuilder(currentLanguage.getId(), input, "<shell>").interactive(true).build();
context.eval(source);
bufferSource = null;
console.getHistory().replace(source.getCharacters());
}
if (switchedLanguage != null) {
throw new ChangeLanguageException(switchedLanguage);
}
} catch (UserInterruptException | EOFException e) {
// interrupted by ctrl-c
break;
} catch (ChangeLanguageException e) {
bufferSource = null;
histories.put(currentLanguage, console.getHistory());
currentLanguage = e.getLanguage() == null ? languages.get((languages.indexOf(currentLanguage) + 1) % languages.size()) : e.getLanguage();
History history = histories.computeIfAbsent(currentLanguage, k -> new MemoryHistory());
console.setHistory(history);
id = currentLanguage.getId();
prompt = createPrompt(currentLanguage);
console.resetPromptLine("", "", 0);
context.initialize(id);
} catch (ThreadDeath e) {
console.println("Execution killed!");
continue;
} catch (RuntimeIncompleteSourceException e) {
console.println();
input += "\n";
bufferSource = source;
} catch (PolyglotException e) {
input += "\n";
bufferSource = source;
if (e.isExit()) {
return e.getExitStatus();
} else if (e.isIncompleteSource()) {
input += "\n";
bufferSource = source;
} else if (!e.isInternalError()) {
if (e.getMessage() != null && e.getMessage().isEmpty()) {
console.println(e.toString());
} else {
if (verboseErrors) {
e.printStackTrace(new PrintWriter(console.getOutput()));
}
}
} else {
e.printStackTrace(new PrintWriter(console.getOutput()));
}
} catch (Throwable e) {
e.printStackTrace(new PrintWriter(console.getOutput()));
}
}
return 0;
}
use of jline.console.UserInterruptException in project accumulo by apache.
the class Shell method execCommand.
public void execCommand(String input, boolean ignoreAuthTimeout, boolean echoPrompt) throws IOException {
audit.log(Level.INFO, getDefaultPrompt() + input);
if (echoPrompt) {
reader.print(getDefaultPrompt());
reader.println(input);
}
if (input.startsWith(COMMENT_PREFIX)) {
return;
}
String[] fields;
try {
fields = new QuotedStringTokenizer(input).getTokens();
} catch (BadArgumentException e) {
printException(e);
++exitCode;
return;
}
if (fields.length == 0)
return;
String command = fields[0];
fields = fields.length > 1 ? Arrays.copyOfRange(fields, 1, fields.length) : new String[] {};
Command sc = null;
if (command.length() > 0) {
try {
// Obtain the command from the command table
sc = commandFactory.get(command);
if (sc == null) {
reader.println(String.format("Unknown command \"%s\". Enter \"help\" for a list possible commands.", command));
reader.flush();
return;
}
long duration = System.nanoTime() - lastUserActivity;
if (!(sc instanceof ExitCommand) && !ignoreAuthTimeout && (duration < 0 || duration > authTimeout)) {
reader.println("Shell has been idle for too long. Please re-authenticate.");
boolean authFailed = true;
do {
String pwd = readMaskedLine("Enter current password for '" + connector.whoami() + "': ", '*');
if (pwd == null) {
reader.println();
return;
}
try {
authFailed = !connector.securityOperations().authenticateUser(connector.whoami(), new PasswordToken(pwd));
} catch (Exception e) {
++exitCode;
printException(e);
}
if (authFailed)
reader.print("Invalid password. ");
} while (authFailed);
lastUserActivity = System.nanoTime();
}
// Get the options from the command on how to parse the string
Options parseOpts = sc.getOptionsWithHelp();
// Parse the string using the given options
CommandLine cl = new BasicParser().parse(parseOpts, fields);
int actualArgLen = cl.getArgs().length;
int expectedArgLen = sc.numArgs();
if (cl.hasOption(helpOption)) {
// Display help if asked to; otherwise execute the command
sc.printHelp(this);
} else if (expectedArgLen != NO_FIXED_ARG_LENGTH_CHECK && actualArgLen != expectedArgLen) {
++exitCode;
// Check for valid number of fixed arguments (if not
// negative; negative means it is not checked, for
// vararg-like commands)
printException(new IllegalArgumentException(String.format("Expected %d argument%s. There %s %d.", expectedArgLen, expectedArgLen == 1 ? "" : "s", actualArgLen == 1 ? "was" : "were", actualArgLen)));
sc.printHelp(this);
} else {
int tmpCode = sc.execute(input, cl, this);
exitCode += tmpCode;
reader.flush();
}
} catch (ConstraintViolationException e) {
++exitCode;
printConstraintViolationException(e);
} catch (TableNotFoundException e) {
++exitCode;
if (getTableName().equals(e.getTableName()))
setTableName("");
printException(e);
} catch (ParseException e) {
// option when the user is asking for help
if (!(e instanceof MissingOptionException && (Arrays.asList(fields).contains("-" + helpOption) || Arrays.asList(fields).contains("--" + helpLongOption)))) {
++exitCode;
printException(e);
}
if (sc != null)
sc.printHelp(this);
} catch (UserInterruptException e) {
++exitCode;
} catch (Exception e) {
++exitCode;
printException(e);
}
} else {
++exitCode;
printException(new BadArgumentException("Unrecognized empty command", command, -1));
}
reader.flush();
}
use of jline.console.UserInterruptException in project accumulo by apache.
the class Shell method start.
public int start() throws IOException {
String input;
if (isVerbose())
printInfo();
String home = System.getProperty("HOME");
if (home == null)
home = System.getenv("HOME");
String configDir = home + "/" + HISTORY_DIR_NAME;
String historyPath = configDir + "/" + HISTORY_FILE_NAME;
File accumuloDir = new File(configDir);
if (!accumuloDir.exists() && !accumuloDir.mkdirs())
log.warn("Unable to make directory for history at " + accumuloDir);
try {
final FileHistory history = new FileHistory(new File(historyPath));
reader.setHistory(history);
// Add shutdown hook to flush file history, per jline javadocs
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
try {
history.flush();
} catch (IOException e) {
log.warn("Could not flush history to file.");
}
}
});
} catch (IOException e) {
log.warn("Unable to load history file at " + historyPath);
}
// Turn Ctrl+C into Exception instead of JVM exit
reader.setHandleUserInterrupt(true);
ShellCompletor userCompletor = null;
if (execFile != null) {
try (java.util.Scanner scanner = new java.util.Scanner(execFile, UTF_8.name())) {
while (scanner.hasNextLine() && !hasExited()) {
execCommand(scanner.nextLine(), true, isVerbose());
}
}
} else if (execCommand != null) {
for (String command : execCommand.split("\n")) {
execCommand(command, true, isVerbose());
}
return exitCode;
}
while (true) {
try {
if (hasExited())
return exitCode;
// If tab completion is true we need to reset
if (tabCompletion) {
if (userCompletor != null)
reader.removeCompleter(userCompletor);
userCompletor = setupCompletion();
reader.addCompleter(userCompletor);
}
reader.setPrompt(getDefaultPrompt());
input = reader.readLine();
if (input == null) {
reader.println();
return exitCode;
}
// User Canceled (Ctrl+D)
execCommand(input, disableAuthTimeout, false);
} catch (UserInterruptException uie) {
// User Cancelled (Ctrl+C)
reader.println();
String partialLine = uie.getPartialLine();
if (partialLine == null || "".equals(uie.getPartialLine().trim())) {
// No content, actually exit
return exitCode;
}
} finally {
reader.flush();
}
}
}
Aggregations