Search in sources :

Example 6 with Terminal

use of org.jline.terminal.Terminal 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 7 with Terminal

use of org.jline.terminal.Terminal 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 8 with Terminal

use of org.jline.terminal.Terminal in project SpongeVanilla by SpongePowered.

the class VanillaServerMain method main.

public static void main(String[] args) throws Exception {
    OptionSet options = VanillaCommandLine.parse(args);
    if (options.has(HELP)) {
        if (System.console() == null) {
            // We have no supported terminal, print help with default terminal width
            VanillaCommandLine.printHelp(System.err);
        } else {
            // Terminal is (very likely) supported, use the terminal width provided by jline
            Terminal terminal = TerminalBuilder.builder().dumb(true).build();
            VanillaCommandLine.printHelp(new BuiltinHelpFormatter(terminal.getWidth(), 3), System.err);
        }
        return;
    } else if (options.has(VERSION)) {
        final Package pack = VanillaServerMain.class.getPackage();
        System.out.println(pack.getImplementationTitle() + ' ' + pack.getImplementationVersion());
        System.out.println(pack.getSpecificationTitle() + ' ' + pack.getSpecificationVersion());
        return;
    }
    // Download/verify Minecraft server installation if necessary and not disabled
    if (!options.has(NO_VERIFY_CLASSPATH)) {
        // Get the location of our jar
        Path base = Paths.get(VanillaServerMain.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
        try {
            // Download dependencies
            if (!downloadMinecraft(base, !options.has(NO_DOWNLOAD))) {
                System.err.println("Failed to load all required dependencies. Please download them manually:");
                System.err.println("Download " + MINECRAFT_SERVER_REMOTE + " and copy it to " + base.resolve(MINECRAFT_SERVER_LOCAL).toAbsolutePath());
                System.err.println("Download " + LAUNCHWRAPPER_REMOTE + " and copy it to " + base.resolve(LAUNCHWRAPPER_LOCAL).toAbsolutePath());
                System.exit(1);
                return;
            }
        } catch (IOException e) {
            System.err.println("Failed to download required dependencies. Please try again later.");
            e.printStackTrace();
            System.exit(1);
            return;
        }
    } else {
        System.err.println("Classpath verification is disabled. The server may NOT start properly unless you have all required dependencies on " + "the classpath!");
    }
    Launch.main(getLaunchArguments(TWEAKER, options.valuesOf(TWEAK_CLASS)));
}
Also used : Path(java.nio.file.Path) BuiltinHelpFormatter(joptsimple.BuiltinHelpFormatter) IOException(java.io.IOException) OptionSet(joptsimple.OptionSet) Terminal(org.jline.terminal.Terminal)

Example 9 with Terminal

use of org.jline.terminal.Terminal in project LanternServer by LanternPowered.

the class ConsoleManager method shutdown.

public void shutdown() {
    active = false;
    saveHistory();
    if (TerminalConsoleAppender.getReader() != null) {
        TerminalConsoleAppender.setReader(null);
        // Write a nice new line
        final Terminal terminal = TerminalConsoleAppender.getTerminal();
        if (terminal != null) {
            terminal.writer().println();
        }
    }
}
Also used : Terminal(org.jline.terminal.Terminal)

Example 10 with Terminal

use of org.jline.terminal.Terminal in project LanternServer by LanternPowered.

the class LanternServerLaunch method main.

public void main(String[] args) {
    final LanternClassLoader classLoader = LanternClassLoader.get();
    // Exclude the ASM library
    classLoader.addTransformerExclusion(Exclusion.forPackage("org.objectweb.asm"));
    classLoader.addTransformerExclusion(Exclusion.forPackage("org.lanternpowered.server.transformer"));
    classLoader.addTransformerExclusion(Exclusion.forClass("org.lanternpowered.server.util.BytecodeUtils"));
    classLoader.addTransformer(new FinalFieldClassTransformer());
    classLoader.addTransformer(new FastValueContainerClassTransformer());
    // Get the default logger
    final Logger logger = LoggerFactory.getLogger(InternalPluginsInfo.Implementation.IDENTIFIER);
    try {
        // Create the shared option parser
        final OptionParser optionParser = new OptionParser();
        optionParser.allowsUnrecognizedOptions();
        final OptionSpec<Void> version = optionParser.acceptsAll(Arrays.asList("version", "v"), "Display the Lantern version");
        if (optionParser.parse(args).has(version)) {
            final Package pack = Platform.class.getPackage();
            logger.info(pack.getImplementationTitle() + ' ' + pack.getImplementationVersion());
            logger.info(pack.getSpecificationTitle() + ' ' + pack.getSpecificationVersion());
            return;
        }
        final OptionSpec<Void> help = optionParser.acceptsAll(Arrays.asList("help", "h", "?"), "Show this help text").forHelp();
        // Initialize the injector
        final LanternModule module = new LanternModule(logger, args, optionParser);
        final Injector injector = Guice.createInjector(Stage.DEVELOPMENT, module);
        logger.info("Instantiated the Injector in {} mode.", Environment.get().name().toLowerCase());
        // Create the server instance
        final LanternServer lanternServer = injector.getInstance(LanternServer.class);
        // Initialize and start the server
        lanternServer.initialize();
        try {
            final Field field = OptionParser.class.getDeclaredField("allowsUnrecognizedOptions");
            field.setAccessible(true);
            field.set(optionParser, false);
            optionParser.parse(args);
        } catch (OptionException e) {
            logger.warn("Something went wrong while parsing options", e);
        } catch (Exception e) {
            logger.error("Unexpected error", e);
        }
        // annotations will be detected
        if (optionParser.parse(args).has(help)) {
            if (System.console() != null) {
                // Terminal is (very likely) supported, use the terminal width provided by jline
                final Terminal terminal = TerminalConsoleAppender.getTerminal();
                if (terminal != null) {
                    optionParser.formatHelpWith(new BuiltinHelpFormatter(terminal.getWidth(), 3));
                }
            }
            optionParser.printHelpOn(System.err);
            return;
        }
        lanternServer.start();
    } catch (Throwable t) {
        logger.error("Error during server startup.", t);
        System.exit(1);
    }
}
Also used : LanternClassLoader(org.lanternpowered.launch.LanternClassLoader) OptionException(joptsimple.OptionException) Logger(org.slf4j.Logger) OptionParser(joptsimple.OptionParser) Terminal(org.jline.terminal.Terminal) OptionException(joptsimple.OptionException) Field(java.lang.reflect.Field) BuiltinHelpFormatter(joptsimple.BuiltinHelpFormatter) Injector(com.google.inject.Injector) FastValueContainerClassTransformer(org.lanternpowered.server.transformer.data.FastValueContainerClassTransformer) LanternModule(org.lanternpowered.server.inject.LanternModule) FinalFieldClassTransformer(org.lanternpowered.server.transformer.FinalFieldClassTransformer)

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