Search in sources :

Example 1 with Terminal

use of org.jline.terminal.Terminal in project felix by apache.

the class Activator method startShell.

private Runnable startShell(BundleContext context, CommandProcessor processor) throws Exception {
    Dictionary<String, Object> dict = new Hashtable<>();
    dict.put(CommandProcessor.COMMAND_SCOPE, "gogo");
    // register converters
    regs.add(context.registerService(Converter.class.getName(), new Converters(context.getBundle(0).getBundleContext()), null));
    // register commands
    dict.put(CommandProcessor.COMMAND_FUNCTION, Builtin.functions);
    regs.add(context.registerService(Builtin.class.getName(), new Builtin(), dict));
    dict.put(CommandProcessor.COMMAND_FUNCTION, Procedural.functions);
    regs.add(context.registerService(Procedural.class.getName(), new Procedural(), dict));
    dict.put(CommandProcessor.COMMAND_FUNCTION, Posix.functions);
    regs.add(context.registerService(Posix.class.getName(), new Posix(processor), dict));
    Shell shell = new Shell(new ShellContext(), processor);
    dict.put(CommandProcessor.COMMAND_FUNCTION, Shell.functions);
    regs.add(context.registerService(Shell.class.getName(), shell, dict));
    Terminal terminal = TerminalBuilder.builder().name("gogo").system(true).nativeSignals(true).signalHandler(Terminal.SignalHandler.SIG_IGN).build();
    CommandSession session = processor.createSession(terminal.input(), terminal.output(), terminal.output());
    AtomicBoolean closing = new AtomicBoolean();
    Thread thread = new Thread(() -> {
        String errorMessage = "gogo: unable to create console";
        try {
            session.put(Shell.VAR_TERMINAL, terminal);
            try {
                List<String> args = new ArrayList<>();
                args.add("--login");
                String argstr = shell.getContext().getProperty("gosh.args");
                if (argstr != null) {
                    Tokenizer tokenizer = new Tokenizer(argstr);
                    Token token;
                    while ((token = tokenizer.next()) != null) {
                        args.add(token.toString());
                    }
                }
                shell.gosh(session, args.toArray(new String[args.size()]));
            } catch (Throwable e) {
                Object loc = session.get(".location");
                if (null == loc || !loc.toString().contains(":")) {
                    loc = "gogo";
                }
                errorMessage = loc.toString();
                throw e;
            }
        } catch (Throwable e) {
            if (!closing.get()) {
                System.err.println(errorMessage + e.getClass().getSimpleName() + ": " + e.getMessage());
                e.printStackTrace();
            }
        }
    }, "Gogo shell");
    // start shell on a separate thread...
    thread.start();
    return () -> {
        closing.set(true);
        shell.stop();
        try {
            terminal.close();
        } catch (IOException e) {
        // Ignore
        }
        try {
            long t0 = System.currentTimeMillis();
            while (thread.isAlive()) {
                thread.interrupt();
                thread.join(10);
                if (System.currentTimeMillis() - t0 > 5000) {
                    System.err.println("!!! FAILED TO STOP EXECUTOR !!!");
                    break;
                }
            }
        } catch (InterruptedException e) {
            // Restore administration...
            Thread.currentThread().interrupt();
        }
    };
}
Also used : Hashtable(java.util.Hashtable) ArrayList(java.util.ArrayList) Token(org.apache.felix.gogo.runtime.Token) IOException(java.io.IOException) Terminal(org.jline.terminal.Terminal) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CommandSession(org.apache.felix.service.command.CommandSession) Tokenizer(org.apache.felix.gogo.runtime.Tokenizer)

Example 2 with Terminal

use of org.jline.terminal.Terminal in project felix by apache.

the class Builtin method __files.

public List<Candidate> __files(CommandSession session) {
    ParsedLine line = Shell.getParsedLine(session);
    LineReader reader = Shell.getReader(session);
    List<Candidate> candidates = new ArrayList<>();
    new FilesCompleter(session.currentDir()) {

        @Override
        protected String getDisplay(Terminal terminal, Path p) {
            return getFileDisplay(session, p);
        }
    }.complete(reader, line, candidates);
    return candidates;
}
Also used : Candidate(org.jline.reader.Candidate) Path(java.nio.file.Path) ParsedLine(org.jline.reader.ParsedLine) LineReader(org.jline.reader.LineReader) ArrayList(java.util.ArrayList) FilesCompleter(org.jline.builtins.Completers.FilesCompleter) Terminal(org.jline.terminal.Terminal)

Example 3 with Terminal

use of org.jline.terminal.Terminal in project felix by apache.

the class Builtin method __directories.

public List<Candidate> __directories(CommandSession session) {
    ParsedLine line = Shell.getParsedLine(session);
    LineReader reader = Shell.getReader(session);
    List<Candidate> candidates = new ArrayList<>();
    new DirectoriesCompleter(session.currentDir()) {

        @Override
        protected String getDisplay(Terminal terminal, Path p) {
            return getFileDisplay(session, p);
        }
    }.complete(reader, line, candidates);
    return candidates;
}
Also used : Candidate(org.jline.reader.Candidate) Path(java.nio.file.Path) DirectoriesCompleter(org.jline.builtins.Completers.DirectoriesCompleter) ParsedLine(org.jline.reader.ParsedLine) LineReader(org.jline.reader.LineReader) ArrayList(java.util.ArrayList) Terminal(org.jline.terminal.Terminal)

Example 4 with Terminal

use of org.jline.terminal.Terminal in project felix by apache.

the class Posix method less.

protected void less(CommandSession session, Process process, String[] argv) throws Exception {
    String[] usage = { "less -  file pager", "Usage: less [OPTIONS] [FILES]", "  -? --help                    Show help", "  -e --quit-at-eof             Exit on second EOF", "  -E --QUIT-AT-EOF             Exit on EOF", "  -F --quit-if-one-screen      Exit if entire file fits on first screen", "  -q --quiet --silent          Silent mode", "  -Q --QUIET --SILENT          Completely  silent", "  -S --chop-long-lines         Do not fold long lines", "  -i --ignore-case             Search ignores lowercase case", "  -I --IGNORE-CASE             Search ignores all case", "  -x --tabs                    Set tab stops", "  -N --LINE-NUMBERS            Display line number for each line", "     --no-init                 Disable terminal initialization", "     --no-keypad               Disable keypad handling" };
    boolean hasExtendedOptions = false;
    try {
        Less.class.getField("quitIfOneScreen");
        hasExtendedOptions = true;
    } catch (NoSuchFieldException e) {
        List<String> ustrs = new ArrayList<>(Arrays.asList(usage));
        ustrs.removeIf(s -> s.contains("--quit-if-one-screen") || s.contains("--no-init") || s.contains("--no-keypad"));
        usage = ustrs.toArray(new String[ustrs.size()]);
    }
    Options opt = parseOptions(session, usage, argv);
    List<Source> sources = new ArrayList<>();
    if (opt.args().isEmpty()) {
        opt.args().add("-");
    }
    for (String arg : opt.args()) {
        if ("-".equals(arg)) {
            sources.add(new StdInSource(process));
        } else {
            sources.add(new PathSource(session.currentDir().resolve(arg), arg));
        }
    }
    if (!process.isTty(1)) {
        for (Source source : sources) {
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(source.read()))) {
                cat(process, reader, opt.isSet("LINE-NUMBERS"));
            }
        }
        return;
    }
    Less less = new Less(Shell.getTerminal(session));
    less.quitAtFirstEof = opt.isSet("QUIT-AT-EOF");
    less.quitAtSecondEof = opt.isSet("quit-at-eof");
    less.quiet = opt.isSet("quiet");
    less.veryQuiet = opt.isSet("QUIET");
    less.chopLongLines = opt.isSet("chop-long-lines");
    less.ignoreCaseAlways = opt.isSet("IGNORE-CASE");
    less.ignoreCaseCond = opt.isSet("ignore-case");
    if (opt.isSet("tabs")) {
        less.tabs = opt.getNumber("tabs");
    }
    less.printLineNumbers = opt.isSet("LINE-NUMBERS");
    if (hasExtendedOptions) {
        Less.class.getField("quitIfOneScreen").set(less, opt.isSet("quit-if-one-screen"));
        Less.class.getField("noInit").set(less, opt.isSet("no-init"));
        Less.class.getField("noKeypad").set(less, opt.isSet("no-keypad"));
    }
    less.run(sources);
}
Also used : Arrays(java.util.Arrays) PathSource(org.jline.builtins.Source.PathSource) Date(java.util.Date) ZonedDateTime(java.time.ZonedDateTime) IntConsumer(java.util.function.IntConsumer) FileTime(java.nio.file.attribute.FileTime) IntBinaryOperator(java.util.function.IntBinaryOperator) CommandSession(org.apache.felix.service.command.CommandSession) AttributedString(org.jline.utils.AttributedString) WatchKey(java.nio.file.WatchKey) Matcher(java.util.regex.Matcher) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Context(org.apache.felix.gogo.jline.Shell.Context) Path(java.nio.file.Path) EnumSet(java.util.EnumSet) Options(org.jline.builtins.Options) TTop(org.jline.builtins.TTop) PosixFilePermission(java.nio.file.attribute.PosixFilePermission) Predicate(java.util.function.Predicate) Set(java.util.Set) Source(org.jline.builtins.Source) Reader(java.io.Reader) Instant(java.time.Instant) OSUtils(org.jline.utils.OSUtils) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) List(java.util.List) Stream(java.util.stream.Stream) Pattern(java.util.regex.Pattern) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Capability(org.jline.utils.InfoCmp.Capability) Commands(org.jline.builtins.Commands) SimpleDateFormat(java.text.SimpleDateFormat) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Attributes(org.jline.terminal.Attributes) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Process(org.apache.felix.service.command.Process) LinkOption(java.nio.file.LinkOption) FilterInputStream(java.io.FilterInputStream) StandardWatchEventKinds(java.nio.file.StandardWatchEventKinds) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) Nano(org.jline.builtins.Nano) Terminal(org.jline.terminal.Terminal) OutputStream(java.io.OutputStream) PrintStream(java.io.PrintStream) CommandProcessor(org.apache.felix.service.command.CommandProcessor) AttributedStyle(org.jline.utils.AttributedStyle) Files(java.nio.file.Files) IOException(java.io.IOException) InputStreamReader(java.io.InputStreamReader) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) WatchService(java.nio.file.WatchService) TreeMap(java.util.TreeMap) AttributedStringBuilder(org.jline.utils.AttributedStringBuilder) Closeable(java.io.Closeable) DateTimeFormatter(java.time.format.DateTimeFormatter) BufferedReader(java.io.BufferedReader) Comparator(java.util.Comparator) Less(org.jline.builtins.Less) Collections(java.util.Collections) InputStream(java.io.InputStream) Options(org.jline.builtins.Options) InputStreamReader(java.io.InputStreamReader) PathSource(org.jline.builtins.Source.PathSource) ArrayList(java.util.ArrayList) AttributedString(org.jline.utils.AttributedString) PathSource(org.jline.builtins.Source.PathSource) Source(org.jline.builtins.Source) BufferedReader(java.io.BufferedReader) List(java.util.List) ArrayList(java.util.ArrayList) Less(org.jline.builtins.Less)

Example 5 with Terminal

use of org.jline.terminal.Terminal in project felix by apache.

the class Telnet method start.

private void start(CommandSession session) throws IOException {
    ConnectionManager connectionManager = new ConnectionManager(1000, 5 * 60 * 1000, 5 * 60 * 1000, 60 * 1000, null, null, false) {

        @Override
        protected Connection createConnection(ThreadGroup threadGroup, ConnectionData newCD) {
            return new Connection(threadGroup, newCD) {

                TelnetIO telnetIO;

                @Override
                protected void doRun() throws Exception {
                    telnetIO = new TelnetIO();
                    telnetIO.setConnection(this);
                    telnetIO.initIO();
                    InputStream in = new InputStream() {

                        @Override
                        public int read() throws IOException {
                            return telnetIO.read();
                        }

                        @Override
                        public int read(byte[] b, int off, int len) throws IOException {
                            int r = read();
                            if (r >= 0) {
                                b[off] = (byte) r;
                                return 1;
                            } else {
                                return -1;
                            }
                        }
                    };
                    PrintStream out = new PrintStream(new OutputStream() {

                        @Override
                        public void write(int b) throws IOException {
                            telnetIO.write(b);
                        }

                        @Override
                        public void flush() throws IOException {
                            telnetIO.flush();
                        }
                    });
                    Terminal terminal = TerminalBuilder.builder().type(getConnectionData().getNegotiatedTerminalType().toLowerCase()).streams(in, out).system(false).name("telnet").build();
                    terminal.setSize(new Size(getConnectionData().getTerminalColumns(), getConnectionData().getTerminalRows()));
                    terminal.setAttributes(Shell.getTerminal(session).getAttributes());
                    addConnectionListener(new ConnectionListener() {

                        @Override
                        public void connectionIdle(ConnectionEvent ce) {
                        }

                        @Override
                        public void connectionTimedOut(ConnectionEvent ce) {
                        }

                        @Override
                        public void connectionLogoutRequest(ConnectionEvent ce) {
                        }

                        @Override
                        public void connectionSentBreak(ConnectionEvent ce) {
                        }

                        @Override
                        public void connectionTerminalGeometryChanged(ConnectionEvent ce) {
                            terminal.setSize(new Size(getConnectionData().getTerminalColumns(), getConnectionData().getTerminalRows()));
                            terminal.raise(Signal.WINCH);
                        }
                    });
                    PrintStream pout = new PrintStream(terminal.output());
                    CommandSession session = processor.createSession(terminal.input(), pout, pout);
                    session.put(Shell.VAR_TERMINAL, terminal);
                    Context context = new Context() {

                        @Override
                        public String getProperty(String name) {
                            return System.getProperty(name);
                        }

                        @Override
                        public void exit() throws Exception {
                            close();
                        }
                    };
                    new Shell(context, processor).gosh(session, new String[] { "--login" });
                }

                @Override
                protected void doClose() throws Exception {
                    telnetIO.closeOutput();
                    telnetIO.closeInput();
                }
            };
        }
    };
    portListener = new PortListener("gogo", port, 10);
    portListener.setConnectionManager(connectionManager);
    portListener.start();
}
Also used : Context(org.apache.felix.gogo.jline.Shell.Context) PrintStream(java.io.PrintStream) InputStream(java.io.InputStream) Size(org.jline.terminal.Size) OutputStream(java.io.OutputStream) IOException(java.io.IOException) Terminal(org.jline.terminal.Terminal) CommandSession(org.apache.felix.service.command.CommandSession) Shell(org.apache.felix.gogo.jline.Shell)

Aggregations

Terminal (org.jline.terminal.Terminal)39 LineReader (org.jline.reader.LineReader)14 IOException (java.io.IOException)13 InputStream (java.io.InputStream)8 EndOfFileException (org.jline.reader.EndOfFileException)8 UserInterruptException (org.jline.reader.UserInterruptException)8 ByteArrayInputStream (java.io.ByteArrayInputStream)7 Attributes (org.jline.terminal.Attributes)7 PrintStream (java.io.PrintStream)6 Path (java.nio.file.Path)6 CommandSession (org.apache.felix.service.command.CommandSession)6 OutputStream (java.io.OutputStream)5 ArrayList (java.util.ArrayList)5 InputStreamReader (java.io.InputStreamReader)4 Reader (java.io.Reader)4 ParsedLine (org.jline.reader.ParsedLine)4 BufferedReader (java.io.BufferedReader)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 File (java.io.File)3 FileInputStream (java.io.FileInputStream)3