org.jline.terminal.TerminalBuilder Java Examples

The following examples show how to use org.jline.terminal.TerminalBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: InputReader.java    From presto with Apache License 2.0 6 votes vote down vote up
public InputReader(Path historyFile, Completer... completers)
        throws IOException
{
    Terminal terminal = TerminalBuilder.builder()
            .name("Presto")
            .build();

    reader = LineReaderBuilder.builder()
            .terminal(terminal)
            .variable(HISTORY_FILE, historyFile)
            .variable(SECONDARY_PROMPT_PATTERN, colored("%P -> "))
            .variable(BLINK_MATCHING_PAREN, 0)
            .parser(new InputParser())
            .highlighter(new InputHighlighter())
            .completer(new AggregateCompleter(completers))
            .build();

    reader.unsetOpt(HISTORY_TIMESTAMPED);
}
 
Example #2
Source File: JLineCommandHandler.java    From Launcher with GNU General Public License v3.0 6 votes vote down vote up
public JLineCommandHandler() throws IOException {
    super();
    terminalBuilder = TerminalBuilder.builder();
    terminal = terminalBuilder.build();
    completer = new JLineConsoleCompleter();
    reader = LineReaderBuilder.builder()
            .terminal(terminal)
            .completer(completer)
            .build();

    // Set reader
    //reader = new ConsoleReader();
    //reader.setExpandEvents(false);

    // Replace writer
    //LogHelper.removeStdOutput();
    //LogHelper.addOutput(new JLineOutput(), LogHelper.OutputTypes.JANSI);
}
 
Example #3
Source File: JLineCliRepl.java    From Arend with Apache License 2.0 6 votes vote down vote up
public static void launch(
  boolean recompile,
  @NotNull Collection<? extends Path> libDirs
) {
  Terminal terminal;
  try {
    terminal = TerminalBuilder
      .builder()
      .encoding("UTF-8")
      .jansi(true)
      .jna(false)
      .build();
  } catch (IOException e) {
    System.err.println("[FATAL] Failed to create terminal: " + e.getLocalizedMessage());
    System.exit(1);
    return;
  }
  var repl = new JLineCliRepl(terminal);
  repl.println(ASCII_BANNER);
  repl.println();
  repl.addLibraryDirectories(libDirs);
  if (recompile) repl.getReplLibrary().addFlag(SourceLibrary.Flag.RECOMPILE);
  repl.initialize();
  repl.runRepl();
}
 
Example #4
Source File: CompletionTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private LineReaderCompletionImpl getDummyLineReader() {
  try {
    TerminalBuilder terminalBuilder = TerminalBuilder.builder();
    final Terminal terminal = terminalBuilder.build();
    final LineReaderCompletionImpl lineReader =
        new LineReaderCompletionImpl(terminal);
    lineReader.setCompleter(sqlLine.getCommandCompleter());
    lineReader.option(LineReader.Option.DISABLE_EVENT_EXPANSION, true);
    return lineReader;
  } catch (Exception e) {
    // fail
    throw new RuntimeException(e);
  }
}
 
Example #5
Source File: ConsoleProgressBarConsumer.java    From schedge with MIT License 5 votes vote down vote up
private static Terminal getTerminal() {
  Terminal terminal = null;
  try {
    // Issue #42
    // Defaulting to a dumb terminal when a supported terminal can not be
    // correctly created see https://github.com/jline/jline3/issues/291
    terminal = TerminalBuilder.builder().dumb(true).build();
  } catch (IOException ignored) {
  }
  return terminal;
}
 
Example #6
Source File: CompletionTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@BeforeAll
public static void setUp() {
  // Required as DummyLineReader does not support keymap binding
  new MockUp<Candidate>() {
    @Mock public String suffix() {
      return null;
    }
  };

  System.setProperty(TerminalBuilder.PROP_DUMB,
      Boolean.TRUE.toString());

  sqlLine = new SqlLine();
  os = new ByteArrayOutputStream();
  sqlLine.getOpts().setPropertiesFile(DEV_NULL);

  SqlLine.Status status =
      begin(sqlLine, os, false,
          "-e", "!set maxwidth 80", "!set fastconnect true");
  assertEquals(status, SqlLine.Status.OK);
  sqlLine.runCommands(new DispatchCallback(),
      "!connect "
          + SqlLineArgsTest.ConnectionSpec.H2.url + " "
          + SqlLineArgsTest.ConnectionSpec.H2.username + " "
          + "\"\"");

  final String createScript = "CREATE SCHEMA TEST_SCHEMA_FIRST;\n"
      + "CREATE SCHEMA TEST_SCHEMA_SECOND;\n"
      + "CREATE SCHEMA \"TEST SCHEMA WITH SPACES\";\n"
      + "CREATE SCHEMA \"TEST \"\"SCHEMA \"\"WITH \"\"QUOTES\";\n"
      + "CREATE TABLE TEST_SCHEMA_FIRST.TABLE_FIRST(pk int, name varchar);\n"
      + "CREATE TABLE TEST_SCHEMA_FIRST.TABLE_SECOND(pk int, \"last name\" varchar);\n"
      + "CREATE TABLE TEST_SCHEMA_SECOND.\"TBL 1\"(pk int, desc varchar);\n"
      + "CREATE TABLE \"TEST \"\"SCHEMA \"\"WITH \"\"QUOTES\".\"QUOTES \"\"TBL 1\"(pk int, desc varchar);\n"
      + "CREATE TABLE TEST_SCHEMA_SECOND.\"TABLE 2  SECOND\"(pk int, \"field2\" varchar);\n"
      + "CREATE TABLE \"TEST SCHEMA WITH SPACES\".\"TABLE WITH SPACES\"(pk int, \"with spaces\" varchar);\n";
  sqlLine.runCommands(new DispatchCallback(), createScript);

  os.reset();
}
 
Example #7
Source File: SqlLineArgsTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testAnsiConsoleFormatWithZeroMaxWidthAndExistingTerminal() {
  try {
    new MockUp<DumbTerminal>() {
      @Mock
      public Size getSize() {
        return new Size(80, 20);
      }
    };
    final LineReaderBuilder lineReaderBuilder = LineReaderBuilder.builder()
        .parser(new SqlLineParser(sqlLine))
        .terminal(TerminalBuilder.builder().dumb(true).build());
    sqlLine.setLineReader(lineReaderBuilder.build());
    final String script = "!set maxwidth 0\n"
        + "!set incremental true \n"
        + "!set outputformat ansiconsole \n"
        + "!all \n"
        + "values \n"
        + "(1, '2') \n"
        + ";\n";
    final String line1 = ""
        + "C1          C2\n"
        + "1           2 \n";
    checkScriptFile(script, false,
        equalTo(SqlLine.Status.OK),
        containsString(line1));
  } catch (Exception e) {
    fail("Test failed with ", e);
  }
}
 
Example #8
Source File: SqlLineArgsTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testTableOutputWithZeroMaxWidthAndExistingTerminal() {
  try {
    new MockUp<DumbTerminal>() {
      @Mock
      public Size getSize() {
        return new Size(80, 20);
      }
    };
    final LineReaderBuilder lineReaderBuilder = LineReaderBuilder.builder()
        .parser(new SqlLineParser(sqlLine))
        .terminal(TerminalBuilder.builder().dumb(true).build());
    sqlLine.setLineReader(lineReaderBuilder.build());
    final String script = "!set maxwidth 0\n"
        + "!set incremental true\n"
        + "values (1, cast(null as integer), cast(null as varchar(3)));\n";
    checkScriptFile(script, false,
        equalTo(SqlLine.Status.OK),
        containsString(
            "+-------------+-------------+-----+\n"
                + "|     C1      |     C2      | C3  |\n"
                + "+-------------+-------------+-----+\n"
                + "| 1           | null        |     |\n"
                + "+-------------+-------------+-----+\n"));
  } catch (Exception e) {
    fail("Test failed with ", e);
  }
}
 
Example #9
Source File: SqlLine.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public LineReader getConsoleReader(InputStream inputStream,
    History fileHistory) throws IOException {
  if (getLineReader() != null) {
    return getLineReader();
  }
  final TerminalBuilder terminalBuilder =
      TerminalBuilder.builder().signalHandler(signalHandler);
  final Terminal terminal;
  if (inputStream != null) {
    terminal = terminalBuilder.streams(inputStream, System.out).build();
  } else {
    terminal = terminalBuilder.system(true).build();
    getOpts().set(BuiltInProperty.MAX_WIDTH, terminal.getWidth());
    getOpts().set(BuiltInProperty.MAX_HEIGHT, terminal.getHeight());
  }

  final LineReaderBuilder lineReaderBuilder = LineReaderBuilder.builder()
      .terminal(terminal)
      .parser(new SqlLineParser(this))
      .variable(LineReader.HISTORY_FILE, getOpts().getHistoryFile())
      .variable(LineReader.LINE_OFFSET, 1)  // start line numbers with 1
      .option(LineReader.Option.AUTO_LIST, false)
      .option(LineReader.Option.AUTO_MENU, true)
      .option(LineReader.Option.DISABLE_EVENT_EXPANSION, true);
  final LineReader lineReader = inputStream == null
      ? lineReaderBuilder
        .appName("sqlline")
        .completer(new SqlLineCompleter(this))
        .highlighter(new SqlLineHighlighter(this))
        .build()
      : lineReaderBuilder.build();

  addWidget(lineReader,
      this::nextColorSchemeWidget, "CHANGE_COLOR_SCHEME", alt('h'));
  addWidget(lineReader,
      this::toggleLineNumbersWidget, "TOGGLE_LINE_NUMBERS", alt(ctrl('n')));
  fileHistory.attach(lineReader);
  setLineReader(lineReader);
  return lineReader;
}
 
Example #10
Source File: SqshConsole.java    From jsqsh with Apache License 2.0 5 votes vote down vote up
private Terminal newTerminal() {

        Terminal terminal;
        try {

            terminal = TerminalBuilder.builder()
                    .nativeSignals(true)
                    .build();
        }
        catch (IOException e) {

            System.err.println("Unable to create terminal: " + e.getMessage()
                    + ". Falling back to dumb terminal");
            try {

                terminal = TerminalBuilder.builder()
                        .dumb(true)
                        .build();
            }
            catch (IOException e2) {

                System.err.println("Unable to create dumb terminal: " + e2.getMessage()
                        + ". Giving up");
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        return terminal;
    }
 
Example #11
Source File: CliClient.java    From flink with Apache License 2.0 5 votes vote down vote up
private static Terminal createDefaultTerminal() {
	try {
		return TerminalBuilder.builder()
			.name(CliStrings.CLI_NAME)
			.build();
	} catch (IOException e) {
		throw new SqlClientException("Error opening command line interface.", e);
	}
}
 
Example #12
Source File: Util.java    From progressbar with MIT License 5 votes vote down vote up
static Terminal getTerminal() {
    Terminal terminal = null;
    try {
        // Issue #42
        // Defaulting to a dumb terminal when a supported terminal can not be correctly created
        // see https://github.com/jline/jline3/issues/291
        terminal = TerminalBuilder.builder().dumb(true).build();
    }
    catch (IOException ignored) { }
    return terminal;
}
 
Example #13
Source File: LogServiceShell.java    From ratis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  final Terminal terminal = TerminalBuilder.builder()
      .system(true)
      .build();

  History defaultHistory = new DefaultHistory();
  // Register a shutdown-hook per JLine documentation to save history
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    try {
      defaultHistory.save();
    } catch (IOException e) {
      LOG.debug("Failed to save terminal history", e);
    }
  }));

  final LineReader lineReader = LineReaderBuilder.builder()
      .terminal(terminal)
      .highlighter(new DefaultHighlighter())
      .history(defaultHistory)
      .build();

  LogServiceShellOpts opts = new LogServiceShellOpts();
  JCommander.newBuilder()
      .addObject(opts)
      .build()
      .parse(args);

  try (LogServiceClient logServiceClient = new LogServiceClient(opts.metaQuorum)) {
    LogServiceShell client = new LogServiceShell(terminal, lineReader, logServiceClient);
    client.run();
  }
}
 
Example #14
Source File: TerminalProcessor.java    From sshd-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
private Terminal newTerminalInstance(String terminalType, InputStream is, OutputStream os) throws IOException {
    return TerminalBuilder.builder()
            .system(false)
            .type(terminalType)
            .streams(is, os)
            .build();
}
 
Example #15
Source File: LogServiceShell.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
  final Terminal terminal = TerminalBuilder.builder()
      .system(true)
      .build();

  History defaultHistory = new DefaultHistory();
  // Register a shutdown-hook per JLine documentation to save history
  Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    try {
      defaultHistory.save();
    } catch (IOException e) {
      LOG.debug("Failed to save terminal history", e);
    }
  }));

  final LineReader lineReader = LineReaderBuilder.builder()
      .terminal(terminal)
      .highlighter(new DefaultHighlighter())
      .history(defaultHistory)
      .build();

  LogServiceShellOpts opts = new LogServiceShellOpts();
  JCommander.newBuilder()
      .addObject(opts)
      .build()
      .parse(args);

  try (LogServiceClient logServiceClient = new LogServiceClient(opts.getMetaQuorum())) {
    LogServiceShell client = new LogServiceShell(terminal, lineReader, logServiceClient);
    client.run();
  }
}
 
Example #16
Source File: AbstractClientShellHandler.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * Create {@link LineReader}.
 * 
 * @return
 */
private LineReader createLineReader() {
	try {
		return LineReaderBuilder.builder().appName("Devops Shell Cli").completer(new DynamicCompleter(getSingle()))
				.terminal(TerminalBuilder.terminal()).build();
	} catch (IOException e) {
		throw new IllegalStateException(e);
	}
}
 
Example #17
Source File: JLineTerminal.java    From ksql-fork-with-deep-learning-function with Apache License 2.0 5 votes vote down vote up
public JLineTerminal(OutputFormat outputFormat, KsqlRestClient restClient) {
  super(outputFormat, restClient);

  try {
    terminal = TerminalBuilder.builder().system(true).build();
  } catch (IOException e) {
    throw new RuntimeException("JLineTerminal failed to start!", e);
  }
  // Ignore ^C when not reading a line
  terminal.handle(
      org.jline.terminal.Terminal.Signal.INT,
      org.jline.terminal.Terminal.SignalHandler.SIG_IGN
  );
}
 
Example #18
Source File: TerminalUi.java    From milkman with MIT License 5 votes vote down vote up
@PostConstruct
@SneakyThrows
public void setup() {
	cmd = new CommandLine(CommandSpec.create()
			.name("")
			.addSubcommand(null, commandSpecFactory.getSpecFor(wsCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(execCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(editCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(quitCmd))
			.addSubcommand(null, commandSpecFactory.getSpecFor(colCmd)));
       
	cmd.setExecutionExceptionHandler(new IExecutionExceptionHandler() {
		
		@Override
		public int handleExecutionException(Exception ex, CommandLine commandLine, ParseResult parseResult)
				throws Exception {
			System.out.println(ex.getMessage());
			log.error("Command execution failed", ex);
			return 0;
		}
	});
       
       terminal = TerminalBuilder.builder()
       		.build();
       reader = LineReaderBuilder.builder()
               .terminal(terminal)
               .completer(new PicocliJLineCompleter(cmd.getCommandSpec()))
               .parser(new DefaultParser())
               .build();
       rightPrompt = null;
}
 
Example #19
Source File: CliClient.java    From flink with Apache License 2.0 5 votes vote down vote up
private static Terminal createDefaultTerminal() {
	try {
		return TerminalBuilder.builder()
			.name(CliStrings.CLI_NAME)
			.build();
	} catch (IOException e) {
		throw new SqlClientException("Error opening command line interface.", e);
	}
}
 
Example #20
Source File: CliClient.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private static Terminal createDefaultTerminal() {
	try {
		return TerminalBuilder.builder()
			.name(CliStrings.CLI_NAME)
			.build();
	} catch (IOException e) {
		throw new SqlClientException("Error opening command line interface.", e);
	}
}
 
Example #21
Source File: JLineAdapter.java    From Recaf with MIT License 4 votes vote down vote up
private void setupJLine() throws IOException {
	terminal = TerminalBuilder.builder().build();
	reader = setupCompletionReader(terminal, controller.getLookup());
}
 
Example #22
Source File: CliShell.java    From samza with Apache License 2.0 4 votes vote down vote up
CliShell(CliEnvironment environment) throws ExecutorException {
  if (environment == null) {
    throw new IllegalArgumentException();
  }

  // Terminal
  try {
    terminal = TerminalBuilder.builder().name(CliConstants.WINDOW_TITLE).build();
  } catch (IOException e) {
    throw new CliException("Error when creating terminal", e);
  }

  // Terminal writer
  writer = terminal.writer();

  // LineReader
  final DefaultParser parser = new DefaultParser().eofOnEscapedNewLine(true).eofOnUnclosedQuote(true);
  lineReader = LineReaderBuilder.builder()
      .appName(CliConstants.APP_NAME)
      .terminal(terminal)
      .parser(parser)
      .highlighter(new CliHighlighter())
      .completer(new StringsCompleter(CliCommandType.getAllCommands()))
      .build();

  // Command Prompt
  firstPrompt = new AttributedStringBuilder().style(AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW))
      .append(CliConstants.PROMPT_1ST + CliConstants.PROMPT_1ST_END)
      .toAnsi();

  // Execution context and executor
  executor = environment.getExecutor();
  exeContext = new ExecutionContext();
  executor.start(exeContext);

  // Command handlers
  if (commandHandlers == null) {
    commandHandlers = new ArrayList<>();
  }
  commandHandlers.add(new CliCommandHandler());
  commandHandlers.addAll(environment.getCommandHandlers());
  for (CommandHandler commandHandler : commandHandlers) {
    LOG.info("init commandHandler {}", commandHandler.getClass().getName());
    commandHandler.init(this, environment, terminal, exeContext);
  }
}
 
Example #23
Source File: InteractiveMode.java    From rdflint with MIT License 4 votes vote down vote up
/**
 * execute interacitve mode.
 */
void execute(Map<String, String> cmdOptions) throws IOException {
  // initialize graph model
  Model m = ModelFactory.createDefaultModel();

  // initialize jline
  Terminal terminal = TerminalBuilder.builder()
      .system(true)
      .build();
  LineReader lineReader = LineReaderBuilder.builder()
      .terminal(terminal)
      .completer(new InteractiveCompleter(m))
      .parser(new InteractiveParser())
      .build();

  String welcome = MessageFormat
      .format(messages.getString("interactivemode.welcome"), RdfLint.VERSION);
  System.out.println(welcome);// NOPMD

  RdfLintParameters params = new RdfLintParameters();
  try {
    // load configurations
    params = ConfigurationLoader.loadParameters(cmdOptions);
    // load rdf
    m.removeAll();
    m.add(DatasetLoader.loadRdfSet(params, params.getTargetDir()));
  } catch (Exception ex) {
    System.out.println(ex.getLocalizedMessage()); // NOPMD
  }

  while (true) {
    String line;

    try {
      line = lineReader.readLine("SPARQL> ");
    } catch (UserInterruptException | EndOfFileException e) {
      return;
    }

    if (!interactiveCommand(System.out, line, params, cmdOptions, m)) {
      return;
    }
  }
}
 
Example #24
Source File: Client.java    From batfish with Apache License 2.0 4 votes vote down vote up
public Client(Settings settings) {
  _additionalBatfishOptions = new HashMap<>();
  _bfq = new TreeMap<>();
  _settings = settings;

  switch (_settings.getRunMode()) {
    case batch:
      if (_settings.getBatchCommandFile() == null) {
        System.err.println(
            "org.batfish.client: Command file not specified while running in batch mode.");
        System.err.printf(
            "Use '-%s <cmdfile>' if you want batch mode, or '-%s interactive' if you want "
                + "interactive mode\n",
            Settings.ARG_COMMAND_FILE, Settings.ARG_RUN_MODE);
        System.exit(1);
      }
      _logger = new BatfishLogger(_settings.getLogLevel(), false, _settings.getLogFile());
      break;
    case interactive:
      System.err.println(
          "This is not a supported client for Batfish. Please use pybatfish following the "
              + "instructions in the README: https://github.com/batfish/batfish/#how-do-i-get-started");
      try {
        _reader =
            LineReaderBuilder.builder()
                .terminal(TerminalBuilder.builder().build())
                .completer(new ArgumentCompleter(new CommandCompleter(), new NullCompleter()))
                .build();
        Path historyPath = Paths.get(System.getenv(ENV_HOME), HISTORY_FILE);
        historyPath.toFile().createNewFile();
        _reader.setVariable(LineReader.HISTORY_FILE, historyPath.toAbsolutePath().toString());
        _reader.unsetOpt(Option.INSERT_TAB); // supports completion with nothing entered

        @SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
        PrintWriter pWriter = new PrintWriter(_reader.getTerminal().output(), true);
        @SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
        OutputStream os = new WriterOutputStream(pWriter, StandardCharsets.UTF_8);
        @SuppressWarnings("PMD.CloseResource") // PMD does not understand things closed later.
        PrintStream ps = new PrintStream(os, true);
        _logger = new BatfishLogger(_settings.getLogLevel(), false, ps);
      } catch (Exception e) {
        System.err.printf("Could not initialize client: %s\n", e.getMessage());
        e.printStackTrace();
      }
      break;
    default:
      System.err.println("org.batfish.client: Unknown run mode.");
      System.exit(1);
  }
}
 
Example #25
Source File: ProgressBar.java    From redis-rdb-cli with Apache License 2.0 4 votes vote down vote up
public ProgressBar(long total) throws IOException {
    this.total = total;
    this.ctime = System.currentTimeMillis();
    this.terminal = TerminalBuilder.builder().dumb(true).build();
}
 
Example #26
Source File: CompletionTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
@AfterAll
public static void tearDown() {
  System.setProperty(TerminalBuilder.PROP_DUMB,
      Boolean.FALSE.toString());
  sqlLine.setExit(true);
}
 
Example #27
Source File: ConsoleIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Constructor
 *
 * @param input
 * @param out
 * @param info
 * @throws IOException
 */
public ConsoleIO(InputStream input, OutputStream out, ConsoleState info) throws IOException {
	this.terminal = TerminalBuilder.builder().system(false).streams(input, out).build();
	this.appInfo = info;
	this.input = buildLineReader();
}
 
Example #28
Source File: ConsoleIO.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 2 votes vote down vote up
/**
 * Constructor
 *
 * @param info
 * @throws IOException
 */
public ConsoleIO(ConsoleState info) throws IOException {
	this.terminal = TerminalBuilder.terminal();
	this.appInfo = info;
	this.input = buildLineReader();
}