Java Code Examples for org.jline.utils.AttributedStringBuilder

The following examples show how to use org.jline.utils.AttributedStringBuilder. 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: Bats   Source File: BatsSqlLineApplication.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PromptHandler getPromptHandler(SqlLine sqlLine) {
    // if (config.hasPath(PROMPT_WITH_SCHEMA) && config.getBoolean(PROMPT_WITH_SCHEMA)) {
    return new PromptHandler(sqlLine) {
        @Override
        protected AttributedString getDefaultPrompt(int connectionIndex, String url, String defaultPrompt) {
            AttributedStringBuilder builder = new AttributedStringBuilder();
            builder.style(resolveStyle("f:y"));
            builder.append("bats");

            ConnectionMetadata meta = sqlLine.getConnectionMetadata();

            String currentSchema = meta.getCurrentSchema();
            if (currentSchema != null) {
                builder.append(" (").append(currentSchema).append(")");
            }
            return builder.style(resolveStyle("default")).append("> ").toAttributedString();
        }
    };
    // }
    // return super.getPromptHandler(sqlLine);
}
 
Example 2
Source Project: Bats   Source File: DrillSqlLineApplication.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PromptHandler getPromptHandler(SqlLine sqlLine) {
  if (config.hasPath(PROMPT_WITH_SCHEMA) && config.getBoolean(PROMPT_WITH_SCHEMA)) {
    return new PromptHandler(sqlLine) {
      @Override
      protected AttributedString getDefaultPrompt(int connectionIndex, String url, String defaultPrompt) {
        AttributedStringBuilder builder = new AttributedStringBuilder();
        builder.style(resolveStyle("f:y"));
        builder.append("apache drill");

        ConnectionMetadata meta = sqlLine.getConnectionMetadata();

        String currentSchema = meta.getCurrentSchema();
        if (currentSchema != null) {
          builder.append(" (").append(currentSchema).append(")");
        }
        return builder.style(resolveStyle("default")).append("> ").toAttributedString();
      }
    };
  }
  return super.getPromptHandler(sqlLine);
}
 
Example 3
Source Project: Flink-CEPplus   Source 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 4
Source Project: flink   Source 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 5
Source Project: graph-examples   Source 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 6
Source Project: graph-examples   Source 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 7
Source Project: samza   Source 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 8
Source Project: samza   Source 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 9
Source Project: samza   Source 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 10
Source Project: Lealone-Plugins   Source File: SqlLineApplication.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public PromptHandler getPromptHandler(SqlLine sqlLine) {
    if (config.hasPath(PROMPT_WITH_SCHEMA) && config.getBoolean(PROMPT_WITH_SCHEMA)) {
        return new PromptHandler(sqlLine) {
            @Override
            protected AttributedString getDefaultPrompt(int connectionIndex, String url, String defaultPrompt) {
                AttributedStringBuilder builder = new AttributedStringBuilder();
                builder.style(resolveStyle("f:y"));
                builder.append("lealone");

                ConnectionMetadata meta = sqlLine.getConnectionMetadata();

                String currentSchema = meta.getCurrentSchema();
                if (currentSchema != null) {
                    builder.append(" (").append(currentSchema).append(")");
                }
                return builder.style(resolveStyle("default")).append("> ").toAttributedString();
            }
        };
    }
    return super.getPromptHandler(sqlLine);
}
 
Example 11
Source Project: flink   Source 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 12
Source Project: sqlline   Source File: Commands.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void dbinfo(String line, DispatchCallback callback) {
  if (!sqlLine.assertConnection()) {
    callback.setToFailure();
    return;
  }

  sqlLine.showWarnings();
  int padlen = 50;

  for (String method : METHODS) {
    try {
      final String s =
          String.valueOf(sqlLine.getReflector()
              .invoke(sqlLine.getDatabaseMetaData(), method));
      sqlLine.output(
          new AttributedStringBuilder()
              .append(rpad(method, padlen))
              .append(s)
              .toAttributedString());
    } catch (Exception e) {
      sqlLine.handleException(e);
    }
  }

  callback.setToSuccess();
}
 
Example 13
void printRow(AttributedString attributedString, boolean header) {
  AttributedStringBuilder builder = new AttributedStringBuilder();
  if (header) {
    sqlLine.output(
        builder.append("+-", AttributedStyles.GREEN)
            .append(attributedString)
            .append("-+", AttributedStyles.GREEN)
            .toAttributedString());
  } else {
    sqlLine.output(
        builder.append("| ", AttributedStyles.GREEN)
            .append(attributedString)
            .append(" |", AttributedStyles.GREEN)
            .toAttributedString());
  }
}
 
Example 14
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 15
Source Project: sqlline   Source 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 16
Source Project: presto   Source File: AbstractWarningsPrinter.java    License: Apache License 2.0 5 votes vote down vote up
private String getWarningMessage(Warning warning)
{
    // If this is a real terminal color the warnings yellow
    if (REAL_TERMINAL) {
        return new AttributedStringBuilder()
                .style(DEFAULT.foreground(YELLOW))
                .append("WARNING: ")
                .append(warning.getMessage())
                .style(DEFAULT)
                .toAnsi();
    }
    return format("WARNING: %s", warning.getMessage());
}
 
Example 17
Source Project: presto   Source File: Query.java    License: Apache License 2.0 5 votes vote down vote up
private static void renderErrorLocation(String query, ErrorLocation location, PrintStream out)
{
    List<String> lines = ImmutableList.copyOf(Splitter.on('\n').split(query).iterator());

    String errorLine = lines.get(location.getLineNumber() - 1);
    String good = errorLine.substring(0, location.getColumnNumber() - 1);
    String bad = errorLine.substring(location.getColumnNumber() - 1);

    if ((location.getLineNumber() == lines.size()) && bad.trim().isEmpty()) {
        bad = " <EOF>";
    }

    if (REAL_TERMINAL) {
        AttributedStringBuilder builder = new AttributedStringBuilder();

        builder.style(DEFAULT.foreground(CYAN));
        for (int i = 1; i < location.getLineNumber(); i++) {
            builder.append(lines.get(i - 1)).append("\n");
        }
        builder.append(good);

        builder.style(DEFAULT.foreground(RED));
        builder.append(bad).append("\n");
        for (int i = location.getLineNumber(); i < lines.size(); i++) {
            builder.append(lines.get(i)).append("\n");
        }

        builder.style(DEFAULT);
        out.print(builder.toAnsi());
    }
    else {
        String prefix = format("LINE %s: ", location.getLineNumber());
        String padding = Strings.repeat(" ", prefix.length() + (location.getColumnNumber() - 1));
        out.println(prefix + errorLine);
        out.println(padding + "^");
    }
}
 
Example 18
Source Project: presto   Source File: InputHighlighter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public AttributedString highlight(LineReader reader, String buffer)
{
    TokenSource tokens = StatementSplitter.getLexer(buffer, STATEMENT_DELIMITERS);
    AttributedStringBuilder builder = new AttributedStringBuilder();

    boolean error = false;
    while (true) {
        Token token = tokens.nextToken();
        int type = token.getType();
        if (type == Token.EOF) {
            break;
        }
        String text = token.getText();

        if (error || (type == SqlBaseLexer.UNRECOGNIZED)) {
            error = true;
            builder.styled(ERROR_STYLE, text);
        }
        else if (isKeyword(text)) {
            builder.styled(KEYWORD_STYLE, text);
        }
        else if (isString(type)) {
            builder.styled(STRING_STYLE, text);
        }
        else if (isNumber(type)) {
            builder.styled(NUMBER_STYLE, text);
        }
        else if (isComment(type)) {
            builder.styled(COMMENT_STYLE, text);
        }
        else {
            builder.append(text);
        }
    }

    return builder.toAttributedString();
}
 
Example 19
Source Project: Flink-CEPplus   Source 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 20
Source Project: Flink-CEPplus   Source 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 21
Source Project: Flink-CEPplus   Source File: CliUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void normalizeColumn(AttributedStringBuilder sb, String col, int maxWidth) {
	// limit column content
	if (col.length() > maxWidth) {
		sb.append(col, 0, maxWidth - 1);
		sb.append('~');
	} else {
		repeatChar(sb, ' ', maxWidth - col.length());
		sb.append(col);
	}
}
 
Example 22
Source Project: Flink-CEPplus   Source 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 23
Source Project: Flink-CEPplus   Source 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 24
Source Project: Flink-CEPplus   Source 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 25
Source Project: Flink-CEPplus   Source 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 26
Source Project: Flink-CEPplus   Source 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 27
Source Project: Flink-CEPplus   Source 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 28
Source Project: Flink-CEPplus   Source 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 29
Source Project: Flink-CEPplus   Source 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 30
Source Project: Flink-CEPplus   Source 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;
}