Example usage for org.apache.commons.lang StringUtils leftPad

List of usage examples for org.apache.commons.lang StringUtils leftPad

Introduction

In this page you can find the example usage for org.apache.commons.lang StringUtils leftPad.

Prototype

public static String leftPad(String str, int size, String padStr) 

Source Link

Document

Left pad a String with a specified String.

Usage

From source file:com.rogoman.easyauth.Authenticator.java

/**
 * Generates a verification code based on the passed secret and a challenge value.
 *
 * @param secret         passed secret key
 * @param challengeValue passed challenge value
 * @return generated code//from   ww w  .j a  va2s.  c o m
 * @exception java.security.InvalidKeyException if the secret passed has an invalid format
 * @exception com.rogoman.easyauth.AuthenticatorException if there is another problem in computing the code value
 */
protected String getCodeInternal(final String secret, final long challengeValue)
        throws InvalidKeyException, AuthenticatorException {
    long chlg = challengeValue;

    byte[] challenge = ByteBuffer.allocate(8).putLong(challengeValue).array();

    byte[] key = Base32Encoding.toBytes(secret);
    for (int i = secret.length(); i < key.length; i++) {
        key[i] = 0;
    }

    byte[] hash;
    try {
        hash = HMAC.hmacDigest(challenge, key, CRYPTO_ALGORITHM);
    } catch (final NoSuchAlgorithmException e) {
        throw new AuthenticatorException("HmacSHA1 algorithm is not present in your JVM.", e);
    }

    int offset = hash[hash.length - 1] & 0xf;

    long truncatedHash = 0;
    for (int j = 0; j < 4; j++) {
        truncatedHash <<= 8;
        int absValue = (int) hash[offset + j] & 0xFF;
        truncatedHash |= absValue;
    }

    truncatedHash &= 0x7FFFFFFF;
    truncatedHash %= 1000000;

    String code = Long.toString(truncatedHash);
    return StringUtils.leftPad(code, 6, '0');
}

From source file:com.ocs.dynamo.utils.DateUtils.java

/**
 * Converts a date to its corresponding week code
 * /*from  w w w  . j av a 2  s.c  o m*/
 * @param date
 * @return
 */
public static String toWeekCode(Date date) {
    if (date != null) {
        Calendar calendar = new GregorianCalendar(DynamoConstants.DEFAULT_LOCALE);
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int week = calendar.get(Calendar.WEEK_OF_YEAR);
        int month = calendar.get(Calendar.MONTH);

        // if the week number is reported as 1, but we are in December,
        // then we have an "overflow"
        if (week == FIRST_WEEK_NUMBER && month == Calendar.DECEMBER) {
            year++;
        }

        return year + "-" + StringUtils.leftPad(Integer.toString(week), 2, "0");
    }
    return null;
}

From source file:com.axelor.apps.base.service.administration.SequenceService.java

/**
 * Fonction retournant une numro de squence depuis une squence gnrique, et une date
 *
 * @param seq/*from   ww w  . j  a v a 2 s .com*/
 * @param todayYear
 * @param todayMoy
 * @param todayDom
 * @param todayWoy
 * @return
 */
@Transactional(rollbackOn = { AxelorException.class, Exception.class })
public String getSequenceNumber(Sequence sequence) {

    SequenceVersion sequenceVersion = getVersion(sequence);

    String seqPrefixe = StringUtils.defaultString(sequence.getPrefixe(), ""),
            seqSuffixe = StringUtils.defaultString(sequence.getSuffixe(), ""), padLeft = StringUtils
                    .leftPad(sequenceVersion.getNextNum().toString(), sequence.getPadding(), PADDING_STRING);

    String nextSeq = (seqPrefixe + padLeft + seqSuffixe)
            .replaceAll(PATTERN_YEAR, Integer.toString(refDate.getYearOfCentury()))
            .replaceAll(PATTERN_MONTH, Integer.toString(refDate.getMonthOfYear()))
            .replaceAll(PATTERN_FULL_MONTH, refDate.toString("MM"))
            .replaceAll(PATTERN_DAY, Integer.toString(refDate.getDayOfMonth()))
            .replaceAll(PATTERN_WEEK, Integer.toString(refDate.getWeekOfWeekyear()));

    log.debug("nextSeq : : : : {}", nextSeq);

    sequenceVersion.setNextNum(sequenceVersion.getNextNum() + sequence.getToBeAdded());
    sequenceVersionRepository.save(sequenceVersion);
    return nextSeq;
}

From source file:nc.noumea.mairie.appock.core.utility.AppockUtil.java

public static String paddingZeroAGaucheSaufSiVide(String str, int nombreChiffre) {
    return StringUtils.isBlank(str) ? null : StringUtils.leftPad(str, nombreChiffre, "0");
}

From source file:com.alibaba.otter.shared.common.model.config.ConfigHelper.java

/**
 * ?DataMedianamespacename?offer[1-128]/*w  w  w. j ava2 s.  c o  m*/
 */
public static ModeValue parseMode(String value) {
    PatternMatcher matcher = new Perl5Matcher();
    if (matcher.matches(value, patterns.get(MODE_PATTERN))) {
        MatchResult matchResult = matcher.getMatch();
        String prefix = matchResult.group(1);
        String startStr = matchResult.group(3);
        String ednStr = matchResult.group(4);
        int start = Integer.valueOf(startStr);
        int end = Integer.valueOf(ednStr);
        String postfix = matchResult.group(5);

        List<String> values = new ArrayList<String>();
        for (int i = start; i <= end; i++) {
            StringBuilder builder = new StringBuilder(value.length());
            String str = String.valueOf(i);
            // ?0001
            if (startStr.length() == ednStr.length() && startStr.startsWith("0")) {
                str = StringUtils.leftPad(String.valueOf(i), startStr.length(), '0');
            }

            builder.append(prefix).append(str).append(postfix);
            values.add(builder.toString());
        }
        return new ModeValue(Mode.MULTI, values);
    } else if (isWildCard(value)) {// ??
        return new ModeValue(Mode.WILDCARD, Arrays.asList(value));
    } else {
        return new ModeValue(Mode.SINGLE, Arrays.asList(value));
    }
}

From source file:net.sourceforge.fenixedu.util.FenixStringTools.java

public static String multipleLineRightPadWithSuffix(String field, int LINE_LENGTH, char fillPaddingWith,
        String suffix) {// w  w w  . ja v  a  2  s  .  c  o  m
    if (!StringUtils.isEmpty(field) && !field.endsWith(" ")) {
        field += " ";
    }

    if (StringUtils.isEmpty(suffix)) {
        return multipleLineRightPad(field, LINE_LENGTH, fillPaddingWith);
    } else if (!suffix.startsWith(" ")) {
        suffix = " " + suffix;
    }

    int LINE_LENGTH_WITH_SUFFIX = LINE_LENGTH - suffix.length();

    if (field.length() < LINE_LENGTH_WITH_SUFFIX) {
        return FenixStringTools.rightPad(field, LINE_LENGTH_WITH_SUFFIX, fillPaddingWith) + suffix;
    } else {
        final List<String> words = Arrays.asList(field.split(" "));
        int currentLineLength = 0;
        String result = "";

        for (final String word : words) {
            final String toAdd = word + " ";

            if (currentLineLength + toAdd.length() > LINE_LENGTH) {
                result = StringUtils.rightPad(result, LINE_LENGTH, ' ') + '\n';
                currentLineLength = toAdd.length();
            } else {
                currentLineLength += toAdd.length();
            }

            result += toAdd;
        }

        if (currentLineLength < LINE_LENGTH_WITH_SUFFIX) {
            return FenixStringTools.rightPad(result,
                    result.length() + (LINE_LENGTH_WITH_SUFFIX - currentLineLength), fillPaddingWith) + suffix;
        } else {
            return FenixStringTools.rightPad(result, result.length() + (LINE_LENGTH - currentLineLength),
                    fillPaddingWith) + "\n" + StringUtils.leftPad(suffix, LINE_LENGTH, fillPaddingWith);
        }
    }
}

From source file:ca.uhn.hl7v2.testpanel.model.MessagesList.java

/**
 * Save all files to work directory/*ww  w .  j  a v  a  2 s .co m*/
 */
public void dumpToWorkDirectory(File theWorkfilesDir) throws IOException {
    ourLog.info("Flushing work files to directory: " + theWorkfilesDir.getAbsolutePath());

    IOUtils.deleteAllFromDirectory(theWorkfilesDir);

    int index = 0;
    for (Hl7V2MessageCollection next : myMessages) {
        index++;
        String seq = StringUtils.leftPad(Integer.toString(index), 10, '0');

        File nextFile = new File(theWorkfilesDir, next.getId() + "-" + seq + ".xml");
        nextFile.delete();
        Writer nextWriter = new OutputStreamWriter(new FileOutputStream(nextFile), Charset.forName("UTF-8"));
        nextWriter.append(next.exportConfigToXml());
        nextWriter.close();
    }

}

From source file:ch.algotrader.option.OptionSymbol.java

/**
 * Generates the RIC for the specified {@link ch.algotrader.entity.security.OptionFamily}.
 *//*from w  ww.j  av  a2  s.c  om*/
public static String getRic(OptionFamily family, LocalDate expiration, OptionType type, BigDecimal strike) {

    StringBuilder buffer = new StringBuilder();
    buffer.append(family.getRicRoot() != null ? family.getRicRoot() : family.getSymbolRoot());
    if (OptionType.CALL.equals(type)) {
        buffer.append(monthCallEnc[expiration.getMonthValue() - 1]);
    } else {
        buffer.append(monthPutEnc[expiration.getMonthValue() - 1]);
    }
    buffer.append(DateTimePatterns.DAY_OF_MONTH.format(expiration));
    final String s = DateTimePatterns.YEAR_4_DIGIT.format(expiration);
    buffer.append(s.substring(s.length() - 2, s.length()));
    buffer.append(StringUtils.leftPad(String.valueOf((int) (strike.doubleValue() * 100)), 5, "0"));
    buffer.append(".U");

    return buffer.toString();
}

From source file:net.sf.zekr.common.resource.QuranLocation.java

public String toSortableString() {
    String suraStr = StringUtils.leftPad(String.valueOf(sura), 3, '0');
    String ayaStr = StringUtils.leftPad(String.valueOf(aya), 3, '0');
    return new StringBuffer(suraStr).append("-").append(ayaStr).toString();
}

From source file:gov.nih.nci.firebird.test.ValueGenerator.java

private static String getIntegerString(int length) {
    String value = StringUtils.leftPad(String.valueOf(getUniqueInt()), length, '0');
    return StringUtils.right(value, length);
}