Search in sources :

Example 1 with UserInterruptException

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;
}
Also used : OutputStream(java.io.OutputStream) PrintWriter(java.io.PrintWriter) History(jline.console.history.History) ActionListener(java.awt.event.ActionListener) PolyglotException(org.graalvm.polyglot.PolyglotException) MemoryHistory(jline.console.history.MemoryHistory) UserInterruptException(jline.console.UserInterruptException) Set(java.util.Set) IOException(java.io.IOException) HashMap(java.util.HashMap) ActionEvent(java.awt.event.ActionEvent) EOFException(java.io.EOFException) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) List(java.util.List) ConsoleReader(jline.console.ConsoleReader) Language(org.graalvm.polyglot.Language) Map(java.util.Map) Source(org.graalvm.polyglot.Source) Context(org.graalvm.polyglot.Context) Comparator(java.util.Comparator) NonBlockingInputStream(jline.internal.NonBlockingInputStream) InputStream(java.io.InputStream) HashMap(java.util.HashMap) ActionEvent(java.awt.event.ActionEvent) ArrayList(java.util.ArrayList) NonBlockingInputStream(jline.internal.NonBlockingInputStream) UserInterruptException(jline.console.UserInterruptException) History(jline.console.history.History) MemoryHistory(jline.console.history.MemoryHistory) Source(org.graalvm.polyglot.Source) Language(org.graalvm.polyglot.Language) EOFException(java.io.EOFException) HashSet(java.util.HashSet) PrintWriter(java.io.PrintWriter) ConsoleReader(jline.console.ConsoleReader) MemoryHistory(jline.console.history.MemoryHistory) PolyglotException(org.graalvm.polyglot.PolyglotException) ActionListener(java.awt.event.ActionListener)

Example 2 with UserInterruptException

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();
}
Also used : BadArgumentException(org.apache.accumulo.core.util.BadArgumentException) Options(org.apache.commons.cli.Options) ExitCommand(org.apache.accumulo.shell.commands.ExitCommand) UserInterruptException(jline.console.UserInterruptException) UserInterruptException(jline.console.UserInterruptException) TableNotFoundException(org.apache.accumulo.core.client.TableNotFoundException) NamespaceNotFoundException(org.apache.accumulo.core.client.NamespaceNotFoundException) FileSystemException(org.apache.commons.vfs2.FileSystemException) BadArgumentException(org.apache.accumulo.core.util.BadArgumentException) ConfigurationException(org.apache.commons.configuration.ConfigurationException) ConstraintViolationException(org.apache.accumulo.core.tabletserver.thrift.ConstraintViolationException) IOException(java.io.IOException) MissingOptionException(org.apache.commons.cli.MissingOptionException) ParameterException(com.beust.jcommander.ParameterException) FileNotFoundException(java.io.FileNotFoundException) ParseException(org.apache.commons.cli.ParseException) AccumuloSecurityException(org.apache.accumulo.core.client.AccumuloSecurityException) AccumuloException(org.apache.accumulo.core.client.AccumuloException) BasicParser(org.apache.commons.cli.BasicParser) TableNotFoundException(org.apache.accumulo.core.client.TableNotFoundException) PasswordToken(org.apache.accumulo.core.client.security.tokens.PasswordToken) CommandLine(org.apache.commons.cli.CommandLine) QuotedStringTokenizer(org.apache.accumulo.shell.commands.QuotedStringTokenizer) WhoAmICommand(org.apache.accumulo.shell.commands.WhoAmICommand) SetAuthsCommand(org.apache.accumulo.shell.commands.SetAuthsCommand) InsertCommand(org.apache.accumulo.shell.commands.InsertCommand) SystemPermissionsCommand(org.apache.accumulo.shell.commands.SystemPermissionsCommand) CreateNamespaceCommand(org.apache.accumulo.shell.commands.CreateNamespaceCommand) CloneTableCommand(org.apache.accumulo.shell.commands.CloneTableCommand) DropTableCommand(org.apache.accumulo.shell.commands.DropTableCommand) CreateTableCommand(org.apache.accumulo.shell.commands.CreateTableCommand) DUCommand(org.apache.accumulo.shell.commands.DUCommand) DeleteAuthsCommand(org.apache.accumulo.shell.commands.DeleteAuthsCommand) CreateUserCommand(org.apache.accumulo.shell.commands.CreateUserCommand) InterpreterCommand(org.apache.accumulo.shell.commands.InterpreterCommand) SetIterCommand(org.apache.accumulo.shell.commands.SetIterCommand) OfflineCommand(org.apache.accumulo.shell.commands.OfflineCommand) ScanCommand(org.apache.accumulo.shell.commands.ScanCommand) TablePermissionsCommand(org.apache.accumulo.shell.commands.TablePermissionsCommand) UserCommand(org.apache.accumulo.shell.commands.UserCommand) GetGroupsCommand(org.apache.accumulo.shell.commands.GetGroupsCommand) DeleteTableCommand(org.apache.accumulo.shell.commands.DeleteTableCommand) DeleteUserCommand(org.apache.accumulo.shell.commands.DeleteUserCommand) AddAuthsCommand(org.apache.accumulo.shell.commands.AddAuthsCommand) ListBulkCommand(org.apache.accumulo.shell.commands.ListBulkCommand) TablesCommand(org.apache.accumulo.shell.commands.TablesCommand) AuthenticateCommand(org.apache.accumulo.shell.commands.AuthenticateCommand) HistoryCommand(org.apache.accumulo.shell.commands.HistoryCommand) SummariesCommand(org.apache.accumulo.shell.commands.SummariesCommand) SetScanIterCommand(org.apache.accumulo.shell.commands.SetScanIterCommand) SleepCommand(org.apache.accumulo.shell.commands.SleepCommand) ImportTableCommand(org.apache.accumulo.shell.commands.ImportTableCommand) DropUserCommand(org.apache.accumulo.shell.commands.DropUserCommand) FormatterCommand(org.apache.accumulo.shell.commands.FormatterCommand) ExecfileCommand(org.apache.accumulo.shell.commands.ExecfileCommand) InfoCommand(org.apache.accumulo.shell.commands.InfoCommand) ConstraintCommand(org.apache.accumulo.shell.commands.ConstraintCommand) DebugCommand(org.apache.accumulo.shell.commands.DebugCommand) DeleteManyCommand(org.apache.accumulo.shell.commands.DeleteManyCommand) DeleteShellIterCommand(org.apache.accumulo.shell.commands.DeleteShellIterCommand) CompactCommand(org.apache.accumulo.shell.commands.CompactCommand) GetSplitsCommand(org.apache.accumulo.shell.commands.GetSplitsCommand) DeleteScanIterCommand(org.apache.accumulo.shell.commands.DeleteScanIterCommand) FateCommand(org.apache.accumulo.shell.commands.FateCommand) HelpCommand(org.apache.accumulo.shell.commands.HelpCommand) GrantCommand(org.apache.accumulo.shell.commands.GrantCommand) ConfigCommand(org.apache.accumulo.shell.commands.ConfigCommand) ExitCommand(org.apache.accumulo.shell.commands.ExitCommand) RenameNamespaceCommand(org.apache.accumulo.shell.commands.RenameNamespaceCommand) AboutCommand(org.apache.accumulo.shell.commands.AboutCommand) DeleteCommand(org.apache.accumulo.shell.commands.DeleteCommand) SetGroupsCommand(org.apache.accumulo.shell.commands.SetGroupsCommand) UserPermissionsCommand(org.apache.accumulo.shell.commands.UserPermissionsCommand) SetShellIterCommand(org.apache.accumulo.shell.commands.SetShellIterCommand) ScriptCommand(org.apache.accumulo.shell.commands.ScriptCommand) ImportDirectoryCommand(org.apache.accumulo.shell.commands.ImportDirectoryCommand) OnlineCommand(org.apache.accumulo.shell.commands.OnlineCommand) ListScansCommand(org.apache.accumulo.shell.commands.ListScansCommand) DeleteRowsCommand(org.apache.accumulo.shell.commands.DeleteRowsCommand) PasswdCommand(org.apache.accumulo.shell.commands.PasswdCommand) ExtensionCommand(org.apache.accumulo.shell.commands.ExtensionCommand) MaxRowCommand(org.apache.accumulo.shell.commands.MaxRowCommand) ByeCommand(org.apache.accumulo.shell.commands.ByeCommand) GrepCommand(org.apache.accumulo.shell.commands.GrepCommand) MergeCommand(org.apache.accumulo.shell.commands.MergeCommand) NoTableCommand(org.apache.accumulo.shell.commands.NoTableCommand) ListCompactionsCommand(org.apache.accumulo.shell.commands.ListCompactionsCommand) PingCommand(org.apache.accumulo.shell.commands.PingCommand) ClsCommand(org.apache.accumulo.shell.commands.ClsCommand) ListIterCommand(org.apache.accumulo.shell.commands.ListIterCommand) DeleteIterCommand(org.apache.accumulo.shell.commands.DeleteIterCommand) GetAuthsCommand(org.apache.accumulo.shell.commands.GetAuthsCommand) TraceCommand(org.apache.accumulo.shell.commands.TraceCommand) RenameTableCommand(org.apache.accumulo.shell.commands.RenameTableCommand) NamespacePermissionsCommand(org.apache.accumulo.shell.commands.NamespacePermissionsCommand) UsersCommand(org.apache.accumulo.shell.commands.UsersCommand) DeleteNamespaceCommand(org.apache.accumulo.shell.commands.DeleteNamespaceCommand) TableCommand(org.apache.accumulo.shell.commands.TableCommand) ClearCommand(org.apache.accumulo.shell.commands.ClearCommand) HiddenCommand(org.apache.accumulo.shell.commands.HiddenCommand) FlushCommand(org.apache.accumulo.shell.commands.FlushCommand) ExportTableCommand(org.apache.accumulo.shell.commands.ExportTableCommand) ClasspathCommand(org.apache.accumulo.shell.commands.ClasspathCommand) RevokeCommand(org.apache.accumulo.shell.commands.RevokeCommand) ListShellIterCommand(org.apache.accumulo.shell.commands.ListShellIterCommand) QuitCommand(org.apache.accumulo.shell.commands.QuitCommand) EGrepCommand(org.apache.accumulo.shell.commands.EGrepCommand) AddSplitsCommand(org.apache.accumulo.shell.commands.AddSplitsCommand) NamespacesCommand(org.apache.accumulo.shell.commands.NamespacesCommand) QuestionCommand(org.apache.accumulo.shell.commands.QuestionCommand) ConstraintViolationException(org.apache.accumulo.core.tabletserver.thrift.ConstraintViolationException) ParseException(org.apache.commons.cli.ParseException) MissingOptionException(org.apache.commons.cli.MissingOptionException)

Example 3 with UserInterruptException

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();
        }
    }
}
Also used : IOException(java.io.IOException) UserInterruptException(jline.console.UserInterruptException) File(java.io.File) FileHistory(jline.console.history.FileHistory)

Aggregations

IOException (java.io.IOException)3 UserInterruptException (jline.console.UserInterruptException)3 ParameterException (com.beust.jcommander.ParameterException)1 ActionEvent (java.awt.event.ActionEvent)1 ActionListener (java.awt.event.ActionListener)1 EOFException (java.io.EOFException)1 File (java.io.File)1 FileNotFoundException (java.io.FileNotFoundException)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 PrintWriter (java.io.PrintWriter)1 ArrayList (java.util.ArrayList)1 Comparator (java.util.Comparator)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 List (java.util.List)1 Map (java.util.Map)1 Set (java.util.Set)1 ConsoleReader (jline.console.ConsoleReader)1 FileHistory (jline.console.history.FileHistory)1