Search in sources :

Example 16 with LineReader

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

the class TestCLICompleter method setupCompleter.

@BeforeClass
public static void setupCompleter() {
    final Session session = new InMemorySession();
    final ClientFactory<NiFiClient> niFiClientFactory = new NiFiClientFactory();
    final ClientFactory<NiFiRegistryClient> nifiRegClientFactory = new NiFiRegistryClientFactory();
    final Context context = new StandardContext.Builder().output(System.out).session(session).nifiClientFactory(niFiClientFactory).nifiRegistryClientFactory(nifiRegClientFactory).build();
    final Map<String, Command> commands = CommandFactory.createTopLevelCommands(context);
    final Map<String, CommandGroup> commandGroups = CommandFactory.createCommandGroups(context);
    completer = new CLICompleter(commands.values(), commandGroups.values());
    lineReader = Mockito.mock(LineReader.class);
}
Also used : StandardContext(org.apache.nifi.toolkit.cli.impl.context.StandardContext) Context(org.apache.nifi.toolkit.cli.api.Context) NiFiClientFactory(org.apache.nifi.toolkit.cli.impl.client.NiFiClientFactory) NiFiClient(org.apache.nifi.toolkit.cli.impl.client.nifi.NiFiClient) NiFiRegistryClientFactory(org.apache.nifi.toolkit.cli.impl.client.NiFiRegistryClientFactory) NiFiRegistryCommandGroup(org.apache.nifi.toolkit.cli.impl.command.registry.NiFiRegistryCommandGroup) CommandGroup(org.apache.nifi.toolkit.cli.api.CommandGroup) NiFiRegistryClient(org.apache.nifi.registry.client.NiFiRegistryClient) Command(org.apache.nifi.toolkit.cli.api.Command) InMemorySession(org.apache.nifi.toolkit.cli.impl.session.InMemorySession) StandardContext(org.apache.nifi.toolkit.cli.impl.context.StandardContext) LineReader(org.jline.reader.LineReader) Session(org.apache.nifi.toolkit.cli.api.Session) InMemorySession(org.apache.nifi.toolkit.cli.impl.session.InMemorySession) BeforeClass(org.junit.BeforeClass)

Example 17 with LineReader

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

the class Shell method gosh.

public Object gosh(CommandSession currentSession, String[] argv) throws Exception {
    final String[] usage = { "gosh - execute script with arguments in a new session", "  args are available as session variables $1..$9 and $args.", "Usage: gosh [OPTIONS] [script-file [args..]]", "  -c --command             pass all remaining args to sub-shell", "     --nointeractive       don't start interactive session", "     --nohistory           don't save the command history", "     --login               login shell (same session, reads etc/gosh_profile)", "  -s --noshutdown          don't shutdown framework when script completes", "  -x --xtrace              echo commands before execution", "  -? --help                show help", "If no script-file, an interactive shell is started, type $D to exit." };
    Options opt = Options.compile(usage).setOptionsFirst(true).parse(argv);
    List<String> args = opt.args();
    boolean login = opt.isSet("login");
    boolean interactive = !opt.isSet("nointeractive");
    if (opt.isSet("help")) {
        opt.usage(System.err);
        if (login && !opt.isSet("noshutdown")) {
            shutdown();
        }
        return null;
    }
    if (opt.isSet("command") && args.isEmpty()) {
        throw opt.usageError("option --command requires argument(s)");
    }
    CommandSession session;
    if (login) {
        session = currentSession;
    } else {
        session = createChildSession(currentSession);
    }
    if (opt.isSet("xtrace")) {
        session.put("echo", true);
    }
    Terminal terminal = getTerminal(session);
    session.put(Shell.VAR_CONTEXT, context);
    session.put(Shell.VAR_PROCESSOR, processor);
    session.put(Shell.VAR_SESSION, session);
    session.put("#TERM", (Function) (s, arguments) -> terminal.getType());
    session.put("#COLUMNS", (Function) (s, arguments) -> terminal.getWidth());
    session.put("#LINES", (Function) (s, arguments) -> terminal.getHeight());
    session.put("#PWD", (Function) (s, arguments) -> s.currentDir().toString());
    if (!opt.isSet("nohistory")) {
        session.put(LineReader.HISTORY_FILE, Paths.get(System.getProperty("user.home"), ".gogo.history"));
    }
    if (tio != null) {
        PrintWriter writer = terminal.writer();
        PrintStream out = new PrintStream(new OutputStream() {

            @Override
            public void write(int b) throws IOException {
                write(new byte[] { (byte) b }, 0, 1);
            }

            public void write(byte[] b, int off, int len) throws IOException {
                writer.write(new String(b, off, len));
            }

            public void flush() throws IOException {
                writer.flush();
            }

            public void close() throws IOException {
                writer.close();
            }
        });
        tio.setStreams(terminal.input(), out, out);
    }
    try {
        LineReader reader;
        if (args.isEmpty() && interactive) {
            CompletionEnvironment completionEnvironment = new CompletionEnvironment() {

                @Override
                public Map<String, List<CompletionData>> getCompletions() {
                    return Shell.getCompletions(session);
                }

                @Override
                public Set<String> getCommands() {
                    return Shell.getCommands(session);
                }

                @Override
                public String resolveCommand(String command) {
                    return Shell.resolve(session, command);
                }

                @Override
                public String commandName(String command) {
                    int idx = command.indexOf(':');
                    return idx >= 0 ? command.substring(idx + 1) : command;
                }

                @Override
                public Object evaluate(LineReader reader, ParsedLine line, String func) throws Exception {
                    session.put(Shell.VAR_COMMAND_LINE, line);
                    return session.execute(func);
                }
            };
            reader = LineReaderBuilder.builder().terminal(terminal).variables(((CommandSessionImpl) session).getVariables()).completer(new org.jline.builtins.Completers.Completer(completionEnvironment)).highlighter(new Highlighter(session)).parser(new Parser()).expander(new Expander(session)).build();
            reader.setOpt(LineReader.Option.AUTO_FRESH_LINE);
            session.put(Shell.VAR_READER, reader);
            session.put(Shell.VAR_COMPLETIONS, new HashMap());
        } else {
            reader = null;
        }
        if (login || interactive) {
            URI uri = baseURI.resolve("etc/" + profile);
            if (!new File(uri).exists()) {
                URL url = getClass().getResource("/ext/" + profile);
                if (url == null) {
                    url = getClass().getResource("/" + profile);
                }
                uri = (url == null) ? null : url.toURI();
            }
            if (uri != null) {
                source(session, uri.toString());
            }
        }
        Object result = null;
        if (args.isEmpty()) {
            if (interactive) {
                result = runShell(session, terminal, reader);
            }
        } else {
            CharSequence program;
            if (opt.isSet("command")) {
                StringBuilder buf = new StringBuilder();
                for (String arg : args) {
                    if (buf.length() > 0) {
                        buf.append(' ');
                    }
                    buf.append(arg);
                }
                program = buf;
            } else {
                URI script = session.currentDir().toUri().resolve(args.remove(0));
                // set script arguments
                session.put("0", script);
                session.put("args", args);
                for (int i = 0; i < args.size(); ++i) {
                    session.put(String.valueOf(i + 1), args.get(i));
                }
                program = readScript(script);
            }
            result = session.execute(program);
        }
        if (login && interactive && !opt.isSet("noshutdown")) {
            if (terminal != null) {
                terminal.writer().println("gosh: stopping framework");
                terminal.flush();
            }
            shutdown();
        }
        return result;
    } finally {
        if (tio != null) {
            tio.close();
        }
    }
}
Also used : Job(org.apache.felix.service.command.Job) LineReaderBuilder(org.jline.reader.LineReaderBuilder) URL(java.net.URL) Status(org.apache.felix.service.command.Job.Status) Descriptor(org.apache.felix.service.command.Descriptor) CommandSession(org.apache.felix.service.command.CommandSession) ParsedLine(org.jline.reader.ParsedLine) Map(java.util.Map) CommandProxy(org.apache.felix.gogo.runtime.CommandProxy) URI(java.net.URI) Method(java.lang.reflect.Method) Options(org.jline.builtins.Options) PrintWriter(java.io.PrintWriter) LineReader(org.jline.reader.LineReader) CharBuffer(java.nio.CharBuffer) Set(java.util.Set) Reader(java.io.Reader) CompletionEnvironment(org.jline.builtins.Completers.CompletionEnvironment) List(java.util.List) EndOfFileException(org.jline.reader.EndOfFileException) Annotation(java.lang.annotation.Annotation) Entry(java.util.Map.Entry) Function(org.apache.felix.service.command.Function) CommandSessionImpl(org.apache.felix.gogo.runtime.CommandSessionImpl) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SignalHandler(org.jline.terminal.Terminal.SignalHandler) CompletionData(org.jline.builtins.Completers.CompletionData) URLConnection(java.net.URLConnection) Reflective(org.apache.felix.gogo.runtime.Reflective) Terminal(org.jline.terminal.Terminal) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) Parameter(org.apache.felix.service.command.Parameter) Closure(org.apache.felix.gogo.runtime.Closure) CommandProcessor(org.apache.felix.service.command.CommandProcessor) Iterator(java.util.Iterator) AttributedStyle(org.jline.utils.AttributedStyle) IOException(java.io.IOException) Field(java.lang.reflect.Field) InputStreamReader(java.io.InputStreamReader) File(java.io.File) ThreadIO(org.apache.felix.service.threadio.ThreadIO) Converter(org.apache.felix.service.command.Converter) TreeMap(java.util.TreeMap) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) Paths(java.nio.file.Paths) Signal(org.jline.terminal.Terminal.Signal) UserInterruptException(org.jline.reader.UserInterruptException) InputStream(java.io.InputStream) Options(org.jline.builtins.Options) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) URI(java.net.URI) URL(java.net.URL) LineReader(org.jline.reader.LineReader) ParsedLine(org.jline.reader.ParsedLine) List(java.util.List) ArrayList(java.util.ArrayList) PrintWriter(java.io.PrintWriter) PrintStream(java.io.PrintStream) IOException(java.io.IOException) CompletionEnvironment(org.jline.builtins.Completers.CompletionEnvironment) Terminal(org.jline.terminal.Terminal) CommandSession(org.apache.felix.service.command.CommandSession) File(java.io.File)

Example 18 with LineReader

use of org.jline.reader.LineReader 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 19 with LineReader

use of org.jline.reader.LineReader in project Payara by payara.

the class AsadminTrustManager method isItOKToAddCertToTrustStore.

/**
 * Displays the certificate and prompts the user whether or
 * not it is trusted.
 * @param c
 * @throws IOException
 * @return true if the user trusts the certificate
 */
private boolean isItOKToAddCertToTrustStore(X509Certificate c) {
    if (!interactive) {
        return true;
    }
    String result = null;
    LineReader lineReader = null;
    try {
        lineReader = LineReaderBuilder.builder().terminal(new DumbTerminal(System.in, System.out)).build();
        result = lineReader.readLine(STRING_MANAGER.get("certificateTrustPrompt"));
    } catch (IOException ioe) {
        logger.log(Level.WARNING, "Error instantiating console", ioe);
    } finally {
        if (lineReader != null && lineReader.getTerminal() != null) {
            try {
                lineReader.getTerminal().close();
            } catch (IOException ioe) {
                logger.log(Level.WARNING, "Error closing terminal", ioe);
            }
        }
    }
    return result != null && result.equalsIgnoreCase("y");
}
Also used : LineReader(org.jline.reader.LineReader) IOException(java.io.IOException) DumbTerminal(org.jline.terminal.impl.DumbTerminal)

Example 20 with LineReader

use of org.jline.reader.LineReader in project Payara by payara.

the class AsadminSecurityUtil method promptForPassword.

/**
 * If we fail to open the client database using the default password
 * (changeit) or the password found in  "javax.net.ssl.trustStorePassword"
 * system property, then the fallback behavior is to prompt the user for
 * the password by calling this method.
 * @return the password to the client side truststore
 */
private char[] promptForPassword() {
    LineReader lineReader = null;
    try {
        char mask = 0;
        Terminal terminal = TerminalBuilder.builder().system(true).build();
        lineReader = LineReaderBuilder.builder().terminal(terminal).build();
        String line = lineReader.readLine(strmgr.get("certificateDbPrompt"), mask);
        return line.toCharArray();
    } catch (IOException ioe) {
        logger.log(Level.WARNING, "Error reading input", ioe);
    } catch (UserInterruptException | EndOfFileException e) {
    // Ignore
    } finally {
        if (lineReader != null && lineReader.getTerminal() != null) {
            try {
                lineReader.getTerminal().close();
            } catch (IOException ioe) {
                logger.log(Level.WARNING, "Error closing terminal", ioe);
            }
        }
    }
    return null;
}
Also used : EndOfFileException(org.jline.reader.EndOfFileException) LineReader(org.jline.reader.LineReader) UserInterruptException(org.jline.reader.UserInterruptException) Terminal(org.jline.terminal.Terminal)

Aggregations

LineReader (org.jline.reader.LineReader)27 Terminal (org.jline.terminal.Terminal)15 EndOfFileException (org.jline.reader.EndOfFileException)10 UserInterruptException (org.jline.reader.UserInterruptException)10 IOException (java.io.IOException)7 AccumuloClient (org.apache.accumulo.core.client.AccumuloClient)5 Shell (org.apache.accumulo.shell.Shell)5 PrintWriter (java.io.PrintWriter)4 ArrayList (java.util.ArrayList)4 SecurityOperations (org.apache.accumulo.core.client.admin.SecurityOperations)4 CommandLine (org.apache.commons.cli.CommandLine)4 ParsedLine (org.jline.reader.ParsedLine)4 Test (org.junit.Test)4 PrintStream (java.io.PrintStream)3 Authorizations (org.apache.accumulo.core.security.Authorizations)3 Candidate (org.jline.reader.Candidate)3 File (java.io.File)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 InputStreamReader (java.io.InputStreamReader)2