org.apache.commons.lang3.StringUtils#rightPad ( )源码实例Demo

下面列出了org.apache.commons.lang3.StringUtils#rightPad ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: macrobase   文件: Row.java
/**
 * Pretty print row in vertical, column-wise format. Example output:
 *
 * col_1    |  val_1
 * col_2    |  val_2
 * ...
 * col_n    |  val_n
 * -----------------------
 *
 * @param out PrintStream to print Row to STDOUT or file (default: STDOUT)
 */
void prettyPrintColumnWise(final PrintStream out) {
    final int maxColNameLength = schema.getColumnNames().stream()
        .reduce("", (x, y) -> x.length() > y.length() ? x : y).length();

    int maxLength = 0;
    for (int i = 0; i < schema.getNumColumns(); ++i) {
        final String colName = schema.getColumnName(i);
        final Object val = vals.get(i);
        final String strToPrint =
            // truncate Strings longer than 40 chars
            StringUtils.rightPad(colName, maxColNameLength) + "  |  " + formatVal(val, 40);
        if (strToPrint.length() > maxLength) {
            maxLength = strToPrint.length();
        }
        out.println(strToPrint);
    }
    // add 5 dashes to account for "  |  "
    final String dashes = Joiner.on("").join(Collections.nCopies(maxLength + 5, "-"));
    out.println(dashes);
}
 
源代码2 项目: react-native-esc-pos   文件: LayoutBuilder.java
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";
    }
}
 
源代码3 项目: uyuni   文件: CreateRedirectURITest.java
public final void testExecuteWhenRedirectURIExceedsMaxLength() throws Exception {
    final String url = StringUtils.rightPad("/YourRhn.do",
            (int)CreateRedirectURI.MAX_URL_LENGTH + 1, "x");

    context().checking(new Expectations() { {
        allowing(mockRequest).getParameterNames();
        will(returnValue(new Vector<String>().elements()));
        allowing(mockRequest).getRequestURI();
        will(returnValue(url));
    } });

    CreateRedirectURI command = new CreateRedirectURI();
    String redirectUrl = command.execute(getMockRequest());

    assertEquals(LoginHelper.DEFAULT_URL_BOUNCE, redirectUrl);
}
 
源代码4 项目: codenjoy   文件: Levels.java
static String resize(String level, int toSize) {
    double sqrt = Math.sqrt(level.length());
    int currentSize = (int) sqrt;
    if (sqrt - currentSize != 0) {
        throw new IllegalArgumentException("Level is not square: " + level);
    }
    if (currentSize >= toSize) {
        return level;
    }

    int before = (int)((toSize - currentSize)/2);
    int after = (toSize - currentSize - before);
    String result = "";
    for (int i = 0; i < currentSize; i++) {
        String part = level.substring(i*currentSize, (i + 1)*currentSize);
        part = StringUtils.leftPad(part, before + part.length());
        part = StringUtils.rightPad(part, after + part.length());
        result += part;
    }
    result = StringUtils.leftPad(result, before*toSize + result.length());
    result = StringUtils.rightPad(result, after*toSize + result.length());

    return result;
}
 
源代码5 项目: org.hl7.fhir.core   文件: BaseDateTimeType.java
/**
 * Returns the nanoseconds within the current second
 * <p>
 * Note that this method returns the
 * same value as {@link #getMillis()} but with more precision.
 * </p>
 */
public Long getNanos() {
	if (isBlank(myFractionalSeconds)) {
		return null;
	}
	String retVal = StringUtils.rightPad(myFractionalSeconds, 9, '0');
	retVal = retVal.substring(0, 9);
	return Long.parseLong(retVal);
}
 
源代码6 项目: org.hl7.fhir.core   文件: BaseDateTimeType.java
/**
 * Returns the nanoseconds within the current second
 * <p>
 * Note that this method returns the
 * same value as {@link #getMillis()} but with more precision.
 * </p>
 */
public Long getNanos() {
	if (isBlank(myFractionalSeconds)) {
		return null;
	}
	String retVal = StringUtils.rightPad(myFractionalSeconds, 9, '0');
	retVal = retVal.substring(0, 9);
	return Long.parseLong(retVal);
}
 
源代码7 项目: nifi   文件: AESSensitivePropertyProvider.java
/**
 * Returns the decrypted plaintext.
 *
 * @param protectedValue the cipher text read from the {@code nifi.properties} file
 * @return the raw value to be used by the application
 * @throws SensitivePropertyProtectionException if there is an error decrypting the cipher text
 */
@Override
public String unprotect(String protectedValue) throws SensitivePropertyProtectionException {
    if (protectedValue == null || protectedValue.trim().length() < MIN_CIPHER_TEXT_LENGTH) {
        throw new IllegalArgumentException("Cannot decrypt a cipher text shorter than " + MIN_CIPHER_TEXT_LENGTH + " chars");
    }

    if (!protectedValue.contains(DELIMITER)) {
        throw new IllegalArgumentException("The cipher text does not contain the delimiter " + DELIMITER + " -- it should be of the form Base64(IV) || Base64(cipherText)");
    }

    protectedValue = protectedValue.trim();

    final String IV_B64 = protectedValue.substring(0, protectedValue.indexOf(DELIMITER));
    byte[] iv = Base64.decode(IV_B64);
    if (iv.length < IV_LENGTH) {
        throw new IllegalArgumentException("The IV (" + iv.length + " bytes) must be at least " + IV_LENGTH + " bytes");
    }

    String CIPHERTEXT_B64 = protectedValue.substring(protectedValue.indexOf(DELIMITER) + 2);

    // Restore the = padding if necessary to reconstitute the GCM MAC check
    if (CIPHERTEXT_B64.length() % 4 != 0) {
        final int paddedLength = CIPHERTEXT_B64.length() + 4 - (CIPHERTEXT_B64.length() % 4);
        CIPHERTEXT_B64 = StringUtils.rightPad(CIPHERTEXT_B64, paddedLength, '=');
    }

    try {
        byte[] cipherBytes = Base64.decode(CIPHERTEXT_B64);

        cipher.init(Cipher.DECRYPT_MODE, this.key, new IvParameterSpec(iv));
        byte[] plainBytes = cipher.doFinal(cipherBytes);
        logger.debug(getName() + " decrypted a sensitive value successfully");
        return new String(plainBytes, StandardCharsets.UTF_8);
    } catch (BadPaddingException | IllegalBlockSizeException | DecoderException | InvalidAlgorithmParameterException | InvalidKeyException e) {
        final String msg = "Error decrypting a protected value";
        logger.error(msg, e);
        throw new SensitivePropertyProtectionException(msg, e);
    }
}
 
源代码8 项目: org.hl7.fhir.core   文件: BaseDateTimeType.java
/**
 * Returns the nanoseconds within the current second
 * <p>
 * Note that this method returns the
 * same value as {@link #getMillis()} but with more precision.
 * </p>
 */
public Long getNanos() {
  if (isBlank(myFractionalSeconds)) {
    return null;
  }
  String retVal = StringUtils.rightPad(myFractionalSeconds, 9, '0');
  retVal = retVal.substring(0, 9);
  return Long.parseLong(retVal);
}
 
源代码9 项目: pikatimer   文件: Award.java
private String outputHeader(){
    String dispFormat = race.getStringAttribute("TimeDisplayFormat");
    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();
    // print the headder
    report += "Place"; // 4R chars 
    report += StringUtils.rightPad(" Name",fullNameLength.get()); // based on the longest name
    report += "   BIB"; // 5R chars for the bib #
    report += " AGE"; // 4R for the age
    report += " SEX"; // 4R for the sex
    report += " AG   "; //6L for the AG Group
    report += " City               "; // 18L for the city
    if (showState.get()) report += "ST  "; // 4C for the state code
    if (showCountry.get()) report += " CO"; // 4C for the state code
    if (showCustomAttributes) {
        for( CustomAttribute a: customAttributesList){
            report += StringUtils.rightPad(" " + a.getName(),customAttributeSizeMap.get(a.getID()));
        }
    }
    report += StringUtils.leftPad(" Time",dispFormatLength); // Need to adjust for the format code
    report += System.lineSeparator();

    return report;
}
 
源代码10 项目: DDMQ   文件: ValidatorsTest.java
@Test
public void testCheckTopic_TooLongTopic() {
    String tooLongTopic = StringUtils.rightPad("TooLongTopic", Validators.CHARACTER_MAX_LENGTH + 1, "_");
    assertThat(tooLongTopic.length()).isGreaterThan(Validators.CHARACTER_MAX_LENGTH);
    try {
        Validators.checkTopic(tooLongTopic);
        failBecauseExceptionWasNotThrown(MQClientException.class);
    } catch (MQClientException e) {
        assertThat(e).hasMessageStartingWith("The specified topic is longer than topic max length 255.");
    }
}
 
源代码11 项目: Resource   文件: SensitiveInfoUtils.java
public static String cnapsCode(String cnaps)
{
    if (StringUtils.isBlank(cnaps))
    {
        return "";
    }
    return StringUtils.rightPad(StringUtils.left(cnaps, 2), StringUtils.length(cnaps), "*");
}
 
@Test
public void testCheckTopic_TooLongTopic() {
    String tooLongTopic = StringUtils.rightPad("TooLongTopic", Validators.CHARACTER_MAX_LENGTH + 1, "_");
    assertThat(tooLongTopic.length()).isGreaterThan(Validators.CHARACTER_MAX_LENGTH);
    try {
        Validators.checkTopic(tooLongTopic);
        failBecauseExceptionWasNotThrown(MQClientException.class);
    } catch (MQClientException e) {
        assertThat(e).hasMessageStartingWith("The specified topic is longer than topic max length 255.");
    }
}
 
源代码13 项目: gocd   文件: AgentRegistrationControllerTest.java
@Test
public void shouldSendAnEmptyStringInBase64_AsAgentExtraProperties_IfTheValueIsTooBigAfterConvertingToBase64() throws IOException {
    final String longExtraPropertiesValue = StringUtils.rightPad("", AgentRegistrationController.MAX_HEADER_LENGTH, "z");
    final String expectedValueToBeUsedForProperties = "";
    final String expectedBase64ExtraPropertiesValue = getEncoder().encodeToString(expectedValueToBeUsedForProperties.getBytes(UTF_8));

    when(systemEnvironment.get(AGENT_EXTRA_PROPERTIES)).thenReturn(longExtraPropertiesValue);

    controller.downloadAgent(response);

    assertEquals(expectedBase64ExtraPropertiesValue, response.getHeader(SystemEnvironment.AGENT_EXTRA_PROPERTIES_HEADER));
}
 
源代码14 项目: levelup-java-examples   文件: RightPadString.java
@Test
public void right_pad_string_with_zeros_apache_commons () {
	
	String rightPaddedString = StringUtils.rightPad("levelup", 10, "0");
	
	assertEquals("levelup000", rightPaddedString);
	assertEquals(10, rightPaddedString.length());
	assertThat(rightPaddedString, endsWith("0"));
}
 
源代码15 项目: genie   文件: TagEntityTest.java
/**
 * Make sure a tag can't be validated if it exceeds size limitations.
 */
@Test
void cantCreateTagEntityDueToSize() {
    final TagEntity tagEntity = new TagEntity();
    final String tag = StringUtils.rightPad(UUID.randomUUID().toString(), 256);
    tagEntity.setTag(tag);
    Assertions
        .assertThatExceptionOfType(ConstraintViolationException.class)
        .isThrownBy(() -> this.validate(tagEntity));
}
 
源代码16 项目: codenjoy   文件: LevelImpl.java
private String pad(int len, char left, char middle, char right) {
    return left + StringUtils.rightPad("", len - 2, middle) + right;
}
 
源代码17 项目: VoxelGamesLibv2   文件: LogFormatter.java
private String formatLevel(String level, String msg) {
    if (msg.startsWith("Hibernate:")) {
        return "FINER ";
    }
    return StringUtils.rightPad(level.replace("WARNING", "WARN"), 6);
}
 
源代码18 项目: swagger-brake   文件: CliHelpProvider.java
private String formatPadCliOption(CliOption option) {
    return StringUtils.rightPad(option.asCliOption(), 40);
}
 
源代码19 项目: guarda-android-wallets   文件: SeedValidator.java
public static String getSeed(String seed) {

        seed = seed.toUpperCase();

        if (seed.length() > SEED_LENGTH_MAX)
            seed = seed.substring(0, SEED_LENGTH_MAX);

        seed = seed.replaceAll("[^A-Z9]", "9");

        seed = StringUtils.rightPad(seed, SEED_LENGTH_MAX, '9');

        return seed;
    }
 
源代码20 项目: incubator-pinot   文件: StringFunctions.java
/**
 * @see StringUtils#rightPad(String, int, char)
 * @param input
 * @param size final size of the string
 * @param pad pad string to be used
 * @return string padded from the right side with pad to reach final size
 */
@ScalarFunction
static String rpad(String input, Integer size, String pad) {
  return StringUtils.rightPad(input, size, pad);
}
 
 同类方法