Java Code Examples for org.apache.commons.lang3.StringUtils#center()

The following examples show how to use org.apache.commons.lang3.StringUtils#center() . 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
private StringBuilder getTitleBlock(TableDefinition tableDefinition, Map<String, ColumnDefinition> columnDefinitions, Locale locale) {
    List<String> order = tableDefinition.getOrder();
    String translationKey = tableDefinition.getTitleTranslationKey();
    String defaultTitle = tableDefinition.getDefaultTitle();

    String title = I18nString.getLocaleStringOrDefault(translationKey, locale, StringUtils.defaultString(defaultTitle));
    if (StringUtils.isBlank(title)) {
        return new StringBuilder();
    }

    StringBuilder out = new StringBuilder(getHorizontalBorder(order, columnDefinitions, HORIZONTAL_MARGIN));
    int contentLength = out.length() - 4;
    String centeredTitle = StringUtils.center(title, contentLength, TableSpecialCharacters.NON_BREAKING_SPACE);

    return out.append(TableSpecialCharacters.VERTICAL_BORDER)
            .append(centeredTitle.toUpperCase())
            .append(TableSpecialCharacters.VERTICAL_BORDER)
            .append(lineBreaker);
}
 
Example 2
Source Project: react-native-esc-pos   File: LayoutBuilder.java    License: MIT License 6 votes vote down vote up
public String createTextOnLine(String text, char space, String alignment, int charsOnLine) {
    if (text.length() > charsOnLine) {
        StringBuilder out = new StringBuilder();
        int len = text.length();
        for (int i = 0; i <= len / charsOnLine; i++) {
            String str = text.substring(i * charsOnLine, Math.min((i + 1) * charsOnLine, len));
            if (!str.trim().isEmpty()) {
                out.append(createTextOnLine(str, space, alignment));
            }
        }

        return out.toString();
    }

    switch (alignment) {
    case TEXT_ALIGNMENT_RIGHT:
        return StringUtils.leftPad(text, charsOnLine, space) + "\n";

    case TEXT_ALIGNMENT_CENTER:
        return StringUtils.center(text, charsOnLine, space) + "\n";

    default:
        return StringUtils.rightPad(text, charsOnLine, space) + "\n";
    }
}
 
Example 3
Source Project: esc-pos-android   File: Ticket.java    License: Apache License 2.0 6 votes vote down vote up
private String fixText(String text, char fill, TicketBuilder.TextAlignment alignment, int charsOnLine) {
  if (text.length() > charsOnLine) {
    StringBuilder out = new StringBuilder();
    int len = text.length();
    for (int i = 0; i <= len / charsOnLine; i++) {
      String str = text.substring(i * charsOnLine, Math.min((i + 1) * charsOnLine, len));
      if (!str.trim().isEmpty()) out.append(fixText(str, fill, alignment, charsOnLine));
    }

    return out.toString();
  }

  switch (alignment) {
    case RIGHT:
      return StringUtils.leftPad(text, charsOnLine, fill) + "\n";
    case CENTER:
      return StringUtils.center(text, charsOnLine, fill) + "\n";
    default:
      return StringUtils.rightPad(text, charsOnLine, fill) + "\n";
  }
}
 
Example 4
Source Project: geowave   File: TestUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param testName Name of the test that we are starting.
 * @param startMillis The time (millis) that the test started.
 */
public static void printEndOfTest(
    final Logger logger,
    final String testName,
    final long startMillis) {
  // Get Elapsed Time
  final double elapsedS = (System.currentTimeMillis() - startMillis) / 1000.;
  // Format
  final String paddedName = StringUtils.center("FINISHED " + testName, 37);
  final String paddedElapsed = StringUtils.center(elapsedS + "s elapsed.", 37);
  // Print
  logger.warn("-----------------------------------------");
  logger.warn("*                                       *");
  logger.warn("* " + paddedName + " *");
  logger.warn("* " + paddedElapsed + " *");
  logger.warn("*                                       *");
  logger.warn("-----------------------------------------");
}
 
Example 5
Source Project: pikatimer   File: Award.java    License: GNU General Public License v3.0 5 votes vote down vote up
private String printWinners(List<AwardWinner> winners) {
    String dispFormat = race.getStringAttribute("TimeDisplayFormat");
    String roundMode = race.getStringAttribute("TimeRoundingMode");
    Integer dispFormatLength;  // add a space
    if (dispFormat.contains("[HH:]")) dispFormatLength = dispFormat.length()-1; // get rid of the two brackets and add a space
    else dispFormatLength = dispFormat.length()+1;
    
    String report = new String();
    for(AwardWinner aw: winners) {
        
       report += StringUtils.center(aw.awardPlace.toString(),6); // 4R chars  
       report += StringUtils.rightPad(aw.participant.fullNameProperty().getValue(),fullNameLength.get()); // based on the longest name
        report += StringUtils.leftPad(aw.participant.getBib(),5); // 5R chars for the bib #
        report += StringUtils.leftPad(aw.participant.getAge().toString(),4); // 4R for the age
        report += StringUtils.center(aw.participant.getSex(),5); // 4R for the sex
        report += StringUtils.rightPad(aw.processedResult.getAGCode(),5); //6L for the AG Group
        report += " ";
        report += StringUtils.rightPad(aw.participant.getCity(),18); // 18L for the city
        if (showState.get())  report += StringUtils.center(aw.participant.getState(),4); // 4C for the state code
        if (showCountry.get())  report += StringUtils.leftPad(aw.participant.getCountry(),4); // 4C for the state code
        if (showCustomAttributes) {
            for( CustomAttribute a: customAttributesList){
                report += StringUtils.rightPad(" " + aw.participant.getCustomAttribute(a.getID()).getValueSafe(),customAttributeSizeMap.get(a.getID()));
            }
        }
        report += StringUtils.leftPad(DurationFormatter.durationToString(aw.awardTime, dispFormat, roundMode), dispFormatLength);
        report += System.lineSeparator();
    }
    return report;
}
 
Example 6
Source Project: jinjava   File: CenterFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object filter(Object var, JinjavaInterpreter interpreter, String... args) {
  if (var == null) {
    return null;
  }

  int size = 80;
  if (args.length > 0) {
    size = NumberUtils.toInt(args[0], 80);
  }

  return StringUtils.center(var.toString(), size);
}
 
Example 7
Source Project: geowave   File: TestUtils.java    License: Apache License 2.0 5 votes vote down vote up
/** @param testName Name of the test that we are starting. */
public static void printStartOfTest(final Logger logger, final String testName) {
  // Format
  final String paddedName = StringUtils.center("RUNNING " + testName, 37);
  // Print
  logger.warn("-----------------------------------------");
  logger.warn("*                                       *");
  logger.warn("* " + paddedName + " *");
  logger.warn("*                                       *");
  logger.warn("-----------------------------------------");
}
 
Example 8
Source Project: nifi   File: LogHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected String createFactsLogMessage(Map<String, Object> facts, String eventMessage) {

        final Set<String> fields = facts.keySet();
        final StringBuilder message = new StringBuilder();
        String dashedLine;

        if (StringUtils.isBlank(logPrefix)) {
            dashedLine = StringUtils.repeat('-', 50);
        } else {
            // abbreviate long lines
            logPrefix = StringUtils.abbreviate(logPrefix, 40);
            // center the logPrefix and pad with dashes
            logPrefix = StringUtils.center(logPrefix, 40, '-');
            // five dashes on the left and right side, plus the dashed logPrefix
            dashedLine = StringUtils.repeat('-', 5) + logPrefix + StringUtils.repeat('-', 5);
        }

        message.append("\n");
        message.append(dashedLine);
        message.append("\n");
        message.append("Log Message: ");
        message.append(eventMessage);
        message.append("\n");

        if (logFacts) {
            message.append("Log Facts:\n");
            fields.forEach(field -> {
                message.append("Field: ");
                message.append(field);
                message.append(", Value: ");
                message.append(facts.get(field));
                message.append("\n");
            });
        }

        return message.toString().trim();

    }
 
Example 9
Source Project: localization_nifi   File: LogAttribute.java    License: Apache License 2.0 4 votes vote down vote up
protected String processFlowFile(final ComponentLog logger, final DebugLevels logLevel, final FlowFile flowFile, final ProcessSession session, final ProcessContext context) {
    final Set<String> attributeKeys = getAttributesToLog(flowFile.getAttributes().keySet(), context);
    final ComponentLog LOG = getLogger();
    final String dashedLine;

    String logPrefix = context.getProperty(LOG_PREFIX).evaluateAttributeExpressions(flowFile).getValue();

    if (StringUtil.isBlank(logPrefix)) {
        dashedLine = StringUtils.repeat('-', 50);
    } else {
        // abbreviate long lines
        logPrefix = StringUtils.abbreviate(logPrefix, 40);
        // center the logPrefix and pad with dashes
        logPrefix = StringUtils.center(logPrefix, 40, '-');
        // five dashes on the left and right side, plus the dashed logPrefix
        dashedLine = StringUtils.repeat('-', 5) + logPrefix + StringUtils.repeat('-', 5);
    }

    // Pretty print metadata
    final StringBuilder message = new StringBuilder();
    message.append("logging for flow file ").append(flowFile);
    message.append("\n");
    message.append(dashedLine);
    message.append("\nStandard FlowFile Attributes");
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "entryDate", new Date(flowFile.getEntryDate())));
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "lineageStartDate", new Date(flowFile.getLineageStartDate())));
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "fileSize", flowFile.getSize()));
    message.append("\nFlowFile Attribute Map Content");
    for (final String key : attributeKeys) {
        message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", key, flowFile.getAttribute(key)));
    }
    message.append("\n");
    message.append(dashedLine);

    // The user can request to log the payload
    final boolean logPayload = context.getProperty(LOG_PAYLOAD).asBoolean();
    if (logPayload) {
        message.append("\n");
        if (flowFile.getSize() < ONE_MB) {
            final FlowFilePayloadCallback callback = new FlowFilePayloadCallback();
            session.read(flowFile, callback);
            message.append(callback.getContents());
        } else {
            message.append("\n Not including payload since it is larger than one mb.");
        }
    }
    final String outputMessage = message.toString().trim();
    // Uses optional property to specify logging level
    switch (logLevel) {
        case info:
            LOG.info(outputMessage);
            break;
        case debug:
            LOG.debug(outputMessage);
            break;
        case warn:
            LOG.warn(outputMessage);
            break;
        case trace:
            LOG.trace(outputMessage);
            break;
        case error:
            LOG.error(outputMessage);
            break;
        default:
            LOG.debug(outputMessage);
    }

    return outputMessage;

}
 
Example 10
Source Project: codebuff   File: Trainer.java    License: BSD 2-Clause "Simplified" License 4 votes vote down vote up
public static String _toString(FeatureMetaData[] FEATURES, InputDocument doc, int[] features,
                               boolean showInfo) {
	Vocabulary v = doc.parser.getVocabulary();
	String[] ruleNames = doc.parser.getRuleNames();
	StringBuilder buf = new StringBuilder();
	for (int i=0; i<FEATURES.length; i++) {
		if ( FEATURES[i].type.equals(UNUSED) ) continue;
		if ( i>0 ) buf.append(" ");
		if ( i==INDEX_CUR_TOKEN_TYPE ) {
			buf.append("| "); // separate prev from current tokens
		}
		int displayWidth = FEATURES[i].type.displayWidth;
		switch ( FEATURES[i].type ) {
			case TOKEN :
				String tokenName = v.getDisplayName(features[i]);
				String abbrev = StringUtils.abbreviateMiddle(tokenName, "*", displayWidth);
				String centered = StringUtils.center(abbrev, displayWidth);
				buf.append(String.format("%"+displayWidth+"s", centered));
				break;
			case RULE :
				if ( features[i]>=0 ) {
					String ruleName = ruleNames[unrulealt(features[i])[0]];
					int ruleAltNum = unrulealt(features[i])[1];
					ruleName += ":"+ruleAltNum;
					abbrev = StringUtils.abbreviateMiddle(ruleName, "*", displayWidth);
					buf.append(String.format("%"+displayWidth+"s", abbrev));
				}
				else {
					buf.append(Tool.sequence(displayWidth, " "));
				}
				break;
			case INT :
			case INFO_LINE:
			case INFO_CHARPOS:
				if ( showInfo ) {
					if ( features[i]>=0 ) {
						buf.append(String.format("%"+displayWidth+"s", StringUtils.center(String.valueOf(features[i]), displayWidth)));
					}
					else {
						buf.append(Tool.sequence(displayWidth, " "));
					}
				}
				break;
			case INFO_FILE:
				if ( showInfo ) {
					String fname = new File(doc.fileName).getName();
					fname = StringUtils.abbreviate(fname, displayWidth);
					buf.append(String.format("%"+displayWidth+"s", fname));
				}
				break;
			case BOOL :
				if ( features[i]!=-1 ) {
					buf.append(features[i] == 1 ? "true " : "false");
				}
				else {
					buf.append(Tool.sequence(displayWidth, " "));
				}
				break;
			default :
				System.err.println("NO STRING FOR FEATURE TYPE: "+ FEATURES[i].type);
		}
	}
	return buf.toString();
}
 
Example 11
Source Project: nifi   File: LogAttribute.java    License: Apache License 2.0 4 votes vote down vote up
protected String processFlowFile(final ComponentLog logger, final DebugLevels logLevel, final FlowFile flowFile, final ProcessSession session, final ProcessContext context) {
    final Set<String> attributeKeys = getAttributesToLog(flowFile.getAttributes().keySet(), context);
    final ComponentLog LOG = getLogger();
    final String dashedLine;

    String logPrefix = context.getProperty(LOG_PREFIX).evaluateAttributeExpressions(flowFile).getValue();
    Charset charset = Charset.forName(context.getProperty(CHARSET).evaluateAttributeExpressions(flowFile).getValue());

    if (StringUtil.isBlank(logPrefix)) {
        dashedLine = StringUtils.repeat('-', 50);
    } else {
        // abbreviate long lines
        logPrefix = StringUtils.abbreviate(logPrefix, 40);
        // center the logPrefix and pad with dashes
        logPrefix = StringUtils.center(logPrefix, 40, '-');
        // five dashes on the left and right side, plus the dashed logPrefix
        dashedLine = StringUtils.repeat('-', 5) + logPrefix + StringUtils.repeat('-', 5);
    }

    // Pretty print metadata
    final StringBuilder message = new StringBuilder();
    message.append("logging for flow file ").append(flowFile);
    message.append("\n");
    message.append(dashedLine);
    message.append("\nStandard FlowFile Attributes");
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "entryDate", new Date(flowFile.getEntryDate())));
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "lineageStartDate", new Date(flowFile.getLineageStartDate())));
    message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", "fileSize", flowFile.getSize()));
    message.append("\nFlowFile Attribute Map Content");
    for (final String key : attributeKeys) {
        message.append(String.format("\nKey: '%1$s'\n\tValue: '%2$s'", key, flowFile.getAttribute(key)));
    }
    message.append("\n");
    message.append(dashedLine);

    // The user can request to log the payload
    final boolean logPayload = context.getProperty(LOG_PAYLOAD).asBoolean();
    if (logPayload) {
        message.append("\n");
        if (flowFile.getSize() < ONE_MB) {
            final FlowFilePayloadCallback callback = new FlowFilePayloadCallback(charset);
            session.read(flowFile, callback);
            message.append(callback.getContents());
        } else {
            message.append("\n Not including payload since it is larger than one mb.");
        }
    }
    final String outputMessage = message.toString().trim();
    // Uses optional property to specify logging level
    switch (logLevel) {
        case info:
            LOG.info(outputMessage);
            break;
        case debug:
            LOG.debug(outputMessage);
            break;
        case warn:
            LOG.warn(outputMessage);
            break;
        case trace:
            LOG.trace(outputMessage);
            break;
        case error:
            LOG.error(outputMessage);
            break;
        default:
            LOG.debug(outputMessage);
    }

    return outputMessage;

}
 
Example 12
Source Project: nifi   File: StringEncryptor.java    License: Apache License 2.0 4 votes vote down vote up
private static String centerString(String msg) {
    return "*" + StringUtils.center(msg, 78, " ") + "*";
}
 
Example 13
Source Project: spring-boot   File: MyStringUtils.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * 指定数量的字符
 *
 * @param size
 * @param padChar
 * @return
 */
public static String center(int size, String padChar) {
    return StringUtils.center("", size, padChar);
}