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 Project: presto   Author: prestosql   File: Query.java    License: 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 #2
Source Project: flink   Author: apache   File: CliClientTest.java    License: 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 #3
Source Project: flink   Author: apache   File: CliClientTest.java    License: 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 #4
Source Project: Arend   Author: JetBrains   File: JLineCliRepl.java    License: 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 #5
Source Project: presto   Author: prestosql   File: TestInsecureQueryRunner.java    License: 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 #6
Source Project: Flink-CEPplus   Author: ljygz   File: CliView.java    License: 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 Project: flink   Author: apache   File: CliClientTest.java    License: 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 Project: flink   Author: flink-tpc-ds   File: CliView.java    License: 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 Project: flink   Author: flink-tpc-ds   File: CliClientTest.java    License: 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 #10
Source Project: flink   Author: flink-tpc-ds   File: CliClientTest.java    License: 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 #11
Source Project: flink   Author: apache   File: CliClientTest.java    License: 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 #12
Source Project: flink   Author: apache   File: CliClientTest.java    License: 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 #13
Source Project: samza   Author: apache   File: QueryResultLogView.java    License: 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 #14
Source Project: ssh-shell-spring-boot   Author: fonimus   File: AbstractShellHelperTest.java    License: 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 #15
Source Project: ssh-shell-spring-boot   Author: fonimus   File: StacktraceCommandTest.java    License: 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 #16
Source Project: flink   Author: apache   File: CliView.java    License: 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 #17
Source Project: ssh-shell-spring-boot   Author: fonimus   File: DemoCommandTest.java    License: 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 #18
Source Project: ratis   Author: hortonworks   File: ListLogsCommand.java    License: 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 #19
Source Project: TerminalConsoleAppender   Author: Minecrell   File: SimpleTerminalConsole.java    License: 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 #20
Source Project: incubator-ratis   Author: apache   File: ListLogsCommand.java    License: 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 #21
Source Project: ratis   Author: hortonworks   File: DeleteLogCommand.java    License: 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());
  }
}
 
Example #22
Source Project: schedge   Author: BUGS-NYU   File: ConsoleProgressBarConsumer.java    License: MIT License 5 votes vote down vote up
private static int getTerminalWidth(Terminal terminal) {
  if (terminal != null &&
      terminal.getWidth() >= 10) // Workaround for issue #23 under IntelliJ
    return terminal.getWidth();
  else
    return 80; // Default width
}
 
Example #23
Source Project: sqlline   Author: julianhyde   File: SqlLineSignalHandler.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void handle(Terminal.Signal sig) {
  try {
    synchronized (this) {
      if (dispatchCallback != null) {
        dispatchCallback.forceKillSqlQuery();
        dispatchCallback.setToCancel();
      }
    }
  } catch (SQLException ex) {
    throw new RuntimeException(ex);
  }
}
 
Example #24
Source Project: sqlline   Author: julianhyde   File: SqlLine.java    License: 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 #25
Source Project: presto   Author: prestosql   File: ConsolePrinter.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean detectRealTerminal()
{
    try (Terminal terminal = terminal()) {
        return !Terminal.TYPE_DUMB.equals(terminal.getType()) &&
                !Terminal.TYPE_DUMB_COLOR.equals(terminal.getType());
    }
    catch (IOException e) {
        return false;
    }
}
 
Example #26
Source Project: presto   Author: prestosql   File: StatusPrinter.java    License: Apache License 2.0 5 votes vote down vote up
private static int readKey(Terminal terminal)
{
    try {
        return terminal.reader().read(1L);
    }
    catch (IOException e) {
        return -1;
    }
}
 
Example #27
Source Project: presto   Author: prestosql   File: TestQueryRunner.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCookie()
        throws Exception
{
    server.enqueue(new MockResponse()
            .setResponseCode(307)
            .addHeader(LOCATION, server.url("/v1/statement"))
            .addHeader(SET_COOKIE, "a=apple"));
    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), false);

    try (Terminal terminal = terminal()) {
        try (Query query = queryRunner.startQuery("first query will introduce a cookie")) {
            query.renderOutput(terminal, nullPrintStream(), nullPrintStream(), CSV, false, false);
        }
        try (Query query = queryRunner.startQuery("second query should carry the cookie")) {
            query.renderOutput(terminal, nullPrintStream(), nullPrintStream(), CSV, false, false);
        }
    }

    assertNull(server.takeRequest().getHeader("Cookie"));
    assertEquals(server.takeRequest().getHeader("Cookie"), "a=apple");
    assertEquals(server.takeRequest().getHeader("Cookie"), "a=apple");
}
 
Example #28
Source Project: Flink-CEPplus   Author: ljygz   File: CliView.java    License: Apache License 2.0 5 votes vote down vote up
private void unsetTerminalFullScreen() {
	final Terminal terminal = client.getTerminal();

	terminal.puts(Capability.exit_ca_mode);
	terminal.puts(Capability.keypad_local);
	terminal.puts(Capability.cursor_visible);
}
 
Example #29
Source Project: Flink-CEPplus   Author: ljygz   File: CliClient.java    License: 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 #30
Source Project: Flink-CEPplus   Author: ljygz   File: TerminalUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Terminal createDummyTerminal() {
	try {
		return new DumbTerminal(new MockInputStream(), new MockOutputStream());
	} catch (IOException e) {
		throw new RuntimeException("Unable to create dummy terminal.");
	}
}