org.jline.terminal.Terminal Java Examples

The following examples show how to use org.jline.terminal.Terminal. 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: AbstractShellHelperTest.java    From ssh-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@BeforeEach
public void each() {
    h = new SshShellHelper();
    List<String> auth = Collections.singletonList("ROLE_ACTUATOR");
    lr = mock(LineReader.class);
    ter = mock(Terminal.class);
    writer = mock(PrintWriter.class);
    when(ter.writer()).thenReturn(writer);
    reader = mock(NonBlockingReader.class);
    when(ter.reader()).thenReturn(reader);
    when(lr.getTerminal()).thenReturn(ter);

    SshContext ctx = new SshContext(new SshShellRunnable(new SshShellProperties(), mockChannelSession(4L), null,
            null, null,
            null, null, null, null, null, null, null, null, null), ter, lr,
            new SshAuthentication("user", "user", null, null, auth));
    SshShellCommandFactory.SSH_THREAD_CONTEXT.set(ctx);
    when(ter.getType()).thenReturn("osx");
    when(ter.getSize()).thenReturn(new Size(123, 40));
}
 
Example #2
Source File: CliView.java    From flink with Apache License 2.0 6 votes vote down vote up
private Tuple2<Attributes, Map<Signal, SignalHandler>> prepareTerminal() {
	final Terminal terminal = client.getTerminal();

	final Attributes prevAttributes = terminal.getAttributes();
	// adopted from org.jline.builtins.Nano
	// see also https://en.wikibooks.org/wiki/Serial_Programming/termios#Basic_Configuration_of_a_Serial_Interface

	// no line processing
	// canonical mode off, echo off, echo newline off, extended input processing off
	Attributes newAttr = new Attributes(prevAttributes);
	newAttr.setLocalFlags(EnumSet.of(LocalFlag.ICANON, LocalFlag.ECHO, LocalFlag.IEXTEN), false);
	// turn off input processing
	newAttr.setInputFlags(EnumSet.of(Attributes.InputFlag.IXON, Attributes.InputFlag.ICRNL, Attributes.InputFlag.INLCR), false);
	// one input byte is enough to return from read, inter-character timer off
	newAttr.setControlChar(Attributes.ControlChar.VMIN, 1);
	newAttr.setControlChar(Attributes.ControlChar.VTIME, 0);
	newAttr.setControlChar(Attributes.ControlChar.VINTR, 0);
	terminal.setAttributes(newAttr);

	final Map<Signal, SignalHandler> prevSignals = new HashMap<>();
	prevSignals.put(Signal.WINCH, terminal.handle(Signal.WINCH, this::handleSignal));
	prevSignals.put(Signal.INT, terminal.handle(Signal.INT, this::handleSignal));
	prevSignals.put(Signal.QUIT, terminal.handle(Signal.QUIT, this::handleSignal));

	return Tuple2.of(prevAttributes, prevSignals);
}
 
Example #3
Source File: ListLogsCommand.java    From ratis with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 0) {
    terminal.writer().println("ERROR - Usage: list");
    return;
  }

  try {
    List<LogInfo> logs = client.listLogs();
    StringBuilder sb = new StringBuilder();
    for (LogInfo log : logs) {
      if (sb.length() > 0) {
        sb.append("\n");
      }
      sb.append(log.getLogName().getName());
    }
    terminal.writer().println(sb.toString());
  } catch (IOException e) {
    terminal.writer().println("Failed to list available logs");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #4
Source File: SimpleTerminalConsole.java    From TerminalConsoleAppender with MIT License 6 votes vote down vote up
private void readCommands(Terminal terminal) {
    LineReader reader = buildReader(LineReaderBuilder.builder().terminal(terminal));
    TerminalConsoleAppender.setReader(reader);

    try {
        String line;
        while (isRunning()) {
            try {
                line = reader.readLine("> ");
            } catch (EndOfFileException ignored) {
                // Continue reading after EOT
                continue;
            }

            if (line == null) {
                break;
            }

            processInput(line);
        }
    } catch (UserInterruptException e) {
        shutdown();
    } finally {
        TerminalConsoleAppender.setReader(null);
    }
}
 
Example #5
Source File: DemoCommandTest.java    From ssh-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@BeforeAll
static void prepare() {
    cmd = new DemoCommand(new SshShellHelper());
    terminal = mock(Terminal.class);
    when(terminal.getSize()).thenReturn(size);
    PrintWriter writer = mock(PrintWriter.class);
    lr = mock(LineReader.class);
    ParsedLine line = mock(ParsedLine.class);
    when(line.line()).thenReturn("y");
    when(lr.getParsedLine()).thenReturn(line);
    when(lr.getTerminal()).thenReturn(terminal);
    when(terminal.writer()).thenReturn(writer);
    reader = mock(NonBlockingReader.class);
    when(terminal.reader()).thenReturn(reader);
    when(terminal.getType()).thenReturn("osx");
    auth = new SshAuthentication("user", "user", null, null, null);
    SshContext ctx = new SshContext(new SshShellRunnable(new SshShellProperties(), null, null, null, null, null,
            null, null, null, null, null, null, null, null), terminal, lr, auth);
    SshShellCommandFactory.SSH_THREAD_CONTEXT.set(ctx);
}
 
Example #6
Source File: CliView.java    From flink with Apache License 2.0 6 votes vote down vote up
private Tuple2<Attributes, Map<Signal, SignalHandler>> prepareTerminal() {
	final Terminal terminal = client.getTerminal();

	final Attributes prevAttributes = terminal.getAttributes();
	// adopted from org.jline.builtins.Nano
	// see also https://en.wikibooks.org/wiki/Serial_Programming/termios#Basic_Configuration_of_a_Serial_Interface

	// no line processing
	// canonical mode off, echo off, echo newline off, extended input processing off
	Attributes newAttr = new Attributes(prevAttributes);
	newAttr.setLocalFlags(EnumSet.of(LocalFlag.ICANON, LocalFlag.ECHO, LocalFlag.IEXTEN), false);
	// turn off input processing
	newAttr.setInputFlags(EnumSet.of(Attributes.InputFlag.IXON, Attributes.InputFlag.ICRNL, Attributes.InputFlag.INLCR), false);
	// one input byte is enough to return from read, inter-character timer off
	newAttr.setControlChar(Attributes.ControlChar.VMIN, 1);
	newAttr.setControlChar(Attributes.ControlChar.VTIME, 0);
	newAttr.setControlChar(Attributes.ControlChar.VINTR, 0);
	terminal.setAttributes(newAttr);

	final Map<Signal, SignalHandler> prevSignals = new HashMap<>();
	prevSignals.put(Signal.WINCH, terminal.handle(Signal.WINCH, this::handleSignal));
	prevSignals.put(Signal.INT, terminal.handle(Signal.INT, this::handleSignal));
	prevSignals.put(Signal.QUIT, terminal.handle(Signal.QUIT, this::handleSignal));

	return Tuple2.of(prevAttributes, prevSignals);
}
 
Example #7
Source File: CliClientTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testHistoryFile() throws Exception {
	final SessionContext context = new SessionContext("test-session", new Environment());
	final MockExecutor mockExecutor = new MockExecutor();
	String sessionId = mockExecutor.openSession(context);

	InputStream inputStream = new ByteArrayInputStream("help;\nuse catalog cat;\n".getBytes());
	CliClient cliClient = null;
	try (Terminal terminal = new DumbTerminal(inputStream, new MockOutputStream())) {
		Path historyFilePath = File.createTempFile("history", "tmp").toPath();
		cliClient = new CliClient(terminal, sessionId, mockExecutor, historyFilePath);
		cliClient.open();
		List<String> content = Files.readAllLines(historyFilePath);
		assertEquals(2, content.size());
		assertTrue(content.get(0).contains("help"));
		assertTrue(content.get(1).contains("use catalog cat"));
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example #8
Source File: CliView.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private Tuple2<Attributes, Map<Signal, SignalHandler>> prepareTerminal() {
	final Terminal terminal = client.getTerminal();

	final Attributes prevAttributes = terminal.getAttributes();
	// adopted from org.jline.builtins.Nano
	// see also https://en.wikibooks.org/wiki/Serial_Programming/termios#Basic_Configuration_of_a_Serial_Interface

	// no line processing
	// canonical mode off, echo off, echo newline off, extended input processing off
	Attributes newAttr = new Attributes(prevAttributes);
	newAttr.setLocalFlags(EnumSet.of(LocalFlag.ICANON, LocalFlag.ECHO, LocalFlag.IEXTEN), false);
	// turn off input processing
	newAttr.setInputFlags(EnumSet.of(Attributes.InputFlag.IXON, Attributes.InputFlag.ICRNL, Attributes.InputFlag.INLCR), false);
	// one input byte is enough to return from read, inter-character timer off
	newAttr.setControlChar(Attributes.ControlChar.VMIN, 1);
	newAttr.setControlChar(Attributes.ControlChar.VTIME, 0);
	newAttr.setControlChar(Attributes.ControlChar.VINTR, 0);
	terminal.setAttributes(newAttr);

	final Map<Signal, SignalHandler> prevSignals = new HashMap<>();
	prevSignals.put(Signal.WINCH, terminal.handle(Signal.WINCH, this::handleSignal));
	prevSignals.put(Signal.INT, terminal.handle(Signal.INT, this::handleSignal));
	prevSignals.put(Signal.QUIT, terminal.handle(Signal.QUIT, this::handleSignal));

	return Tuple2.of(prevAttributes, prevSignals);
}
 
Example #9
Source File: StacktraceCommandTest.java    From ssh-shell-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
void stacktrace() {
    TypePostProcessorResultHandler.THREAD_CONTEXT.set(null);

    StacktraceCommand cmd = new StacktraceCommand();
    Terminal terminal = Mockito.mock(Terminal.class);
    Mockito.when(terminal.writer()).thenReturn(new PrintWriter(new StringWriter()));
    cmd.setTerminal(terminal);
    cmd.stacktrace();
    Mockito.verify(terminal, Mockito.never()).writer();

    TypePostProcessorResultHandler.THREAD_CONTEXT.set(new IllegalArgumentException("[TEST]"));

    cmd.stacktrace();
    Mockito.verify(terminal, Mockito.times(1)).writer();

}
 
Example #10
Source File: TestInsecureQueryRunner.java    From presto with Apache License 2.0 6 votes vote down vote up
@Test
public void testInsecureConnection()
        throws Exception
{
    server.enqueue(new MockResponse()
            .addHeader(CONTENT_TYPE, "application/json")
            .setBody(createResults(server)));
    server.enqueue(new MockResponse()
            .addHeader(CONTENT_TYPE, "application/json")
            .setBody(createResults(server)));

    QueryRunner queryRunner = createQueryRunner(createClientSession(server), true);

    try (Terminal terminal = terminal()) {
        try (Query query = queryRunner.startQuery("query with insecure mode")) {
            query.renderOutput(terminal, nullPrintStream(), nullPrintStream(), CSV, false, false);
        }
    }

    assertEquals(server.takeRequest().getPath(), "/v1/statement");
}
 
Example #11
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 #12
Source File: ListLogsCommand.java    From incubator-ratis with Apache License 2.0 6 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 0) {
    terminal.writer().println("ERROR - Usage: list");
    return;
  }

  try {
    List<LogInfo> logs = client.listLogs();
    StringBuilder sb = new StringBuilder();
    for (LogInfo log : logs) {
      if (sb.length() > 0) {
        sb.append("\n");
      }
      sb.append(log.getLogName().getName());
    }
    terminal.writer().println(sb.toString());
  } catch (IOException e) {
    terminal.writer().println("Failed to list available logs");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #13
Source File: CliClientTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testUseNonExistingDB() throws Exception {
	Executor executor = mock(Executor.class);
	doThrow(new SqlExecutionException("mocked exception")).when(executor).useDatabase(any(), any());
	InputStream inputStream = new ByteArrayInputStream("use db;\n".getBytes());
	// don't care about the output
	OutputStream outputStream = new OutputStream() {
		@Override
		public void write(int b) throws IOException {
		}
	};
	CliClient cliClient = null;
	try (Terminal terminal = new DumbTerminal(inputStream, outputStream)) {
		cliClient = new CliClient(terminal, new SessionContext("test-session", new Environment()), executor);
		cliClient.open();
		verify(executor).useDatabase(any(), any());
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example #14
Source File: CliClientTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testUseNonExistingCatalog() throws Exception {
	Executor executor = mock(Executor.class);
	doThrow(new SqlExecutionException("mocked exception")).when(executor).useCatalog(any(), any());
	InputStream inputStream = new ByteArrayInputStream("use catalog cat;\n".getBytes());
	// don't care about the output
	OutputStream outputStream = new OutputStream() {
		@Override
		public void write(int b) throws IOException {
		}
	};
	CliClient cliClient = null;
	try (Terminal terminal = new DumbTerminal(inputStream, outputStream)) {
		cliClient = new CliClient(terminal, new SessionContext("test-session", new Environment()), executor);
		cliClient.open();
		verify(executor).useCatalog(any(), any());
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example #15
Source File: QueryResultLogView.java    From samza with Apache License 2.0 6 votes vote down vote up
private void handleSignal(Terminal.Signal signal) {
  switch (signal) {
    case INT:
    case QUIT:
      keepRunning = false;
      break;
    case TSTP:
      paused = true;
      break;
    case CONT:
      paused = false;
      break;
    case WINCH:
      updateTerminalSize();
      break;
  }
}
 
Example #16
Source File: CliClientTest.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * execute a sql statement and return the terminal output as string.
 */
private String testExecuteSql(TestingExecutor executor, String sql) throws IOException {
	InputStream inputStream = new ByteArrayInputStream((sql + "\n").getBytes());
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
	CliClient cliClient = null;
	SessionContext sessionContext = new SessionContext("test-session", new Environment());
	String sessionId = executor.openSession(sessionContext);

	try (Terminal terminal = new DumbTerminal(inputStream, outputStream)) {
		cliClient = new CliClient(terminal, sessionId, executor, File.createTempFile("history", "tmp").toPath());
		cliClient.open();
		return new String(outputStream.toByteArray());
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example #17
Source File: CliClientTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateTableWithInvalidDdl() throws Exception {
	TestingExecutor executor = new TestingExecutorBuilder().build();

	// proctimee() is invalid
	InputStream inputStream = new ByteArrayInputStream("create table tbl(a int, b as proctimee());\n".getBytes());
	ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
	CliClient cliClient = null;
	SessionContext sessionContext = new SessionContext("test-session", new Environment());
	String sessionId = executor.openSession(sessionContext);

	try (Terminal terminal = new DumbTerminal(inputStream, outputStream)) {
		cliClient = new CliClient(terminal, sessionId, executor, File.createTempFile("history", "tmp").toPath());
		cliClient.open();
		String output = new String(outputStream.toByteArray());
		assertTrue(output.contains("No match found for function signature proctimee()"));
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example #18
Source File: Query.java    From presto with Apache License 2.0 6 votes vote down vote up
public boolean renderOutput(Terminal terminal, PrintStream out, PrintStream errorChannel, OutputFormat outputFormat, boolean usePager, boolean showProgress)
{
    Thread clientThread = Thread.currentThread();
    SignalHandler oldHandler = terminal.handle(Signal.INT, signal -> {
        if (ignoreUserInterrupt.get() || client.isClientAborted()) {
            return;
        }
        client.close();
        clientThread.interrupt();
    });
    try {
        return renderQueryOutput(terminal, out, errorChannel, outputFormat, usePager, showProgress);
    }
    finally {
        terminal.handle(Signal.INT, oldHandler);
        Thread.interrupted(); // clear interrupt status
    }
}
 
Example #19
Source File: CliClientTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testUseNonExistingDB() throws Exception {
	TestingExecutor executor = new TestingExecutorBuilder()
		.setUseDatabaseConsumer((ignored1, ignored2) -> {
			throw new SqlExecutionException("mocked exception");
		})
		.build();
	InputStream inputStream = new ByteArrayInputStream("use db;\n".getBytes());
	SessionContext session = new SessionContext("test-session", new Environment());
	String sessionId = executor.openSession(session);

	CliClient cliClient = null;
	try (Terminal terminal = new DumbTerminal(inputStream, new MockOutputStream())) {
		cliClient = new CliClient(terminal, sessionId, executor, File.createTempFile("history", "tmp").toPath());

		cliClient.open();
		assertThat(executor.getNumUseDatabaseCalls(), is(1));
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example #20
Source File: CliClientTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Test
public void testUseNonExistingCatalog() throws Exception {
	TestingExecutor executor = new TestingExecutorBuilder()
		.setUseCatalogConsumer((ignored1, ignored2) -> {
			throw new SqlExecutionException("mocked exception");
		})
		.build();

	InputStream inputStream = new ByteArrayInputStream("use catalog cat;\n".getBytes());
	CliClient cliClient = null;
	SessionContext sessionContext = new SessionContext("test-session", new Environment());
	String sessionId = executor.openSession(sessionContext);

	try (Terminal terminal = new DumbTerminal(inputStream, new MockOutputStream())) {
		cliClient = new CliClient(terminal, sessionId, executor, File.createTempFile("history", "tmp").toPath());
		cliClient.open();
		assertThat(executor.getNumUseCatalogCalls(), is(1));
	} finally {
		if (cliClient != null) {
			cliClient.close();
		}
	}
}
 
Example #21
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 #22
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 #23
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 #24
Source File: HelpCommand.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  CommandFactory.getCommands()
      .values()
      .stream()
      .forEach((c) -> terminal.writer().println(c.getHelpMessage()));
}
 
Example #25
Source File: ReadLogCommand.java    From incubator-ratis with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 1) {
    terminal.writer().println("ERROR - Usage: read <name>");
    return;
  }
  String logName = args[0];
  try (LogStream stream = client.getLog(LogName.of(logName));
      LogReader reader = stream.createReader()) {
    long firstId = stream.getStartRecordId();
    long lastId = stream.getLastRecordId();
    StringBuilder sb = new StringBuilder();
    List<ByteBuffer> records = reader.readBulk((int) (lastId - firstId));
    for (ByteBuffer record : records) {
      if (sb.length() > 0) {
        sb.append(", ");
      }
      sb.append("\"");
      if (record != null) {
        String strData = new String(record.array(), record.arrayOffset(), record.remaining(), StandardCharsets.UTF_8);
        sb.append(strData);
      }
      sb.append("\"");
    }
    sb.insert(0, "[");
    sb.append("]");
    terminal.writer().println(sb.toString());
  } catch (Exception e) {
    terminal.writer().println("Failed to read from log");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #26
Source File: CreateLogCommand.java    From ratis with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 1) {
    terminal.writer().println("ERROR - Usage: create <name>");
    return;
  }
  String logName = args[0];
  try (LogStream stream = client.createLog(LogName.of(logName))) {
    terminal.writer().println("Created log '" + logName + "'");
  } catch (Exception e) {
    terminal.writer().println("Error creating log '" + logName + "'");
    e.printStackTrace(terminal.writer());
  }
}
 
Example #27
Source File: DefaultBuiltInCommand.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
/**
 * See:<a href=
 * "https://github.com/jline/jline3/issues/183">https://github.com/jline/jline3/issues/183</a>
 */
@ShellMethod(keys = { INTERNAL_CLEAR, INTERNAL_CLS }, group = DEFAULT_GROUP, help = "Clean up console history")
public void clear() {
	Terminal terminal = runner.getLineReader().getTerminal();
	terminal.puts(Capability.clear_screen);
	terminal.flush();
}
 
Example #28
Source File: AbstractCommandTest.java    From ssh-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
protected void setCtx(String response) throws Exception {
    LineReader lr = mock(LineReader.class);
    Terminal t = mock(Terminal.class);
    when(lr.getTerminal()).thenReturn(t);
    when(t.getSize()).thenReturn(new Size(300, 20));
    when(t.writer()).thenReturn(new PrintWriter("target/rh.tmp"));
    ParsedLine pl = mock(ParsedLine.class);
    when(pl.line()).thenReturn(response);
    when(lr.getParsedLine()).thenReturn(pl);
    SSH_THREAD_CONTEXT.set(new SshContext(null, t, lr, null));
}
 
Example #29
Source File: SshShellHelper.java    From ssh-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
private Terminal terminal() {
    SshContext sshContext = SshShellCommandFactory.SSH_THREAD_CONTEXT.get();
    if (sshContext == null) {
        throw new IllegalStateException("Unable to find ssh context");
    }
    return sshContext.getTerminal();
}
 
Example #30
Source File: DeleteLogCommand.java    From ratis with Apache License 2.0 5 votes vote down vote up
@Override
public void run(Terminal terminal, LineReader lineReader, LogServiceClient client, String[] args) {
  if (args.length != 1) {
    terminal.writer().println("ERROR - Usage: delete <name>");
    return;
  }
  String logName = args[0];
  try {
    client.deleteLog(LogName.of(logName));
    terminal.writer().println("Deleted log '" + logName + "'");
  } catch (IOException e) {
    terminal.writer().println("Error deleting log '" + logName + "'");
    e.printStackTrace(terminal.writer());
  }
}