Package jline

Examples of jline.Terminal


                .a(": ")
                .toString() : "";
        for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
            Object param = it.next();
            if (HelpOption.HELP.name().equals(param)) {
                Terminal term = session != null ? (Terminal) session.get(".jline.terminal") : null;
                int termWidth = term != null ? term.getWidth() : 80;
                boolean globalScope = NameScoping.isGlobalScope(session, actionMetaData.getCommand().scope());
                actionMetaData.printUsage(action, System.out, globalScope, termWidth);
                return false;
            }
        }
View Full Code Here


            }
            config.setCommand(sb.toString());
        }

        SshClient client = null;
        Terminal terminal = null;
        int exitStatus = 0;
        try {
            client = SshClient.setUpDefaultClient();
            setupAgent(config.getUser(), client);
            client.start();
            ClientSession session = connectWithRetries(client, config);
            Console console = System.console();
            if (console != null) {
                console.printf("Logging in as %s\n", config.getUser());
            }
            if (!session.authAgent(config.getUser()).await().isSuccess()) {
                AuthFuture authFuture;
                boolean useDefault = config.getPassword() != null;
                do {
                    String password;
                    if (useDefault) {
                        password = config.getPassword();
                        useDefault = false;
                    } else {
                        if (console != null) {
                            char[] readPassword = console.readPassword("Password: ");
                            if (readPassword != null) {
                                password = new String(readPassword);
                            } else {
                                return;
                            }
                        } else {
                            throw new Exception("Unable to prompt password: could not get system console");
                        }
                    }
                    authFuture = session.authPassword(config.getUser(), password);
                } while (authFuture.await().isFailure());
                if (!authFuture.isSuccess()) {
                    throw new Exception("Authentication failure");
                }
            }
            ClientChannel channel;
            if (config.getCommand().length() > 0) {
                channel = session.createChannel("exec", config.getCommand() + "\n");
                channel.setIn(new ByteArrayInputStream(new byte[0]));
            } else {
                TerminalFactory.registerFlavor(TerminalFactory.Flavor.UNIX, NoInterruptUnixTerminal.class);
                terminal = TerminalFactory.create();
                channel = session.createChannel("shell");
                ConsoleInputStream in = new ConsoleInputStream(terminal.wrapInIfNeeded(System.in));
                new Thread(in).start();
                channel.setIn(in);
                ((ChannelShell) channel).setPtyColumns(terminal != null ? terminal.getWidth() : 80);
                ((ChannelShell) channel).setupSensibleDefaultPty();
                ((ChannelShell) channel).setAgentForwarding(true);
                String ctype = System.getenv("LC_CTYPE");
                if (ctype == null) {
                    ctype = Locale.getDefault().toString() + "."
                            + System.getProperty("input.encoding", Charset.defaultCharset().name());
                }
                ((ChannelShell) channel).setEnv("LC_CTYPE", ctype);
            }
            channel.setOut(AnsiConsole.wrapOutputStream(System.out));
            channel.setErr(AnsiConsole.wrapOutputStream(System.err));
            channel.open();
            channel.waitFor(ClientChannel.CLOSED, 0);
            if (channel.getExitStatus() != null) {
                exitStatus = channel.getExitStatus();
            }
        } catch (Throwable t) {
            if (config.getLevel() > SimpleLogger.WARN) {
                t.printStackTrace();
            } else {
                System.err.println(t.getMessage());
            }
            System.exit(1);
        } finally {
            try {
                client.stop();
            } catch (Throwable t) {
            }
            try {
                if (terminal != null) {
                    terminal.restore();
                }
            } catch (Throwable t) {
            }
        }
        System.exit(exitStatus);
View Full Code Here

                        runConsole();
                    }
                }
                protected void runConsole() {
                    try {
                        final Terminal terminal = new SshTerminal(env);
                        String encoding = env.getEnv().get("LC_CTYPE");
                        if (encoding != null && encoding.indexOf('.') > 0) {
                            encoding = encoding.substring(encoding.indexOf('.') + 1);
                        }
                        final Console console = new Console(commandProcessor,
                                threadIO,
                                in,
                                new PrintStream(new LfToCrLfFilterOutputStream(out), true),
                                new PrintStream(new LfToCrLfFilterOutputStream(err), true),
                                terminal,
                                encoding,
                                new Runnable() {
                                    public void run() {
                                        ShellImpl.this.destroy();
                                    }
                                },
                                bundleContext);
                        final CommandSession session = console.getSession();
                        session.put("APPLICATION", System.getProperty("karaf.name", "root"));
                        for (Map.Entry<String,String> e : env.getEnv().entrySet()) {
                            session.put(e.getKey(), e.getValue());
                        }
                        session.put("#LINES", new Function() {
                            public Object execute(CommandSession session, List<Object> arguments) throws Exception {
                                return Integer.toString(terminal.getHeight());
                            }
                        });
                        session.put("#COLUMNS", new Function() {
                            public Object execute(CommandSession session, List<Object> arguments) throws Exception {
                                return Integer.toString(terminal.getWidth());
                            }
                        });
                        session.put(".jline.terminal", terminal);
                        console.run();
                    } catch (Exception e) {
View Full Code Here

                command.append((char) c);
            }
        }

        SshClient client = null;
        Terminal terminal = null;
        SshAgent agent = null;
        int exitStatus = 0;
        try {

            final Console console = System.console();
            client = SshClient.setUpDefaultClient();
            setupAgent(user, client, keyFile);
            client.setUserInteraction(new UserInteraction() {
                public void welcome(String banner) {
                    System.out.println(banner);
                }

                public String[] interactive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
                    String[] answers = new String[prompt.length];
                    try {
                        for (int i = 0; i < prompt.length; i++) {
                            if (console != null) {
                                if (echo[i]) {
                                    answers[i] = console.readLine(prompt[i] + " ");
                                } else {
                                    answers[i] = new String(console.readPassword(prompt[i] + " "));
                                }
                            }
                        }
                    } catch (IOError e) {
                    }
                    return answers;
                }
            });
            client.start();
            if (console != null) {
                console.printf("Logging in as %s\n", user);
            }
           
            ClientSession session = null;
            int retries = 0;
            do {
                ConnectFuture future = client.connect(user, host, port);
                future.await();
                try {
                    session = future.getSession();
                } catch (RuntimeSshException ex) {
                    if (retries++ < retryAttempts) {
                        Thread.sleep(retryDelay * 1000);
                        System.out.println("retrying (attempt " + retries + ") ...");
                    } else {
                        throw ex;
                    }
                }
            } while (session == null);
           
           
            if (password != null) {
                session.addPasswordIdentity(password);
            }
            session.auth().verify();

            ClientChannel channel;
      if (command.length() > 0) {
                channel = session.createChannel("exec", command.append("\n").toString());
                channel.setIn(new ByteArrayInputStream(new byte[0]));
      } else {
                terminal = new TerminalFactory().getTerminal();
         channel = session.createChannel("shell");
                ConsoleInputStream in = new ConsoleInputStream(terminal.wrapInIfNeeded(System.in));
                new Thread(in).start();
                channel.setIn(in);
                ((ChannelShell) channel).setPtyColumns(terminal != null ? terminal.getWidth() : 80);
                ((ChannelShell) channel).setupSensibleDefaultPty();
                ((ChannelShell) channel).setAgentForwarding(true);
                String ctype = System.getenv("LC_CTYPE");
                if (ctype == null) {
                    ctype = Locale.getDefault().toString() + "."
                                + System.getProperty("input.encoding", Charset.defaultCharset().name());
                }
                ((ChannelShell) channel).setEnv("LC_CTYPE", ctype);
            }
            channel.setOut(AnsiConsole.wrapOutputStream(System.out));
            channel.setErr(AnsiConsole.wrapOutputStream(System.err));
            channel.open();
            channel.waitFor(ClientChannel.CLOSED, 0);
            if (channel.getExitStatus() != null) {
                exitStatus = channel.getExitStatus();
            }
        } catch (Throwable t) {
            if (level > 1) {
                t.printStackTrace();
            } else {
                System.err.println(t.getMessage());
            }
            System.exit(1);
        } finally {
            try {
                client.stop();
            } catch (Throwable t) { }
            try {
                if (terminal != null) {
                    terminal.restore();
                }
            } catch (Throwable t) { }
        }
        System.exit(exitStatus);
    }
View Full Code Here

             return stream;
        }
    }

    protected void doStart(String user) throws Exception {
        final Terminal terminal = terminalFactory.getTerminal();
        // unwrap stream so it can be recognized by the terminal and wrapped to get
        // special keys in windows
        InputStream unwrappedIn = unwrapBIS(unwrap(System.in));
        InputStream in = terminal.wrapInIfNeeded(unwrappedIn);
        PrintStream out = unwrap(System.out);
        PrintStream err = unwrap(System.err);
        Runnable callback = new Runnable() {
            public void run() {
                try {
                    bundleContext.getBundle(0).stop();
                } catch (Exception e) {
                    // Ignore
                }
            }
        };
        String ctype = System.getenv("LC_CTYPE");
        String encoding = ctype;
        if (encoding != null && encoding.indexOf('.') > 0) {
            encoding = encoding.substring(encoding.indexOf('.') + 1);
        } else {
            encoding = System.getProperty("input.encoding", Charset.defaultCharset().name());
        }
        this.console = new Console(commandProcessor,
                                   threadIO,
                                   in,
                                   wrap(out),
                                   wrap(err),
                                   terminal,
                                   encoding,
                                   callback,
                                   bundleContext);
        CommandSession session = console.getSession();
        for (Object o : System.getProperties().keySet()) {
            String key = o.toString();
            session.put(key, System.getProperty(key));
        }
        session.put("USER", user);
        session.put("APPLICATION", System.getProperty("karaf.name", "root"));
        session.put("#LINES", new Function() {
            public Object execute(CommandSession session, List<Object> arguments) throws Exception {
                return Integer.toString(terminal.getHeight());
            }
        });
        session.put("#COLUMNS", new Function() {
            public Object execute(CommandSession session, List<Object> arguments) throws Exception {
                return Integer.toString(terminal.getWidth());
            }
        });
        if (ctype != null) {
            session.put("LC_CTYPE", ctype);
        }
View Full Code Here

        return null;
    }

    private int getTermWidth() {
        Terminal term = (Terminal) session.get(".jline.terminal");
        return term != null ? term.getWidth() : 80;
    }
View Full Code Here

            }
        } else {
            // We are going into full blown interactive shell mode.

            final TerminalFactory terminalFactory = new TerminalFactory();
            final Terminal terminal = terminalFactory.getTerminal();
            Console console = createConsole(commandProcessor, threadIO, in, out, err, terminal);
            CommandSession session = console.getSession();
            session.put("USER", user);
            session.put("APPLICATION", application);
            session.put(NameScoping.MULTI_SCOPE_MODE_KEY, Boolean.toString(isMultiScopeMode()));
            session.put("#LINES", new Function() {
                public Object execute(CommandSession session, List<Object> arguments) throws Exception {
                    return Integer.toString(terminal.getHeight());
                }
            });
            session.put("#COLUMNS", new Function() {
                public Object execute(CommandSession session, List<Object> arguments) throws Exception {
                    return Integer.toString(terminal.getWidth());
                }
            });
            session.put(".jline.terminal", terminal);

            console.run();
View Full Code Here

        }
        return commands;
    }

    protected void printMethodList(CommandSession session, PrintStream out, SortedMap<String, String> commands) {
        Terminal term = (Terminal) session.get(".jline.terminal");
        out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("COMMANDS").a(Ansi.Attribute.RESET));
        int max = 0;
        for (Map.Entry<String,String> entry : commands.entrySet()) {
            String key = NameScoping.getCommandNameWithoutGlobalPrefix(session, entry.getKey());
            max = Math.max(max,key.length());
        }
        int margin = 4;
        String prefix1 = "        ";
        if (term != null && term.getWidth() - max - prefix1.length() - margin > 50) {
            String prefix2 = prefix1;
            for (int i = 0; i < max + margin; i++) {
                prefix2 += " ";
            }
            for (Map.Entry<String,String> entry : commands.entrySet()) {
                out.print(prefix1);
                String key = NameScoping.getCommandNameWithoutGlobalPrefix(session, entry.getKey());
                out.print(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(key).a(Ansi.Attribute.RESET));
                for (int i = 0; i < max - key.length() + margin; i++) {
                    out.print(' ');
                }
                if (entry.getValue() != null) {
                    DefaultActionPreparator.printFormatted(prefix2, entry.getValue(), term.getWidth(), out, false);
                }
            }
        } else {
            String prefix2 = prefix1 + prefix1;
            for (Map.Entry<String,String> entry : commands.entrySet()) {
                out.print(prefix1);
                String key = NameScoping.getCommandNameWithoutGlobalPrefix(session, entry.getKey());
                out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(key).a(Ansi.Attribute.RESET));
                if (entry.getValue() != null) {
                    DefaultActionPreparator.printFormatted(prefix2, entry.getValue(),
                            term != null ? term.getWidth() : 80, out);
                }
            }
        }
        out.println();
    }
View Full Code Here

    }

    protected void printUsage(CommandSession session, Action action, Map<Option, Field> optionsMap, Map<Argument, Field> argsMap, PrintStream out) {
        Command command = action.getClass().getAnnotation(Command.class);
        if (command != null) {
            Terminal term = session != null ? (Terminal) session.get(".jline.terminal") : null;
            List<Argument> arguments = new ArrayList<Argument>(argsMap.keySet());
            Collections.sort(arguments, new Comparator<Argument>() {
                public int compare(Argument o1, Argument o2) {
                    return Integer.valueOf(o1.index()).compareTo(Integer.valueOf(o2.index()));
                }
            });
            Set<Option> options = new HashSet<Option>(optionsMap.keySet());
            options.add(HELP);
            boolean globalScope = NameScoping.isGlobalScope(session, command.scope());
            if (command != null && (command.description() != null || command.name() != null)) {
                out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("DESCRIPTION").a(Ansi.Attribute.RESET));
                out.print("        ");
                if (command.name() != null) {
                    if (globalScope) {
                        out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(command.name()).a(Ansi.Attribute.RESET));
                    } else {
                        out.println(Ansi.ansi().a(command.scope()).a(":").a(Ansi.Attribute.INTENSITY_BOLD).a(command.name()).a(Ansi.Attribute.RESET));
                    }
                    out.println();
                }
                out.print("\t");
                out.println(command.description());
                out.println();
            }
            StringBuffer syntax = new StringBuffer();
            if (command != null) {
                if (globalScope) {
                    syntax.append(command.name());
                } else {
                    syntax.append(String.format("%s:%s", command.scope(), command.name()));
                }
            }
            if (options.size() > 0) {
                syntax.append(" [options]");
            }
            if (arguments.size() > 0) {
                syntax.append(' ');
                for (Argument argument : arguments) {
                    if (!argument.required()) {
                        syntax.append(String.format("[%s] ", argument.name()));
                    } else {
                        syntax.append(String.format("%s ", argument.name()));
                    }
                }
            }

            out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("SYNTAX").a(Ansi.Attribute.RESET));
            out.print("        ");
            out.println(syntax.toString());
            out.println();
            if (arguments.size() > 0) {
                out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("ARGUMENTS").a(Ansi.Attribute.RESET));
                for (Argument argument : arguments) {
                    out.print("        ");
                    out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(argument.name()).a(Ansi.Attribute.RESET));
                    printFormatted("                ", argument.description(), term != null ? term.getWidth() : 80, out);
                    if (!argument.required()) {
                        if (argument.valueToShowInHelp() != null && argument.valueToShowInHelp().length() != 0) {
                            try {
                                if (Argument.DEFAULT_STRING.equals(argument.valueToShowInHelp())) {
                                    argsMap.get(argument).setAccessible(true);
                                    Object o = argsMap.get(argument).get(action);
                                    printObjectDefaultsTo(out, o);
                                } else {
                                    printDefaultsTo(out, argument.valueToShowInHelp());
                                }
                            } catch (Throwable t) {
                                // Ignore
                            }
                        }
                    }
                }
                out.println();
            }
            if (options.size() > 0) {
                out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("OPTIONS").a(Ansi.Attribute.RESET));
                for (Option option : options) {
                    String opt = option.name();
                    for (String alias : option.aliases()) {
                        opt += ", " + alias;
                    }
                    out.print("        ");
                    out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a(opt).a(Ansi.Attribute.RESET));
                    printFormatted("                ", option.description(), term != null ? term.getWidth() : 80, out);
                    if (option.valueToShowInHelp() != null && option.valueToShowInHelp().length() != 0) {
                        try {
                            if (Option.DEFAULT_STRING.equals(option.valueToShowInHelp())) {
                                optionsMap.get(option).setAccessible(true);
                                Object o = optionsMap.get(option).get(action);
                                printObjectDefaultsTo(out, o);
                            } else {
                                printDefaultsTo(out, option.valueToShowInHelp());
                            }
                        } catch (Throwable t) {
                            // Ignore
                        }
                    }
                }
                out.println();
            }
            if (command.detailedDescription().length() > 0) {
                out.println(Ansi.ansi().a(Ansi.Attribute.INTENSITY_BOLD).a("DETAILS").a(Ansi.Attribute.RESET));
                String desc = loadDescription(action.getClass(), command.detailedDescription());
                printFormatted("        ", desc, term != null ? term.getWidth() : 80, out);
            }
        }
    }
View Full Code Here

                .a(": ")
                .toString() : "";
        for (Iterator<Object> it = params.iterator(); it.hasNext(); ) {
            Object param = it.next();
            if (HelpOption.HELP.name().equals(param)) {
                Terminal term = session != null ? (Terminal) session.get(".jline.terminal") : null;
                int termWidth = term != null ? term.getWidth() : 80;
                boolean globalScope = NameScoping.isGlobalScope(session, actionMetaData.getCommand().scope());
                actionMetaData.printUsage(action, System.out, globalScope, termWidth);
                return false;
            }
        }
View Full Code Here

TOP

Related Classes of jline.Terminal

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.