Search in sources :

Example 1 with UserInterruptException

use of org.jline.reader.UserInterruptException in project nifi by apache.

the class CLIMain method runInteractiveCLI.

/**
 * Runs the interactive CLI.
 *
 * @throws IOException if an error occurs
 */
private static void runInteractiveCLI() throws IOException {
    // Logger.getLogger("org.jline").setLevel(Level.FINE);
    try (final Terminal terminal = TerminalBuilder.builder().name(SHELL_NAME).system(true).nativeSignals(true).signalHandler(Terminal.SignalHandler.SIG_IGN).build();
        final PrintStream output = new PrintStream(terminal.output(), true)) {
        printHeader(BANNER_FILE, output);
        final Context context = createContext(output, true);
        final Map<String, Command> topLevelCommands = CommandFactory.createTopLevelCommands(context);
        final Map<String, CommandGroup> commandGroups = CommandFactory.createCommandGroups(context);
        final CommandProcessor commandProcessor = new CommandProcessor(topLevelCommands, commandGroups, context);
        final Completer completer = new CLICompleter(topLevelCommands.values(), commandGroups.values());
        final LineReader reader = LineReaderBuilder.builder().appName(SHELL_NAME).terminal(terminal).completer(completer).build();
        reader.setOpt(LineReader.Option.AUTO_FRESH_LINE);
        reader.unsetOpt(LineReader.Option.INSERT_TAB);
        while (true) {
            try {
                final String line = reader.readLine(PROMPT);
                if (StringUtils.isBlank(line)) {
                    continue;
                }
                final ParsedLine parsedLine = reader.getParsedLine();
                final String[] parsedArgs = parsedLine.words().toArray(new String[parsedLine.words().size()]);
                commandProcessor.process(parsedArgs);
            } catch (UserInterruptException e) {
            // Ignore
            } catch (EndOfFileException e) {
                return;
            }
        }
    }
}
Also used : StandardContext(org.apache.nifi.toolkit.cli.impl.context.StandardContext) Context(org.apache.nifi.toolkit.cli.api.Context) PrintStream(java.io.PrintStream) EndOfFileException(org.jline.reader.EndOfFileException) CommandGroup(org.apache.nifi.toolkit.cli.api.CommandGroup) Completer(org.jline.reader.Completer) UserInterruptException(org.jline.reader.UserInterruptException) Terminal(org.jline.terminal.Terminal) Command(org.apache.nifi.toolkit.cli.api.Command) LineReader(org.jline.reader.LineReader) ParsedLine(org.jline.reader.ParsedLine) CommandProcessor(org.apache.nifi.toolkit.cli.impl.command.CommandProcessor)

Example 2 with UserInterruptException

use of org.jline.reader.UserInterruptException in project herddb by diennea.

the class HerdDBCLI method runSqlConsole.

private static void runSqlConsole(Connection connection, Statement statement, boolean pretty) throws IOException {
    Terminal terminal = TerminalBuilder.builder().system(true).build();
    LineReader reader = LineReaderBuilder.builder().history(new DefaultHistory()).terminal(terminal).build();
    String prompt = "herd: ";
    while (true) {
        String line = null;
        try {
            line = reader.readLine(prompt);
            if (line == null) {
                return;
            }
            executeStatement(true, true, false, false, line, statement, null, false, pretty);
        } catch (UserInterruptException | EndOfFileException e) {
            return;
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Also used : EndOfFileException(org.jline.reader.EndOfFileException) LineReader(org.jline.reader.LineReader) DefaultHistory(org.jline.reader.impl.history.DefaultHistory) UserInterruptException(org.jline.reader.UserInterruptException) Terminal(org.jline.terminal.Terminal) ScriptException(javax.script.ScriptException) EndOfFileException(org.jline.reader.EndOfFileException) ParseException(org.apache.commons.cli.ParseException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) UserInterruptException(org.jline.reader.UserInterruptException)

Example 3 with UserInterruptException

use of org.jline.reader.UserInterruptException in project felix by apache.

the class Shell method runShell.

private Object runShell(final CommandSession session, Terminal terminal, LineReader reader) throws InterruptedException {
    AtomicBoolean reading = new AtomicBoolean();
    session.setJobListener((job, previous, current) -> {
        if (previous == Status.Background || current == Status.Background || previous == Status.Suspended || current == Status.Suspended) {
            int width = terminal.getWidth();
            String status = current.name().toLowerCase();
            terminal.writer().write(getStatusLine(job, width, status));
            terminal.flush();
            if (reading.get() && !stopping.get()) {
                reader.callWidget(LineReader.REDRAW_LINE);
                reader.callWidget(LineReader.REDISPLAY);
            }
        }
    });
    SignalHandler intHandler = terminal.handle(Signal.INT, s -> {
        Job current = session.foregroundJob();
        if (current != null) {
            current.interrupt();
        }
    });
    SignalHandler suspHandler = terminal.handle(Signal.TSTP, s -> {
        Job current = session.foregroundJob();
        if (current != null) {
            current.suspend();
        }
    });
    Object result = null;
    try {
        while (!stopping.get()) {
            try {
                reading.set(true);
                try {
                    String prompt = Shell.getPrompt(session);
                    String rprompt = Shell.getRPrompt(session);
                    if (stopping.get()) {
                        break;
                    }
                    reader.readLine(prompt, rprompt, null, null);
                } finally {
                    reading.set(false);
                }
                ParsedLine parsedLine = reader.getParsedLine();
                if (parsedLine == null) {
                    throw new EndOfFileException();
                }
                try {
                    result = session.execute(((ParsedLineImpl) parsedLine).program());
                    // set $_ to last result
                    session.put(Shell.VAR_RESULT, result);
                    if (result != null && !Boolean.FALSE.equals(session.get(".Gogo.format"))) {
                        System.out.println(session.format(result, Converter.INSPECT));
                    }
                } catch (Exception e) {
                    AttributedStringBuilder sb = new AttributedStringBuilder();
                    sb.style(sb.style().foreground(AttributedStyle.RED));
                    sb.append(e.toString());
                    sb.style(sb.style().foregroundDefault());
                    terminal.writer().println(sb.toAnsi(terminal));
                    terminal.flush();
                    session.put(Shell.VAR_EXCEPTION, e);
                }
                waitJobCompletion(session);
            } catch (UserInterruptException e) {
            // continue;
            } catch (EndOfFileException e) {
                reader.getHistory().save();
                break;
            }
        }
    } finally {
        terminal.handle(Signal.INT, intHandler);
        terminal.handle(Signal.TSTP, suspHandler);
    }
    return result;
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EndOfFileException(org.jline.reader.EndOfFileException) ParsedLine(org.jline.reader.ParsedLine) SignalHandler(org.jline.terminal.Terminal.SignalHandler) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) Job(org.apache.felix.service.command.Job) UserInterruptException(org.jline.reader.UserInterruptException) EndOfFileException(org.jline.reader.EndOfFileException) IOException(java.io.IOException) UserInterruptException(org.jline.reader.UserInterruptException)

Example 4 with UserInterruptException

use of org.jline.reader.UserInterruptException in project SpongeVanilla by SpongePowered.

the class MixinConsoleHandler method onRun.

@Inject(method = "run", at = @At("HEAD"), cancellable = true, remap = false)
private void onRun(CallbackInfo ci) {
    final Terminal terminal = TerminalConsoleAppender.getTerminal();
    if (terminal != null) {
        LineReader reader = LineReaderBuilder.builder().appName("SpongeVanilla").terminal(terminal).completer(new ConsoleCommandCompleter(this.server)).build();
        reader.unsetOpt(LineReader.Option.INSERT_TAB);
        TerminalConsoleAppender.setReader(reader);
        try {
            String line;
            while (!this.server.isServerStopped() && this.server.isServerRunning()) {
                try {
                    line = reader.readLine("> ");
                } catch (EndOfFileException e) {
                    // Continue reading after EOT
                    continue;
                }
                if (line == null) {
                    break;
                }
                line = line.trim();
                if (!line.isEmpty()) {
                    this.server.addPendingCommand(line, this.server);
                }
            }
        } catch (UserInterruptException e) {
            this.server.initiateShutdown();
        } finally {
            TerminalConsoleAppender.setReader(null);
        }
        ci.cancel();
    }
}
Also used : ConsoleCommandCompleter(org.spongepowered.server.console.ConsoleCommandCompleter) EndOfFileException(org.jline.reader.EndOfFileException) LineReader(org.jline.reader.LineReader) UserInterruptException(org.jline.reader.UserInterruptException) Terminal(org.jline.terminal.Terminal) Inject(org.spongepowered.asm.mixin.injection.Inject)

Example 5 with UserInterruptException

use of org.jline.reader.UserInterruptException in project batfish by batfish.

the class Client method runInteractive.

private void runInteractive() {
    SignalHandler handler = signal -> _logger.debugf("Client: Ignoring signal: %s\n", signal);
    Signal.handle(new Signal("INT"), handler);
    try {
        while (!_exit) {
            try {
                String rawLine = _reader.readLine("batfish> ");
                if (rawLine == null) {
                    break;
                }
                processCommand(rawLine);
            } catch (UserInterruptException e) {
                continue;
            }
        }
    } catch (EndOfFileException e) {
    // ignored
    } catch (Throwable t) {
        t.printStackTrace();
    } finally {
        try {
            _reader.getHistory().save();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
Also used : Arrays(java.util.Arrays) RunMode(org.batfish.client.config.Settings.RunMode) BfConsts(org.batfish.common.BfConsts) Duration(java.time.Duration) Map(java.util.Map) Signal(sun.misc.Signal) JsonNode(com.fasterxml.jackson.databind.JsonNode) Settings(org.batfish.client.config.Settings) Pair(org.batfish.common.Pair) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) PrintWriter(java.io.PrintWriter) InstanceData(org.batfish.datamodel.questions.Question.InstanceData) LineReader(org.jline.reader.LineReader) Set(java.util.Set) StandardCharsets(java.nio.charset.StandardCharsets) FileVisitResult(java.nio.file.FileVisitResult) WorkItemBuilder(org.batfish.common.util.WorkItemBuilder) EndOfFileException(org.jline.reader.EndOfFileException) Question(org.batfish.datamodel.questions.Question) CoordConsts(org.batfish.common.CoordConsts) AnswerElement(org.batfish.datamodel.answers.AnswerElement) ExceptionUtils(org.apache.commons.lang3.exception.ExceptionUtils) SignalHandler(sun.misc.SignalHandler) Capability(org.jline.utils.InfoCmp.Capability) CommonUtil(org.batfish.common.util.CommonUtil) TreeSet(java.util.TreeSet) Protocol(org.batfish.datamodel.Protocol) AbstractClient(org.batfish.common.plugin.AbstractClient) Nullable(javax.annotation.Nullable) Terminal(org.jline.terminal.Terminal) WorkItem(org.batfish.common.WorkItem) Files(java.nio.file.Files) FOLLOW_LINKS(java.nio.file.FileVisitOption.FOLLOW_LINKS) JSONObject(org.codehaus.jettison.json.JSONObject) IOException(java.io.IOException) JSONArray(org.codehaus.jettison.json.JSONArray) InputStreamReader(java.io.InputStreamReader) ArgumentCompleter(org.jline.reader.impl.completer.ArgumentCompleter) File(java.io.File) AnswerStatus(org.batfish.datamodel.answers.AnswerStatus) TerminalBuilder(org.jline.terminal.TerminalBuilder) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) JSONException(org.codehaus.jettison.json.JSONException) UserInterruptException(org.jline.reader.UserInterruptException) ActiveSpan(io.opentracing.ActiveSpan) BufferedReader(java.io.BufferedReader) Container(org.batfish.common.Container) UnzipUtility(org.batfish.common.util.UnzipUtility) WriterOutputStream(org.apache.commons.io.output.WriterOutputStream) IpProtocol(org.batfish.datamodel.IpProtocol) SortedSet(java.util.SortedSet) LineReaderBuilder(org.jline.reader.LineReaderBuilder) IClient(org.batfish.common.plugin.IClient) Edge(org.batfish.datamodel.Edge) TestComparisonMode(org.batfish.client.Command.TestComparisonMode) LoadQuestionAnswerElement(org.batfish.client.answer.LoadQuestionAnswerElement) HashMultimap(com.google.common.collect.HashMultimap) ReporterConfiguration(com.uber.jaeger.Configuration.ReporterConfiguration) Answer(org.batfish.datamodel.answers.Answer) TypeReference(com.fasterxml.jackson.core.type.TypeReference) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) PatternSyntaxException(java.util.regex.PatternSyntaxException) NullCompleter(org.jline.reader.impl.completer.NullCompleter) UUID(java.util.UUID) Task(org.batfish.common.Task) Sets(com.google.common.collect.Sets) FileNotFoundException(java.io.FileNotFoundException) List(java.util.List) Variable(org.batfish.datamodel.questions.Question.InstanceData.Variable) ConstSampler(com.uber.jaeger.samplers.ConstSampler) Entry(java.util.Map.Entry) JSONTokener(org.codehaus.jettison.json.JSONTokener) WorkStatusCode(org.batfish.common.CoordConsts.WorkStatusCode) JsonSchemaGenerator(com.kjetland.jackson.jsonSchema.JsonSchemaGenerator) Pattern(java.util.regex.Pattern) IpWildcard(org.batfish.datamodel.IpWildcard) BatfishLogger(org.batfish.common.BatfishLogger) Ip(org.batfish.datamodel.Ip) SamplerConfiguration(com.uber.jaeger.Configuration.SamplerConfiguration) NodeInterfacePair(org.batfish.datamodel.collections.NodeInterfacePair) HashMap(java.util.HashMap) BatfishException(org.batfish.common.BatfishException) Multimap(com.google.common.collect.Multimap) HashSet(java.util.HashSet) WorkStatus(org.batfish.datamodel.pojo.WorkStatus) Version(org.batfish.common.Version) BatfishObjectMapper(org.batfish.common.util.BatfishObjectMapper) SubRange(org.batfish.datamodel.SubRange) Configuration(org.batfish.datamodel.Configuration) LinkedList(java.util.LinkedList) Backoff(org.batfish.common.util.Backoff) InitEnvironmentParams(org.batfish.client.params.InitEnvironmentParams) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) ZipUtility(org.batfish.common.util.ZipUtility) PrefixRange(org.batfish.datamodel.PrefixRange) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) FileWriter(java.io.FileWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) GlobalTracer(io.opentracing.util.GlobalTracer) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Batch(org.batfish.common.Task.Batch) Option(org.jline.reader.LineReader.Option) FileReader(java.io.FileReader) Prefix(org.batfish.datamodel.Prefix) Signal(sun.misc.Signal) EndOfFileException(org.jline.reader.EndOfFileException) SignalHandler(sun.misc.SignalHandler) IOException(java.io.IOException) UserInterruptException(org.jline.reader.UserInterruptException)

Aggregations

EndOfFileException (org.jline.reader.EndOfFileException)6 UserInterruptException (org.jline.reader.UserInterruptException)6 LineReader (org.jline.reader.LineReader)5 IOException (java.io.IOException)4 Terminal (org.jline.terminal.Terminal)4 BufferedReader (java.io.BufferedReader)2 InputStreamReader (java.io.InputStreamReader)2 PrintStream (java.io.PrintStream)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 HashMultimap (com.google.common.collect.HashMultimap)1 Multimap (com.google.common.collect.Multimap)1 Sets (com.google.common.collect.Sets)1 JsonSchemaGenerator (com.kjetland.jackson.jsonSchema.JsonSchemaGenerator)1 ReporterConfiguration (com.uber.jaeger.Configuration.ReporterConfiguration)1 SamplerConfiguration (com.uber.jaeger.Configuration.SamplerConfiguration)1 ConstSampler (com.uber.jaeger.samplers.ConstSampler)1 ActiveSpan (io.opentracing.ActiveSpan)1