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

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

Introduction

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

Prototype

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

Source Link

Document

Left pad a String with a specified String.

Pad to a size of size .

 StringUtils.leftPad(null, *, *)      = null StringUtils.leftPad("", 3, "z")      = "zzz" StringUtils.leftPad("bat", 3, "yz")  = "bat" StringUtils.leftPad("bat", 5, "yz")  = "yzbat" StringUtils.leftPad("bat", 8, "yz")  = "yzyzybat" StringUtils.leftPad("bat", 1, "yz")  = "bat" StringUtils.leftPad("bat", -1, "yz") = "bat" StringUtils.leftPad("bat", 5, null)  = "  bat" StringUtils.leftPad("bat", 5, "")    = "  bat" 

Usage

From source file:org.jboss.dashboard.ui.config.components.sections.SectionsPropertiesFormatter.java

protected List<Section> initSections(String preffix, WorkspaceImpl workspace) {
    List<Section> pages = new ArrayList<Section>();
    if (workspace != null) {
        Section[] sections = workspace.getAllSections(); //Sorted!
        for (int i = 0; i < sections.length; i++) {
            Section section = sections[i];
            int depth = section.getDepthLevel();
            SectionPermission viewPerm = SectionPermission.newInstance(sections[i],
                    SectionPermission.ACTION_VIEW);
            if (UserStatus.lookup().hasPermission(viewPerm)) {
                pages.add(section);/*  w  ww .  jav  a2  s  . co  m*/
                String title = getTitle(sections[i]);
                pageTitles
                        .add(StringUtils.leftPad(title, title.length() + (depth * preffix.length()), preffix));
            } else { // Skip all following pages with larger depth (children)
                while (i + 1 < sections.length && sections[i + 1].getDepthLevel() > depth)
                    i++;
            }
        }
    }
    return pages;
}

From source file:org.jboss.dashboard.ui.controller.requestChain.CSRFTokenGenerator.java

public synchronized String generateToken() {
    long seed = (long) (Math.random() * Math.pow(10, tokenSize));
    String token = StringUtils.leftPad(String.valueOf(seed), tokenSize, "0");

    if (tokenList.size() == maxTokens)
        tokenList.remove(0);/*  w  w  w  .jav  a2s  .  c  o  m*/
    tokenList.add(token);
    return token;
}

From source file:org.jboss.dashboard.ui.formatters.RenderIndentedSectionsFormatter.java

protected void initSections(String preffix, WorkspaceImpl workspace) {
    if (workspace != null) {
        Section[] sections = workspace.getAllSections(); //Sorted!
        for (int i = 0; i < sections.length; i++) {
            Section section = sections[i];
            int depth = section.getDepthLevel();
            SectionPermission viewPerm = SectionPermission.newInstance(sections[i],
                    SectionPermission.ACTION_VIEW);
            if (UserStatus.lookup().hasPermission(viewPerm)) {
                pages.add(section);/*from  ww w.j av a2 s .  com*/
                String title = getTitle(sections[i]);
                pageTitles
                        .add(StringUtils.leftPad(title, title.length() + (depth * preffix.length()), preffix));
            } else { // Skip all following pages with larger depth (children)
                while (i + 1 < sections.length && sections[i + 1].getDepthLevel() > depth)
                    i++;
            }
        }
    }
}

From source file:org.kie.workbench.common.stunner.svg.gen.translator.css.SVGAttributeParser.java

public static String toHexColorString(final String raw) {
    if (raw.startsWith("#")) {
        return "#" + StringUtils.leftPad(raw.substring(1, raw.length()), 6, "0");
    }/*from   w w w  . j  av a2s  . c  o  m*/
    if (raw.startsWith("rgb")) {
        Matcher m = RBG_PATTERN.matcher(raw);
        if (m.matches()) {
            final int r = Integer.valueOf(m.group(1));
            final int g = Integer.valueOf(m.group(2));
            final int b = Integer.valueOf(m.group(3));
            return rgbToHexString(r, g, b);
        }
    }
    final ColorName name = ColorName.lookup(raw);
    final Color color = null != name ? ColorName.lookup(raw).getColor() : null;
    if (null != color) {
        return rgbToHexString(color.getR(), color.getG(), color.getB());
    }
    throw new RuntimeException("RGB value cannot be parsed! [" + raw + "]");
}

From source file:org.kie.workbench.common.stunner.svg.gen.translator.css.SVGAttributeParserUtils.java

public static String toHexColorString(final String raw) {
    if (raw.startsWith("#")) {
        return "#" + StringUtils.leftPad(raw.substring(1, raw.length()), 6, "0");
    }/*from  ww  w. ja  va2 s.  c  o m*/
    if (raw.startsWith("rgb")) {
        Matcher m = RBG_PATTERN.matcher(raw);
        if (m.matches()) {
            final int r = Integer.valueOf(m.group(1));
            final int g = Integer.valueOf(m.group(2));
            final int b = Integer.valueOf(m.group(3));
            return rgbToHexString(r, g, b, 1);
        }
    }
    final ColorName name = ColorName.lookup(raw);
    final Color color = null != name ? ColorName.lookup(raw).getColor() : null;
    if (null != color) {
        return rgbToHexString(color.getR(), color.getG(), color.getB(), 1);
    }
    throw new RuntimeException("RGB value cannot be parsed! [" + raw + "]");
}

From source file:org.kuali.coeus.common.impl.org.OrganizationMaintenableImpl.java

/**
 * This method pads the district number to CongressionalDistrict.DISTRICT_NUMBER_LENGTH
 * characters (A congressional district consists of a state code, followed by a dash,
 * followed by a district number)./*from w  w  w  . j  a v  a 2  s . c o  m*/
 * @param organization
 */
private void formatCongressionalDistrict(Organization organization) {
    String district = organization.getCongressionalDistrict();
    if (district != null) {
        int dashPosition = district.indexOf('-');
        if (dashPosition >= 0) {
            // everything up to, and including, the dash
            String stateCodePlusDash = district.substring(0, dashPosition + 1);
            String paddedDistrictNumber = StringUtils.leftPad(district.substring(dashPosition + 1),
                    CongressionalDistrict.DISTRICT_NUMBER_LENGTH, '0');
            organization.setCongressionalDistrict(stateCodePlusDash + paddedDistrictNumber);
        }
    }
}

From source file:org.kuali.coeus.propdev.impl.location.CongressionalDistrict.java

public String getNewDistrictNumber() {
    if (StringUtils.isNumeric(newDistrictNumber)) {
        newDistrictNumber = StringUtils.leftPad(newDistrictNumber, CongressionalDistrict.DISTRICT_NUMBER_LENGTH,
                "0");
    }/*from w  w w .j a v  a2 s .  co m*/
    return newDistrictNumber;
}

From source file:org.lockss.util.NumberUtil.java

/**
 * Construct an alphabetical (base-26) sequence by incrementing the first
 * string alphabetically until it reaches the second string. The start string
 * is incremented by the given delta; if the delta does not divide into the
 * Levenstein distance between the start and end strings, an exception is
 * thrown. The strings must also be the same length.
 * <p>//w ww.j av  a2 s  .c o m
 * The string is lower cased before the increment is applied, and then each
 * character position that was upper case in the original string is upper
 * cased in the resulting string. It is assumed that the two strings are
 * capitalised in the same pattern. An exception will be thrown if any
 * character is outside of a-z after lower casing.
 *
 * @param start an alphabetical string (case-insensitive)
 * @param end an alphabetical string (case-insensitive)
 * @param delta the increment between strings in the sequence; can be negative
 * @return a list of strings representing a sequence from <tt>start</tt> to <tt>end</tt>
 * @throws IllegalArgumentException if the delta does not divide into the gap or the strings are different lengths
 */
public static List<String> constructAlphabeticSequence(final String start, final String end, int delta)
        throws IllegalArgumentException {

    // Ensure the delta is positive
    if (delta == 0)
        throw new IllegalArgumentException("Delta cannot be 0.");

    // If the strings are equal, the sequence will be the single string
    if (start.equals(end))
        return new ArrayList<String>() {
            {
                add(start);
            }
        };

    // Check the string lengths are the same
    if (start.length() != end.length())
        throw new IllegalArgumentException(
                String.format("Start and end strings are different lengths: %s %s.", start, end));

    // Find the integer distance
    int distance = Math.abs(fromBase26(start) - fromBase26(end));
    //int distance = StringUtils.getLevenshteinDistance(start, end);
    // Check the delta divides into the gap
    if (distance % delta != 0) {
        throw new IllegalArgumentException(String.format(
                "The distance %s between start and end must be " + "divisible by delta %s.", distance, delta));
    }

    // Track the case of each character, so we can reset them before returning
    BitSet cases = new BitSet(start.length());
    for (int i = 0; i < start.length(); i++) {
        cases.set(i, Character.isUpperCase(start.charAt(i)));
    }

    // Increment alphabetically
    List<String> seq = new ArrayList<String>();
    int[] nums = constructSequence(fromBase26(start), fromBase26(end), delta);
    for (int i = 0; i < nums.length; i++) {
        String s = toBase26(nums[i]);
        // Pad the string to the correct length with 'a'
        s = StringUtils.leftPad(s, start.length(), 'a');
        // Re-case the chars
        char[] carr = s.toCharArray();
        for (int pos = 0; pos < cases.length(); pos++) {
            if (cases.get(pos))
                carr[pos] = Character.toUpperCase(carr[pos]);
        }
        seq.add(new String(carr));
    }
    return seq;
}

From source file:org.lockss.util.NumberUtil.java

/**
 * Increment an alphabetical string by the given delta, considering the string
 * to represent a value in base-26 using the characters a-z or A-Z - the
 * string is treated case-insensitively. For example, with a delta of 1:
 * <ul>//  w w w .j  ava 2s.  co m
 *   <li>aaa to aab</li>
 *   <li>aaz to aba</li>
 *   <li>zzy to zzz</li>
 *   <li>zyz to zza</li>
 * </ul>
 * <p>
 * Note that after 'z' comes 'ba', because 'a' corresponds to 0 and is so
 * every number is implicitly preceded by 'a'. This may not be what is desired
 * for some sequences, in which case this may need to be adapted.
 * <p>
 * The string is lower cased before the increment is applied, and then each
 * character position that was upper case in the original string is upper
 * cased before returning. An exception will be thrown if any character is
 * outside of a-z after lower casing. If the value limit for the string length
 * is reached, the returned string will be longer; the extra characters will
 * be lower cased, which may be unwanted.
 *
 * @param s a purely alphabetical string
 * @return a string incremented according to base-26
 * @throws NumberFormatException if the string contains inappropriate characters or cannot be incremented
 */
public static String incrementBase26String(String s, int delta) throws NumberFormatException {
    // Track the case of each character, so we can reset them before returning
    BitSet cases = new BitSet();
    for (int i = 0; i < s.length(); i++) {
        cases.set(i, Character.isUpperCase(s.charAt(i)));
    }
    // Convert, increment, convert back
    String res = toBase26(fromBase26(s.toLowerCase()) + delta);
    // Pad the string to the correct length with 'a'
    res = StringUtils.leftPad(res, s.length(), 'a');
    // Re-case the chars - using an offset in case the new string is longer
    char[] carr = res.toCharArray();
    int offset = carr.length - s.length();
    for (int pos = 0; pos < s.length(); pos++) {
        if (cases.get(pos))
            carr[offset + pos] = Character.toUpperCase(carr[offset + pos]);
    }
    return new String(carr);
}

From source file:org.meveocrm.admin.action.reporting.MeasurementBean.java

public void generateMVModel() throws ParseException {
    if (measurableQuantity != null && selectedDate != null) {
        mainMVModel = new ArrayList<MeasuredValue>();
        Calendar cal = Calendar.getInstance();
        cal.setTime(selectedDate);/*from www.  java2  s. co  m*/

        int daysInMonth = cal.getActualMaximum(Calendar.DAY_OF_MONTH);

        for (int i = 0; i < daysInMonth; i++) {
            String dateCol = StringUtils
                    .leftPad(StringUtils.leftPad(String.valueOf(String.valueOf(i + 1)), 2, '0') + "/"
                            + String.valueOf(cal.get(Calendar.MONTH) + 1), 2, '0')
                    + "/" + String.valueOf(cal.get(Calendar.YEAR));
            Date date = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH).parse(dateCol);
            MeasuredValue mv = measuredValueService.getByDate(date, period, measurableQuantity);
            if (mv == null) {
                mv = new MeasuredValue();
                mv.setMeasurableQuantity(measurableQuantity);
                mv.setDate(date);
                mv.setMeasurementPeriod(period);
            }
            mainMVModel.add(mv);
        }
    }
}