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

The following examples show how to use org.apache.commons.lang3.StringUtils#rightPad() . 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: CreateRedirectURITest.java    From uyuni with GNU General Public License v2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: Levels.java    From codenjoy with GNU General Public License v3.0 6 votes vote down vote up
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;
}
 
Example 3
Source File: LayoutBuilder.java    From react-native-esc-pos with 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 4
Source File: Row.java    From macrobase with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 5
Source File: TagEntityTest.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 6
Source File: RightPadString.java    From levelup-java-examples with Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 7
Source File: AgentRegistrationControllerTest.java    From gocd with Apache License 2.0 5 votes vote down vote up
@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));
}
 
Example 8
Source File: ValidatorsTest.java    From rocketmq-all-4.1.0-incubating with Apache License 2.0 5 votes vote down vote up
@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.");
    }
}
 
Example 9
Source File: SensitiveInfoUtils.java    From Resource with GNU General Public License v3.0 5 votes vote down vote up
public static String cnapsCode(String cnaps)
{
    if (StringUtils.isBlank(cnaps))
    {
        return "";
    }
    return StringUtils.rightPad(StringUtils.left(cnaps, 2), StringUtils.length(cnaps), "*");
}
 
Example 10
Source File: ValidatorsTest.java    From DDMQ with Apache License 2.0 5 votes vote down vote up
@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.");
    }
}
 
Example 11
Source File: Award.java    From pikatimer with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 12
Source File: BaseDateTimeType.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 13
Source File: AESSensitivePropertyProvider.java    From nifi with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 14
Source File: BaseDateTimeType.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 15
Source File: BaseDateTimeType.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 16
Source File: LevelImpl.java    From codenjoy with GNU General Public License v3.0 4 votes vote down vote up
private String pad(int len, char left, char middle, char right) {
    return left + StringUtils.rightPad("", len - 2, middle) + right;
}
 
Example 17
Source File: CliHelpProvider.java    From swagger-brake with Apache License 2.0 4 votes vote down vote up
private String formatPadCliOption(CliOption option) {
    return StringUtils.rightPad(option.asCliOption(), 40);
}
 
Example 18
Source File: LogFormatter.java    From VoxelGamesLibv2 with MIT License 4 votes vote down vote up
private String formatLevel(String level, String msg) {
    if (msg.startsWith("Hibernate:")) {
        return "FINER ";
    }
    return StringUtils.rightPad(level.replace("WARNING", "WARN"), 6);
}
 
Example 19
Source File: SeedValidator.java    From guarda-android-wallets with GNU General Public License v3.0 3 votes vote down vote up
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;
    }
 
Example 20
Source File: StringFunctions.java    From incubator-pinot with Apache License 2.0 2 votes vote down vote up
/**
 * @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);
}