org.jline.utils.AttributedString Java Examples

The following examples show how to use org.jline.utils.AttributedString. 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: DrillSqlLineApplication.java    From Bats with 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 #2
Source File: PromptHandler.java    From sqlline with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
protected AttributedString getDefaultPrompt(
    int connectionIndex, String url, String defaultPrompt) {
  String resultPrompt;
  if (url == null || url.length() == 0) {
    return new AttributedString(defaultPrompt);
  } else {
    if (url.contains(";")) {
      url = url.substring(0, url.indexOf(";"));
    }
    if (url.contains("?")) {
      url = url.substring(0, url.indexOf("?"));
    }
    resultPrompt = connectionIndex + ": " + url;
    if (resultPrompt.length() > 45) {
      resultPrompt = resultPrompt.substring(0, 45);
    }
    return new AttributedString(resultPrompt + "> ");
  }
}
 
Example #3
Source File: CliChangelogResultView.java    From Flink-CEPplus with 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 File: CliClient.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Submits a SQL update statement and prints status information and/or errors on the terminal.
 *
 * @param statement SQL update statement
 * @return flag to indicate if the submission was successful or not
 */
public boolean submitUpdate(String statement) {
	terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_WILL_EXECUTE).toAnsi());
	terminal.writer().println(new AttributedString(statement).toString());
	terminal.flush();

	final Optional<SqlCommandCall> parsedStatement = parseCommand(statement);
	// only support INSERT INTO/OVERWRITE
	return parsedStatement.map(cmdCall -> {
		switch (cmdCall.command) {
			case INSERT_INTO:
			case INSERT_OVERWRITE:
				return callInsert(cmdCall);
			default:
				printError(CliStrings.MESSAGE_UNSUPPORTED_SQL);
				return false;
		}
	}).orElse(false);
}
 
Example #5
Source File: SqlLineHighlighterTest.java    From sqlline with 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 #6
Source File: CliClient.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Submits a SQL update statement and prints status information and/or errors on the terminal.
 *
 * @param statement SQL update statement
 * @return flag to indicate if the submission was successful or not
 */
public boolean submitUpdate(String statement) {
	terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_WILL_EXECUTE).toAnsi());
	terminal.writer().println(new AttributedString(statement).toString());
	terminal.flush();

	final Optional<SqlCommandCall> parsedStatement = parseCommand(statement);
	// only support INSERT INTO
	return parsedStatement.map(cmdCall -> {
		switch (cmdCall.command) {
			case INSERT_INTO:
				return callInsertInto(cmdCall);
			default:
				printError(CliStrings.MESSAGE_UNSUPPORTED_SQL);
				return false;
		}
	}).orElse(false);
}
 
Example #7
Source File: TableOutputFormat.java    From sqlline with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #8
Source File: BatsSqlLineApplication.java    From Bats with 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 #9
Source File: CliChangelogResultView.java    From flink with 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 #10
Source File: CliView.java    From flink with 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 #11
Source File: CliView.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
protected List<AttributedString> getMainLines() {
	if (mainLines == null) {
		mainLines = computeMainLines();
		totalMainWidth = computeTotalMainWidth();
	}
	return mainLines;
}
 
Example #12
Source File: PicocliCommands.java    From picocli with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param args
 * @return command description for JLine TailTipWidgets to be displayed in terminal status bar.
 */
@Override
public CmdDesc commandDescription(List<String> args) {
    CommandLine sub = findSubcommandLine(args, args.size());
    if (sub == null) {
        return null;
    }
    CommandSpec spec = sub.getCommandSpec();
    Help cmdhelp= new picocli.CommandLine.Help(spec);
    List<AttributedString> main = new ArrayList<>();
    Map<String, List<AttributedString>> options = new HashMap<>();
    String synopsis = AttributedString.stripAnsi(spec.usageMessage().sectionMap().get("synopsis").render(cmdhelp).toString());
    main.add(HelpException.highlightSyntax(synopsis.trim(), HelpException.defaultStyle()));
    // using JLine help highlight because the statement below does not work well...
    //        main.add(new AttributedString(spec.usageMessage().sectionMap().get("synopsis").render(cmdhelp).toString()));
    for (OptionSpec o : spec.options()) {
        String key = Arrays.stream(o.names()).collect(Collectors.joining(" "));
        List<AttributedString> val = new ArrayList<>();
        for (String d:  o.description()) {
            val.add(new AttributedString(d));
        }
        if (o.arity().max() > 0) {
            key += "=" + o.paramLabel();
        }
        options.put(key, val);
    }
    return new CmdDesc(main, ArgDesc.doArgNames(Arrays.asList("")), options);
}
 
Example #13
Source File: CliView.java    From Flink-CEPplus with 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 #14
Source File: CliStrings.java    From flink with 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 #15
Source File: ClassNameCompleter.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Completes candidates using all the classes available in the
 * java <em>CLASSPATH</em>.
 *
 * @throws IOException on error
 */
public ClassNameCompleter() throws IOException {
  super(getClassNames());
  candidates.add(
      new Candidate(AttributedString.stripAnsi("."),
          ".", null, null, null, null, true));
}
 
Example #16
Source File: CliChangelogResultView.java    From Flink-CEPplus with 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 #17
Source File: CustomPromptHandler.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override protected AttributedString getDefaultPrompt(int connectionIndex,
    String url, String defaultPrompt) {
  AttributedStringBuilder builder = new AttributedStringBuilder();
  builder.append("my_app");

  final ConnectionMetadata meta = sqlLine.getConnectionMetadata();

  final String currentSchema = meta.getCurrentSchema();
  if (currentSchema != null) {
    builder.append(" (").append(currentSchema).append(")");
  }
  return builder.append(">").toAttributedString();
}
 
Example #18
Source File: CliStrings.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public static AttributedString messageError(String message, Throwable t) {
	while (t.getCause() != null && t.getCause().getMessage() != null && !t.getCause().getMessage().isEmpty()) {
		t = t.getCause();
	}
	return messageError(message, t.getClass().getName() + ": " + t.getMessage());
	// return messageError(message, ExceptionUtils.stringifyException(t));
}
 
Example #19
Source File: CliTableResultView.java    From flink with 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 #20
Source File: SqlLineHighlighterTest.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void checkHighlightedLine(
    SqlLine sqlLine,
    String line,
    ExpectedHighlightStyle expectedHighlightStyle,
    SqlLineHighlighter highlighter) {
  final AttributedString attributedString =
      highlighter.highlight(sqlLine.getLineReader(), line);
  final HighlightStyle highlightStyle = sqlLine.getHighlightStyle();
  int commandStyle = highlightStyle.getCommandStyle().getStyle();
  int keywordStyle = highlightStyle.getKeywordStyle().getStyle();
  int singleQuoteStyle = highlightStyle.getQuotedStyle().getStyle();
  int identifierStyle = highlightStyle.getIdentifierStyle().getStyle();
  int commentStyle = highlightStyle.getCommentStyle().getStyle();
  int numberStyle = highlightStyle.getNumberStyle().getStyle();
  int defaultStyle = highlightStyle.getDefaultStyle().getStyle();

  for (int i = 0; i < line.length(); i++) {
    checkSymbolStyle(line, i, expectedHighlightStyle.commands,
        attributedString, commandStyle, "command");

    checkSymbolStyle(line, i, expectedHighlightStyle.keywords,
        attributedString, keywordStyle, "key word");

    checkSymbolStyle(line, i, expectedHighlightStyle.singleQuotes,
        attributedString, singleQuoteStyle, "single quote");

    checkSymbolStyle(line, i, expectedHighlightStyle.sqlIdentifierQuotes,
        attributedString, identifierStyle, "sql identifier quote");

    checkSymbolStyle(line, i, expectedHighlightStyle.numbers,
        attributedString, numberStyle, "number");

    checkSymbolStyle(line, i, expectedHighlightStyle.comments,
        attributedString, commentStyle, "comment");

    checkSymbolStyle(line, i, expectedHighlightStyle.defaults,
        attributedString, defaultStyle, "default");
  }
}
 
Example #21
Source File: SshShellAutoConfiguration.java    From ssh-shell-spring-boot with Apache License 2.0 5 votes vote down vote up
/**
 * Primary prompt provider
 *
 * @param properties ssh shell properties
 * @return prompt provider
 */
@Bean
@ConditionalOnMissingBean
public PromptProvider sshPromptProvider(SshShellProperties properties) {
    return () -> new AttributedString(properties.getPrompt().getText(),
            AttributedStyle.DEFAULT.foreground(properties.getPrompt().getColor().toJlineAttributedStyle()));
}
 
Example #22
Source File: CliStrings.java    From flink with Apache License 2.0 5 votes vote down vote up
public static AttributedString messageError(String message, Throwable t) {
	while (t.getCause() != null && t.getCause().getMessage() != null && !t.getCause().getMessage().isEmpty()) {
		t = t.getCause();
	}
	return messageError(message, t.getClass().getName() + ": " + t.getMessage());
	// return messageError(message, ExceptionUtils.stringifyException(t));
}
 
Example #23
Source File: CliInputView.java    From flink with 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 #24
Source File: PromptHandler.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public AttributedString getPrompt() {
  if (!sqlLine.getOpts().isDefault(BuiltInProperty.PROMPT_SCRIPT)) {
    final String promptScript =
        sqlLine.getOpts().get(BuiltInProperty.PROMPT_SCRIPT);
    return getPromptFromScript(sqlLine, promptScript);
  }
  final String defaultPrompt =
      String.valueOf(BuiltInProperty.PROMPT.defaultValue());
  final String currentPrompt = sqlLine.getOpts().get(BuiltInProperty.PROMPT);
  final DatabaseConnection dbc = sqlLine.getDatabaseConnection();
  final boolean useDefaultPrompt =
      sqlLine.getOpts().isDefault(BuiltInProperty.PROMPT);
  if (dbc == null || dbc.getUrl() == null) {
    return useDefaultPrompt
        ? getDefaultPrompt(-1, null, defaultPrompt)
        : getPrompt(sqlLine, -1, currentPrompt);
  } else {
    final int connectionIndex = sqlLine.getConnectionMetadata().getIndex();
    if (useDefaultPrompt || dbc.getNickname() != null) {
      final String nickNameOrUrl =
          dbc.getNickname() == null ? dbc.getUrl() : dbc.getNickname();
      return getDefaultPrompt(connectionIndex, nickNameOrUrl, defaultPrompt);
    } else {
      return getPrompt(sqlLine, connectionIndex, currentPrompt);
    }
  }
}
 
Example #25
Source File: PromptHandler.java    From sqlline with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public AttributedString getRightPrompt() {
  final int connectionIndex = sqlLine.getDatabaseConnections().getIndex();
  final String currentPrompt =
      sqlLine.getOpts().isDefault(BuiltInProperty.RIGHT_PROMPT)
          ? (String) BuiltInProperty.RIGHT_PROMPT.defaultValue()
          : sqlLine.getOpts().get(BuiltInProperty.RIGHT_PROMPT);
  return getPrompt(sqlLine, connectionIndex, currentPrompt);
}
 
Example #26
Source File: SkipperPromptProvider.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
@Override
public AttributedString getPrompt() {
	if (skipperClient != null) {
		return new AttributedString("skipper:>", AttributedStyle.DEFAULT.foreground(AttributedStyle.YELLOW));
	}
	else {
		return new AttributedString("server-unknown:>", AttributedStyle.DEFAULT.foreground(AttributedStyle.RED));
	}
}
 
Example #27
Source File: CliStrings.java    From flink with 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 #28
Source File: CliView.java    From flink with Apache License 2.0 5 votes vote down vote up
protected List<AttributedString> getMainLines() {
	if (mainLines == null) {
		mainLines = computeMainLines();
		totalMainWidth = computeTotalMainWidth();
	}
	return mainLines;
}
 
Example #29
Source File: CliClient.java    From flink with Apache License 2.0 5 votes vote down vote up
private void callSource(SqlCommandCall cmdCall) {
	final String pathString = cmdCall.operands[0];

	// load file
	final String stmt;
	try {
		final Path path = Paths.get(pathString);
		byte[] encoded = Files.readAllBytes(path);
		stmt = new String(encoded, Charset.defaultCharset());
	} catch (IOException e) {
		printExecutionException(e);
		return;
	}

	// limit the output a bit
	if (stmt.length() > SOURCE_MAX_SIZE) {
		printExecutionError(CliStrings.MESSAGE_MAX_SIZE_EXCEEDED);
		return;
	}

	terminal.writer().println(CliStrings.messageInfo(CliStrings.MESSAGE_WILL_EXECUTE).toAnsi());
	terminal.writer().println(new AttributedString(stmt).toString());
	terminal.flush();

	// try to run it
	final Optional<SqlCommandCall> call = parseCommand(stmt);
	call.ifPresent(this::callCommand);
}
 
Example #30
Source File: CliView.java    From flink with Apache License 2.0 5 votes vote down vote up
protected List<AttributedString> getMainHeaderLines() {
	if (mainHeaderLines == null) {
		mainHeaderLines = computeMainHeaderLines();
		totalMainWidth = computeTotalMainWidth();
	}
	return mainHeaderLines;
}