Java Code Examples for org.jline.utils.AttributedStyle

The following examples show how to use org.jline.utils.AttributedStyle. These examples are extracted from open source projects. 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: Flink-CEPplus   Author: ljygz   File: CliChangelogResultView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<AttributedString> computeMainHeaderLines() {
	final AttributedStringBuilder schemaHeader = new AttributedStringBuilder();

	// add change column
	schemaHeader.append(' ');
	schemaHeader.style(AttributedStyle.DEFAULT.underline());
	schemaHeader.append("+/-");
	schemaHeader.style(AttributedStyle.DEFAULT);

	Arrays.stream(resultDescriptor.getResultSchema().getFieldNames()).forEach(s -> {
		schemaHeader.append(' ');
		schemaHeader.style(AttributedStyle.DEFAULT.underline());
		normalizeColumn(schemaHeader, s, MAX_COLUMN_WIDTH);
		schemaHeader.style(AttributedStyle.DEFAULT);
	});

	return Collections.singletonList(schemaHeader.toAttributedString());
}
 
Example #2
Source Project: flink   Author: flink-tpc-ds   File: CliChangelogResultView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<AttributedString> computeMainHeaderLines() {
	final AttributedStringBuilder schemaHeader = new AttributedStringBuilder();

	// add change column
	schemaHeader.append(' ');
	schemaHeader.style(AttributedStyle.DEFAULT.underline());
	schemaHeader.append("+/-");
	schemaHeader.style(AttributedStyle.DEFAULT);

	Arrays.stream(resultDescriptor.getResultSchema().getFieldNames()).forEach(s -> {
		schemaHeader.append(' ');
		schemaHeader.style(AttributedStyle.DEFAULT.underline());
		normalizeColumn(schemaHeader, s, MAX_COLUMN_WIDTH);
		schemaHeader.style(AttributedStyle.DEFAULT);
	});

	return Collections.singletonList(schemaHeader.toAttributedString());
}
 
Example #3
Source Project: graph-examples   Author: datastax   File: App.java    License: Apache License 2.0 6 votes vote down vote up
private static String highlightTraversal(String traversal) {
    return new AttributedStringBuilder()
            .append(traversal)
            .styleMatches(
                    Pattern.compile("\"[^\"]*\""),
                    AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN).faint())
            .styleMatches(
                    Pattern.compile("\\b[0-9]+(L|(\\.[0-9]+))?\\b"),
                    AttributedStyle.DEFAULT.foreground(AttributedStyle.CYAN).faint())
            .styleMatches(
                    Pattern.compile("\\b(assign|gt|id|keys|local|lt|sum|values)\\b"),
                    AttributedStyle.DEFAULT.foreground(AttributedStyle.MAGENTA).faint())
            .styleMatches(
                    Pattern.compile("\\b(as|by|emit|from)\\b"),
                    AttributedStyle.DEFAULT.italic())
            .styleMatches(
                    Pattern.compile("__\\."),
                    AttributedStyle.DEFAULT.foreground(AttributedStyle.BLACK | AttributedStyle.BRIGHT))
            .toAnsi();
}
 
Example #4
Source Project: graph-examples   Author: datastax   File: App.java    License: Apache License 2.0 6 votes vote down vote up
private static String highlightResult(String result) {
    return new AttributedStringBuilder()
            .append(result)
            .styleMatches(
                    Pattern.compile("[a-z]+\\b(?![\\[=])"),
                    AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN).faint())
            .styleMatches(
                    Pattern.compile("\\b[0-9]+(L|(\\.[0-9]+))?\\b"),
                    AttributedStyle.DEFAULT.foreground(AttributedStyle.CYAN))
            .styleMatches(
                    Pattern.compile("[a-z]+(?==)"),
                    AttributedStyle.DEFAULT)
            .styleMatches(
                    Pattern.compile("[a-z]+\\b(?=\\[)"),
                    AttributedStyle.DEFAULT.faint())
            .styleMatches(
                    Pattern.compile("[a-z]+\\b(?==)"),
                    AttributedStyle.DEFAULT.foreground(AttributedStyle.MAGENTA).faint())
            .toAnsi();
}
 
Example #5
Source Project: samza   Author: apache   File: CliCommandHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Prints to terminal the help message of the commands this handler handles
 */
public void printHelpMessage() {
  AttributedStringBuilder builder = new AttributedStringBuilder();
  builder.append("The following commands are supported by ")
      .append(CliConstants.APP_NAME)
      .append("by handler ")
      .append(this.getClass().getName())
      .append(" at the moment.\n\n");

  for (CliCommandType cmdType : CliCommandType.values()) {
    if (cmdType == CliCommandType.INVALID_COMMAND)
      continue;

    String cmdText = cmdType.getCommandName();
    String cmdDescription = cmdType.getDescription();

    builder.style(AttributedStyle.DEFAULT.bold())
        .append(cmdText)
        .append("\t\t")
        .style(AttributedStyle.DEFAULT)
        .append(cmdDescription)
        .append("\n");
  }
  writer.println(builder.toAnsi());
}
 
Example #6
Source Project: samza   Author: apache   File: QueryResultLogView.java    License: Apache License 2.0 6 votes vote down vote up
private void drawStatusBar(int rowsInBuffer) {
  terminal.puts(InfoCmp.Capability.save_cursor);
  terminal.puts(InfoCmp.Capability.cursor_address, height - 1, 0);
  AttributedStyle statusBarStyle = AttributedStyle.DEFAULT.background(AttributedStyle.WHITE)
          .foreground(AttributedStyle.BLACK);
  AttributedStringBuilder attrBuilder = new AttributedStringBuilder()
          .style(statusBarStyle.bold().italic())
          .append("Q")
          .style(statusBarStyle)
          .append(": Quit     ")
          .style(statusBarStyle.bold().italic())
          .append("SPACE")
          .style(statusBarStyle)
          .append(": Pause/Resume     ")
          .append(String.valueOf(rowsInBuffer) + " rows in buffer     ");
  if (paused) {
    attrBuilder.style(statusBarStyle.bold().foreground(AttributedStyle.RED).blink())
            .append("PAUSED");
  }
  String statusBarText = attrBuilder.toAnsi();
  terminal.writer().print(statusBarText);
  terminal.flush();
  terminal.puts(InfoCmp.Capability.restore_cursor);
}
 
Example #7
Source Project: samza   Author: apache   File: CliHighlighter.java    License: Apache License 2.0 6 votes vote down vote up
public AttributedString highlight(LineReader reader, String buffer) {
  AttributedStringBuilder builder = new AttributedStringBuilder();
  List<String> tokens = splitWithSpace(buffer);

  for (String token : tokens) {
    if (isKeyword(token)) {
      builder.style(AttributedStyle.BOLD.foreground(AttributedStyle.YELLOW))
              .append(token);
    } else {
      builder.style(AttributedStyle.DEFAULT)
              .append(token);
    }
  }

  return builder.toAttributedString();
}
 
Example #8
Source Project: flink   Author: apache   File: CliChangelogResultView.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected List<AttributedString> computeMainHeaderLines() {
	final AttributedStringBuilder schemaHeader = new AttributedStringBuilder();

	// add change column
	schemaHeader.append(' ');
	schemaHeader.style(AttributedStyle.DEFAULT.underline());
	schemaHeader.append("+/-");
	schemaHeader.style(AttributedStyle.DEFAULT);

	Arrays.stream(resultDescriptor.getResultSchema().getFieldNames()).forEach(s -> {
		schemaHeader.append(' ');
		schemaHeader.style(AttributedStyle.DEFAULT.underline());
		normalizeColumn(schemaHeader, s, MAX_COLUMN_WIDTH);
		schemaHeader.style(AttributedStyle.DEFAULT);
	});

	return Collections.singletonList(schemaHeader.toAttributedString());
}
 
Example #9
Source Project: sqlline   Author: julianhyde   File: AnsiConsoleOutputFormat.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public int print(Rows rows) {
  int index = 0;
  final int width = getCalculatedWidth();

  // normalize the columns sizes
  rows.normalizeWidths(sqlLine.getOpts().getMaxColumnWidth());

  for (; rows.hasNext();) {
    Rows.Row row = rows.next();
    AttributedString cbuf = getOutputString(
        row, index == 0 ? AttributedStyle.INVERSE : AttributedStyle.DEFAULT);
    cbuf = cbuf.substring(0, Math.min(cbuf.length(), width));

    printRow(cbuf);

    index++;
  }

  return index - 1;
}
 
Example #10
Source Project: sqlline   Author: julianhyde   File: VerticalOutputFormat.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void printRow(Rows rows, Rows.Row header, Rows.Row row) {
  String[] head = header.values;
  String[] vals = row.values;
  int headWidth = 0;
  for (int i = 0; (i < head.length) && (i < vals.length); i++) {
    headWidth = Math.max(headWidth, head[i].length());
  }

  headWidth += 2;

  for (int i = 0; (i < head.length) && (i < vals.length); i++) {
    sqlLine.output(
        new AttributedStringBuilder()
            .append(rpad(head[i], headWidth), AttributedStyle.BOLD)
            .append((vals[i] == null) ? "" : vals[i])
            .toAttributedString());
  }

  sqlLine.output(""); // spacing
}
 
Example #11
Source Project: sqlline   Author: julianhyde   File: SqlLine.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
void runBatch(List<String> statements) {
  try (Statement stmnt = createStatement()) {
    for (String statement : statements) {
      stmnt.addBatch(statement);
    }

    int[] counts = stmnt.executeBatch();
    if (counts == null) {
      counts = new int[0];
    }

    output(new AttributedStringBuilder()
        .append(rpad("COUNT", 8), AttributedStyle.BOLD)
        .append("STATEMENT", AttributedStyle.BOLD)
        .toAttributedString());

    for (int i = 0; i < counts.length; i++) {
      output(new AttributedStringBuilder()
          .append(rpad(counts[i] + "", 8))
          .append(statements.get(i))
          .toAttributedString());
    }
  } catch (Exception e) {
    handleException(e);
  }
}
 
Example #12
Source Project: sqlline   Author: julianhyde   File: HighlightStyle.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/** Creates a HighlightStyle.
 *
 * @param keywordStyle Style for SQL keywords
 * @param commandStyle Style for SQLLine commands
 * @param quotedStyle Style for SQL character literals
 * @param identifierStyle Style for SQL identifiers
 * @param commentStyle Style for SQL comments
 * @param numberStyle Style for numeric values
 * @param defaultStyle Default style
 */
public HighlightStyle(AttributedStyle keywordStyle,
    AttributedStyle commandStyle,
    AttributedStyle quotedStyle,
    AttributedStyle identifierStyle,
    AttributedStyle commentStyle,
    AttributedStyle numberStyle,
    AttributedStyle defaultStyle) {
  this.keywordStyle = keywordStyle;
  this.commandStyle = commandStyle;
  this.quotedStyle = quotedStyle;
  this.identifierStyle = identifierStyle;
  this.commentStyle = commentStyle;
  this.numberStyle = numberStyle;
  this.defaultStyle = defaultStyle;
}
 
Example #13
Source Project: sqlline   Author: julianhyde   File: SqlLineHighlighterTest.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void checkDefaultLine(
    SqlLine sqlLine,
    String line,
    SqlLineHighlighter defaultHighlighter) {
  final AttributedString attributedString =
      defaultHighlighter.highlight(sqlLine.getLineReader(), line);
  int defaultStyle = AttributedStyle.DEFAULT.getStyle();

  for (int i = 0; i < line.length(); i++) {
    if (Character.isWhitespace(line.charAt(i))) {
      continue;
    }
    assertEquals(i == 0 ? defaultStyle + 32 : defaultStyle,
        attributedString.styleAt(i).getStyle(),
        getFailedStyleMessage(line, i, "default"));
  }
}
 
Example #14
Source Project: Flink-CEPplus   Author: ljygz   File: CliResultView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<AttributedString> computeMainLines() {
	final List<AttributedString> lines = new ArrayList<>();

	int lineIdx = 0;
	for (String[] line : results) {
		final AttributedStringBuilder row = new AttributedStringBuilder();

		// highlight selected row
		if (lineIdx == selectedRow) {
			row.style(AttributedStyle.DEFAULT.inverse());
		}

		for (int colIdx = 0; colIdx < line.length; colIdx++) {
			final String col = line[colIdx];
			final int columnWidth = computeColumnWidth(colIdx);

			row.append(' ');
			// check if value was present before last update, if not, highlight it
			// we don't highlight if the retrieval stopped
			// both inverse and bold together do not work correctly
			if (previousResults != null && lineIdx != selectedRow && refreshThread.isRunning &&
					(lineIdx >= previousResults.size() || !col.equals(previousResults.get(lineIdx)[colIdx]))) {
				row.style(AttributedStyle.BOLD);
				normalizeColumn(row, col, columnWidth);
				row.style(AttributedStyle.DEFAULT);
			} else {
				normalizeColumn(row, col, columnWidth);
			}
		}
		lines.add(row.toAttributedString());

		lineIdx++;
	}

	return lines;
}
 
Example #15
Source Project: Flink-CEPplus   Author: ljygz   File: CliView.java    License: Apache License 2.0 5 votes vote down vote up
private AttributedString computeTitleLine() {
	final String title = getTitle();
	final AttributedStringBuilder titleLine = new AttributedStringBuilder();
	titleLine.style(AttributedStyle.INVERSE);
	final int totalMargin = width - title.length();
	final int margin = totalMargin / 2;
	repeatChar(titleLine, ' ', margin);
	titleLine.append(title);
	repeatChar(titleLine, ' ', margin + (totalMargin % 2));
	return titleLine.toAttributedString();
}
 
Example #16
Source Project: Flink-CEPplus   Author: ljygz   File: CliUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<AttributedString> formatTwoLineHelpOptions(int width, List<Tuple2<String, String>> options) {
	final AttributedStringBuilder line1 = new AttributedStringBuilder();
	final AttributedStringBuilder line2 = new AttributedStringBuilder();

	// we assume that every options has not more than 11 characters (+ key and space)
	final int columns = (int) Math.ceil(((double) options.size()) / 2);
	final int space = (width - CliStrings.DEFAULT_MARGIN.length() - columns * 13) / columns;
	final Iterator<Tuple2<String, String>> iter = options.iterator();
	while (iter.hasNext()) {
		// first line
		Tuple2<String, String> option = iter.next();
		line1.style(AttributedStyle.DEFAULT.inverse());
		line1.append(option.f0);
		line1.style(AttributedStyle.DEFAULT);
		line1.append(' ');
		line1.append(option.f1);
		repeatChar(line1, ' ', (11 - option.f1.length()) + space);
		// second line
		if (iter.hasNext()) {
			option = iter.next();
			line2.style(AttributedStyle.DEFAULT.inverse());
			line2.append(option.f0);
			line2.style(AttributedStyle.DEFAULT);
			line2.append(' ');
			line2.append(option.f1);
			repeatChar(line2, ' ', (11 - option.f1.length()) + space);
		}
	}

	return Arrays.asList(line1.toAttributedString(), line2.toAttributedString());
}
 
Example #17
Source Project: Flink-CEPplus   Author: ljygz   File: CliChangelogResultView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<AttributedString> computeHeaderLines() {

	final AttributedStringBuilder statusLine = new AttributedStringBuilder();
	statusLine.style(AttributedStyle.INVERSE);
	// left
	final String left;
	if (isRetrieving()) {
		left = CliStrings.DEFAULT_MARGIN + CliStrings.RESULT_REFRESH_INTERVAL + ' ' + REFRESH_INTERVALS.get(refreshInterval).f0;
	} else {
		left = CliStrings.DEFAULT_MARGIN + CliStrings.RESULT_STOPPED;
	}

	// right
	final String right;
	if (lastRetrieval == null) {
		right = CliStrings.RESULT_LAST_REFRESH + ' ' + CliStrings.RESULT_REFRESH_UNKNOWN + CliStrings.DEFAULT_MARGIN;
	} else {
		right = CliStrings.RESULT_LAST_REFRESH + ' ' + lastRetrieval.format(TIME_FORMATTER) + CliStrings.DEFAULT_MARGIN;
	}
	// all together
	final int middleSpace = getWidth() - left.length() - right.length();
	statusLine.append(left);
	repeatChar(statusLine, ' ', middleSpace);
	statusLine.append(right);

	return Arrays.asList(statusLine.toAttributedString(), AttributedString.EMPTY);
}
 
Example #18
Source Project: Flink-CEPplus   Author: ljygz   File: CliClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CLI instance with a custom terminal. Make sure to close the CLI instance
 * afterwards using {@link #close()}.
 */
@VisibleForTesting
public CliClient(Terminal terminal, SessionContext context, Executor executor) {
	this.terminal = terminal;
	this.context = context;
	this.executor = executor;

	// make space from previous output and test the writer
	terminal.writer().println();
	terminal.writer().flush();

	// initialize line lineReader
	lineReader = LineReaderBuilder.builder()
		.terminal(terminal)
		.appName(CliStrings.CLI_NAME)
		.parser(new SqlMultiLineParser())
		.completer(new SqlCompleter(context, executor))
		.build();
	// this option is disabled for now for correct backslash escaping
	// a "SELECT '\'" query should return a string with a backslash
	lineReader.option(LineReader.Option.DISABLE_EVENT_EXPANSION, true);
	// set strict "typo" distance between words when doing code completion
	lineReader.setVariable(LineReader.ERRORS, 1);
	// perform code completion case insensitive
	lineReader.option(LineReader.Option.CASE_INSENSITIVE, true);

	// create prompt
	prompt = new AttributedStringBuilder()
		.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN))
		.append("Flink SQL")
		.style(AttributedStyle.DEFAULT)
		.append("> ")
		.toAnsi();
}
 
Example #19
Source Project: Flink-CEPplus   Author: ljygz   File: CliStrings.java    License: Apache License 2.0 5 votes vote down vote up
public static AttributedString messageInfo(String message) {
	return new AttributedStringBuilder()
		.style(AttributedStyle.DEFAULT.bold().foreground(AttributedStyle.BLUE))
		.append("[INFO] ")
		.append(message)
		.toAttributedString();
}
 
Example #20
Source Project: Flink-CEPplus   Author: ljygz   File: CliStrings.java    License: Apache License 2.0 5 votes vote down vote up
public static AttributedString messageError(String message, String s) {
	final AttributedStringBuilder builder = new AttributedStringBuilder()
		.style(AttributedStyle.DEFAULT.bold().foreground(AttributedStyle.RED))
		.append("[ERROR] ")
		.append(message);

	if (s != null) {
		builder
			.append(" Reason:\n")
			.append(s);
	}

	return builder.toAttributedString();
}
 
Example #21
Source Project: Flink-CEPplus   Author: ljygz   File: CliStrings.java    License: Apache License 2.0 5 votes vote down vote up
private static AttributedString formatCommand(SqlCommand cmd, String description) {
	return new AttributedStringBuilder()
		.style(AttributedStyle.DEFAULT.bold())
		.append(cmd.toString())
		.append("\t\t")
		.style(AttributedStyle.DEFAULT)
		.append(description)
		.append('\n')
		.toAttributedString();
}
 
Example #22
Source Project: Flink-CEPplus   Author: ljygz   File: CliTableResultView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<AttributedString> computeMainHeaderLines() {
	final AttributedStringBuilder schemaHeader = new AttributedStringBuilder();

	Arrays.stream(resultDescriptor.getResultSchema().getFieldNames()).forEach(s -> {
		schemaHeader.append(' ');
		schemaHeader.style(AttributedStyle.DEFAULT.underline());
		normalizeColumn(schemaHeader, s, MAX_COLUMN_WIDTH);
		schemaHeader.style(AttributedStyle.DEFAULT);
	});

	return Collections.singletonList(schemaHeader.toAttributedString());
}
 
Example #23
Source Project: Flink-CEPplus   Author: ljygz   File: CliRowView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<AttributedString> computeMainLines() {
	final List<AttributedString> lines = new ArrayList<>();

	final AttributedStringBuilder sb = new AttributedStringBuilder();
	IntStream.range(0, row.length).forEach(i -> {
		final String name = columnNames[i];
		final String type = columnTypes[i];

		sb.setLength(0);
		sb.append(CliStrings.DEFAULT_MARGIN);
		sb.style(AttributedStyle.BOLD);
		sb.append(name);
		sb.append(" (");
		sb.append(type);
		sb.append(')');
		sb.append(':');
		lines.add(sb.toAttributedString());

		sb.setLength(0);
		sb.append(CliStrings.DEFAULT_MARGIN);
		sb.style(AttributedStyle.DEFAULT);
		sb.append(row[i]);
		lines.add(sb.toAttributedString());

		lines.add(AttributedString.EMPTY);
	});

	return lines;
}
 
Example #24
Source Project: Flink-CEPplus   Author: ljygz   File: CliInputView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<AttributedString> computeMainLines() {
	final List<AttributedString> lines = new ArrayList<>();

	// space
	IntStream.range(0, getVisibleMainHeight() / 2 - 2).forEach((i) -> lines.add(AttributedString.EMPTY));

	// title
	lines.add(new AttributedString(CliStrings.DEFAULT_MARGIN + inputTitle));

	// input line
	final AttributedStringBuilder inputLine = new AttributedStringBuilder();
	inputLine.append(CliStrings.DEFAULT_MARGIN + "> ");
	final String input = currentInput.toString();
	// add string left of cursor
	inputLine.append(currentInput.substring(0, cursorPos));
	inputLine.style(AttributedStyle.DEFAULT.inverse().blink());
	if (cursorPos < input.length()) {
		inputLine.append(input.charAt(cursorPos));
		inputLine.style(AttributedStyle.DEFAULT);
		inputLine.append(input.substring(cursorPos + 1, input.length()));
	} else {
		inputLine.append(' '); // show the cursor at the end
	}

	lines.add(inputLine.toAttributedString());

	// isError
	if (isError) {
		final AttributedStringBuilder errorLine = new AttributedStringBuilder();
		errorLine.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.RED));
		errorLine.append(CliStrings.DEFAULT_MARGIN + CliStrings.INPUT_ERROR);
		lines.add(AttributedString.EMPTY);
		lines.add(errorLine.toAttributedString());
	}

	return lines;
}
 
Example #25
Source Project: flink   Author: flink-tpc-ds   File: CliResultView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<AttributedString> computeMainLines() {
	final List<AttributedString> lines = new ArrayList<>();

	int lineIdx = 0;
	for (String[] line : results) {
		final AttributedStringBuilder row = new AttributedStringBuilder();

		// highlight selected row
		if (lineIdx == selectedRow) {
			row.style(AttributedStyle.DEFAULT.inverse());
		}

		for (int colIdx = 0; colIdx < line.length; colIdx++) {
			final String col = line[colIdx];
			final int columnWidth = computeColumnWidth(colIdx);

			row.append(' ');
			// check if value was present before last update, if not, highlight it
			// we don't highlight if the retrieval stopped
			// both inverse and bold together do not work correctly
			if (previousResults != null && lineIdx != selectedRow && refreshThread.isRunning &&
					(lineIdx >= previousResults.size() || !col.equals(previousResults.get(lineIdx)[colIdx]))) {
				row.style(AttributedStyle.BOLD);
				normalizeColumn(row, col, columnWidth);
				row.style(AttributedStyle.DEFAULT);
			} else {
				normalizeColumn(row, col, columnWidth);
			}
		}
		lines.add(row.toAttributedString());

		lineIdx++;
	}

	return lines;
}
 
Example #26
Source Project: flink   Author: flink-tpc-ds   File: CliView.java    License: Apache License 2.0 5 votes vote down vote up
private AttributedString computeTitleLine() {
	final String title = getTitle();
	final AttributedStringBuilder titleLine = new AttributedStringBuilder();
	titleLine.style(AttributedStyle.INVERSE);
	final int totalMargin = width - title.length();
	final int margin = totalMargin / 2;
	repeatChar(titleLine, ' ', margin);
	titleLine.append(title);
	repeatChar(titleLine, ' ', margin + (totalMargin % 2));
	return titleLine.toAttributedString();
}
 
Example #27
Source Project: flink   Author: flink-tpc-ds   File: CliUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static List<AttributedString> formatTwoLineHelpOptions(int width, List<Tuple2<String, String>> options) {
	final AttributedStringBuilder line1 = new AttributedStringBuilder();
	final AttributedStringBuilder line2 = new AttributedStringBuilder();

	// we assume that every options has not more than 11 characters (+ key and space)
	final int columns = (int) Math.ceil(((double) options.size()) / 2);
	final int space = (width - CliStrings.DEFAULT_MARGIN.length() - columns * 13) / columns;
	final Iterator<Tuple2<String, String>> iter = options.iterator();
	while (iter.hasNext()) {
		// first line
		Tuple2<String, String> option = iter.next();
		line1.style(AttributedStyle.DEFAULT.inverse());
		line1.append(option.f0);
		line1.style(AttributedStyle.DEFAULT);
		line1.append(' ');
		line1.append(option.f1);
		repeatChar(line1, ' ', (11 - option.f1.length()) + space);
		// second line
		if (iter.hasNext()) {
			option = iter.next();
			line2.style(AttributedStyle.DEFAULT.inverse());
			line2.append(option.f0);
			line2.style(AttributedStyle.DEFAULT);
			line2.append(' ');
			line2.append(option.f1);
			repeatChar(line2, ' ', (11 - option.f1.length()) + space);
		}
	}

	return Arrays.asList(line1.toAttributedString(), line2.toAttributedString());
}
 
Example #28
Source Project: flink   Author: flink-tpc-ds   File: CliChangelogResultView.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected List<AttributedString> computeHeaderLines() {

	final AttributedStringBuilder statusLine = new AttributedStringBuilder();
	statusLine.style(AttributedStyle.INVERSE);
	// left
	final String left;
	if (isRetrieving()) {
		left = CliStrings.DEFAULT_MARGIN + CliStrings.RESULT_REFRESH_INTERVAL + ' ' + REFRESH_INTERVALS.get(refreshInterval).f0;
	} else {
		left = CliStrings.DEFAULT_MARGIN + CliStrings.RESULT_STOPPED;
	}

	// right
	final String right;
	if (lastRetrieval == null) {
		right = CliStrings.RESULT_LAST_REFRESH + ' ' + CliStrings.RESULT_REFRESH_UNKNOWN + CliStrings.DEFAULT_MARGIN;
	} else {
		right = CliStrings.RESULT_LAST_REFRESH + ' ' + lastRetrieval.format(TIME_FORMATTER) + CliStrings.DEFAULT_MARGIN;
	}
	// all together
	final int middleSpace = getWidth() - left.length() - right.length();
	statusLine.append(left);
	repeatChar(statusLine, ' ', middleSpace);
	statusLine.append(right);

	return Arrays.asList(statusLine.toAttributedString(), AttributedString.EMPTY);
}
 
Example #29
Source Project: flink   Author: flink-tpc-ds   File: CliClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CLI instance with a custom terminal. Make sure to close the CLI instance
 * afterwards using {@link #close()}.
 */
@VisibleForTesting
public CliClient(Terminal terminal, SessionContext context, Executor executor) {
	this.terminal = terminal;
	this.context = context;
	this.executor = executor;

	// make space from previous output and test the writer
	terminal.writer().println();
	terminal.writer().flush();

	// initialize line lineReader
	lineReader = LineReaderBuilder.builder()
		.terminal(terminal)
		.appName(CliStrings.CLI_NAME)
		.parser(new SqlMultiLineParser())
		.completer(new SqlCompleter(context, executor))
		.build();
	// this option is disabled for now for correct backslash escaping
	// a "SELECT '\'" query should return a string with a backslash
	lineReader.option(LineReader.Option.DISABLE_EVENT_EXPANSION, true);
	// set strict "typo" distance between words when doing code completion
	lineReader.setVariable(LineReader.ERRORS, 1);
	// perform code completion case insensitive
	lineReader.option(LineReader.Option.CASE_INSENSITIVE, true);

	// create prompt
	prompt = new AttributedStringBuilder()
		.style(AttributedStyle.DEFAULT.foreground(AttributedStyle.GREEN))
		.append("Flink SQL")
		.style(AttributedStyle.DEFAULT)
		.append("> ")
		.toAnsi();
}
 
Example #30
Source Project: flink   Author: flink-tpc-ds   File: CliStrings.java    License: Apache License 2.0 5 votes vote down vote up
public static AttributedString messageInfo(String message) {
	return new AttributedStringBuilder()
		.style(AttributedStyle.DEFAULT.bold().foreground(AttributedStyle.BLUE))
		.append("[INFO] ")
		.append(message)
		.toAttributedString();
}