Search in sources :

Example 1 with FileHistory

use of jline.console.history.FileHistory in project ANNIS by korpling.

the class AnnisBaseRunner method runInteractive.

protected void runInteractive() throws IOException {
    System.out.println(helloMessage + " " + VersionInfo.getReleaseName());
    System.out.println();
    System.out.println("Use \"help\" for a list of all commands.");
    System.out.println();
    ConsoleReader console = new ConsoleReader();
    File annisDir = new File(System.getProperty("user.home") + "/.annis/");
    String annisDirPath = annisDir.getAbsolutePath();
    if (!annisDir.exists()) {
        log.info("Creating directory: " + annisDirPath);
        if (!annisDir.mkdirs()) {
            log.warn("Could not create directory: " + annisDirPath);
        }
    } else if (!annisDir.isDirectory()) {
        log.warn("Could not create directory because a file with the same name already exists: " + annisDirPath);
    }
    history = new FileHistory(new File(System.getProperty("user.home") + "/.annis/shellhistory.txt"));
    console.setHistory(history);
    console.setHistoryEnabled(true);
    console.setBellEnabled(true);
    console.setExpandEvents(false);
    List<String> commands = detectAvailableCommands();
    Collections.sort(commands);
    console.addCompleter(new StringsCompleter(commands));
    Splitter argSplitter = Splitter.on(' ').limit(2);
    String line;
    StringBuilder input = new StringBuilder();
    prompt = "no corpus>";
    console.setPrompt(prompt + " ");
    while ((line = console.readLine()) != null) {
        if (line.endsWith("\\")) {
            // multi-line input
            input.append(line.substring(0, line.length() - 1)).append("\n");
            // notifiy user by changing the prompt
            console.setPrompt("> ");
        } else {
            // input finished, run command
            input.append(line);
            ArrayList<String> splitted = Lists.newArrayList(argSplitter.split(input.toString()));
            String command = splitted.get(0);
            String args = "";
            if ("help".equalsIgnoreCase(command)) {
                System.out.println("Available commands:");
                System.out.println(StringUtils.join(commands, "\n"));
            } else {
                if (splitted.size() > 1) {
                    args = splitted.get(1);
                }
            }
            try {
                if (!command.isEmpty()) {
                    runCommand(command, args);
                }
            } catch (UsageException e) {
                error(e);
            }
            // reset the current prompt
            console.setPrompt(prompt + " ");
            // empty input
            input = new StringBuilder();
        }
    }
// end while
}
Also used : Splitter(com.google.common.base.Splitter) ConsoleReader(jline.console.ConsoleReader) StringsCompleter(jline.console.completer.StringsCompleter) File(java.io.File) FileHistory(jline.console.history.FileHistory)

Example 2 with FileHistory

use of jline.console.history.FileHistory in project apex-core by apache.

the class ApexCli method processLine.

protected void processLine(String line, final ConsoleReader reader, boolean expandMacroAlias) {
    try {
        // clear interrupt flag
        Thread.interrupted();
        if (reader.isHistoryEnabled()) {
            History history = reader.getHistory();
            if (history instanceof FileHistory) {
                try {
                    ((FileHistory) history).flush();
                } catch (IOException ex) {
                // ignore
                }
            }
        }
        // LOG.debug("line: \"{}\"", line);
        List<String[]> commands = tokenizer.tokenize(line);
        if (commands == null) {
            return;
        }
        for (final String[] args : commands) {
            if (args.length == 0 || StringUtils.isBlank(args[0])) {
                continue;
            }
            // LOG.debug("Got: {}", mapper.writeValueAsString(args));
            if (expandMacroAlias) {
                if (macros.containsKey(args[0])) {
                    List<String> macroItems = expandMacro(macros.get(args[0]), args);
                    for (String macroItem : macroItems) {
                        if (consolePresent) {
                            System.out.println("expanded-macro> " + macroItem);
                        }
                        processLine(macroItem, reader, false);
                    }
                    continue;
                }
                if (aliases.containsKey(args[0])) {
                    processLine(aliases.get(args[0]), reader, false);
                    continue;
                }
            }
            CommandSpec cs = null;
            if (changingLogicalPlan) {
                cs = logicalPlanChangeCommands.get(args[0]);
            } else {
                if (currentApp != null) {
                    cs = connectedCommands.get(args[0]);
                }
                if (cs == null) {
                    cs = globalCommands.get(args[0]);
                }
            }
            if (cs == null) {
                if (connectedCommands.get(args[0]) != null) {
                    System.err.println("\"" + args[0] + "\" is valid only when connected to an application. Type \"connect <appid>\" to connect to an application.");
                    lastCommandError = true;
                } else if (logicalPlanChangeCommands.get(args[0]) != null) {
                    System.err.println("\"" + args[0] + "\" is valid only when changing a logical plan.  Type \"begin-logical-plan-change\" to change a logical plan");
                    lastCommandError = true;
                } else {
                    System.err.println("Invalid command '" + args[0] + "'. Type \"help\" for list of commands");
                    lastCommandError = true;
                }
            } else {
                try {
                    cs.verifyArguments(args);
                } catch (CliException ex) {
                    cs.printUsage(args[0]);
                    throw ex;
                }
                final Command command = cs.command;
                commandThread = new Thread() {

                    @Override
                    public void run() {
                        try {
                            command.execute(args, reader);
                            lastCommandError = false;
                        } catch (Exception e) {
                            handleException(e);
                        } catch (Error e) {
                            handleException(e);
                            System.err.println("Fatal error encountered");
                            System.exit(1);
                        }
                    }
                };
                mainThread = Thread.currentThread();
                commandThread.start();
                try {
                    commandThread.join();
                } catch (InterruptedException ex) {
                    System.err.println("Interrupted");
                }
                commandThread = null;
            }
        }
    } catch (Exception e) {
        handleException(e);
    }
}
Also used : IOException(java.io.IOException) FileHistory(jline.console.history.FileHistory) MemoryHistory(jline.console.history.MemoryHistory) History(jline.console.history.History) FileHistory(jline.console.history.FileHistory) IOException(java.io.IOException) JSONException(org.codehaus.jettison.json.JSONException) URISyntaxException(java.net.URISyntaxException) FileNotFoundException(java.io.FileNotFoundException) ParseException(org.apache.commons.cli.ParseException) YarnException(org.apache.hadoop.yarn.exceptions.YarnException)

Example 3 with FileHistory

use of jline.console.history.FileHistory in project apex-core by apache.

the class ApexCli method setupHistory.

private void setupHistory(ConsoleReader reader) {
    File historyFile = new File(StramClientUtils.getUserDTDirectory(), "cli_history");
    historyFile.getParentFile().mkdirs();
    try {
        topLevelHistory = new FileHistory(historyFile);
        reader.setHistory(topLevelHistory);
        historyFile = new File(StramClientUtils.getUserDTDirectory(), "cli_history_clp");
        changingLogicalPlanHistory = new FileHistory(historyFile);
    } catch (IOException ex) {
        System.err.printf("Unable to open %s for writing.", historyFile);
    }
}
Also used : IOException(java.io.IOException) File(java.io.File) FileHistory(jline.console.history.FileHistory)

Example 4 with FileHistory

use of jline.console.history.FileHistory in project presto by prestodb.

the class Console method getHistory.

@VisibleForTesting
static MemoryHistory getHistory(File historyFile) {
    MemoryHistory history;
    try {
        // try creating the history file and its parents to check
        // whether the directory tree is readable/writeable
        createParentDirs(historyFile.getParentFile());
        historyFile.createNewFile();
        history = new FileHistory(historyFile);
        history.setMaxSize(10000);
    } catch (IOException e) {
        System.err.printf("WARNING: Failed to load history file (%s): %s. " + "History will not be available during this session.%n", historyFile, e.getMessage());
        history = new MemoryHistory();
    }
    history.setAutoTrim(true);
    return history;
}
Also used : MemoryHistory(jline.console.history.MemoryHistory) IOException(java.io.IOException) FileHistory(jline.console.history.FileHistory) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 5 with FileHistory

use of jline.console.history.FileHistory in project presto by prestodb.

the class TestConsoleHistory method testNonExistingHomeFolder.

@Test
public void testNonExistingHomeFolder() throws Exception {
    File historyFile = new File("/?", ".history");
    assertFalse(historyFile.canRead(), "historyFile is readable");
    assertFalse(historyFile.canWrite(), "historyFile is writable");
    MemoryHistory result = Console.getHistory(historyFile);
    assertNotNull(result, "result is null");
    assertFalse(result instanceof FileHistory, "result type is FileHistory");
}
Also used : MemoryHistory(jline.console.history.MemoryHistory) File(java.io.File) FileHistory(jline.console.history.FileHistory) Test(org.testng.annotations.Test)

Aggregations

FileHistory (jline.console.history.FileHistory)10 File (java.io.File)8 IOException (java.io.IOException)8 MemoryHistory (jline.console.history.MemoryHistory)4 FileNotFoundException (java.io.FileNotFoundException)2 History (jline.console.history.History)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 Splitter (com.google.common.base.Splitter)1 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)1 ActionEvent (java.awt.event.ActionEvent)1 ActionListener (java.awt.event.ActionListener)1 FileInputStream (java.io.FileInputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URISyntaxException (java.net.URISyntaxException)1 SQLException (java.sql.SQLException)1 Nonnull (javax.annotation.Nonnull)1 ConsoleReader (jline.console.ConsoleReader)1 CursorBuffer (jline.console.CursorBuffer)1 KeyMap (jline.console.KeyMap)1 UserInterruptException (jline.console.UserInterruptException)1