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

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

Introduction

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

Prototype

public static String repeat(final char ch, final int repeat) 

Source Link

Document

<p>Returns padding using the specified delimiter repeated to a given length.</p> <pre> StringUtils.repeat('e', 0) = "" StringUtils.repeat('e', 3) = "eee" StringUtils.repeat('e', -2) = "" </pre> <p>Note: this method doesn't not support padding with <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> as they require a pair of char s to be represented.

Usage

From source file:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java

protected void importMarkupStyle1(Pattern titlePattern, Markup titlePrefix, Reader markupText,
        MarkupLanguage markupLanguage, int levelOffset) {
    Validate.isTrue(levelOffset <= MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) > max levelOffset (%d)", levelOffset, MAX_TITLE_LEVEL));
    Validate.isTrue(levelOffset >= -MAX_TITLE_LEVEL,
            String.format("Specified levelOffset (%d) < min levelOffset (%d)", levelOffset, -MAX_TITLE_LEVEL));

    StringBuffer leveledText = new StringBuffer();
    try (BufferedReader bufferedReader = new BufferedReader(markupText)) {
        String readLine;// www  . jav a  2s.com
        while ((readLine = bufferedReader.readLine()) != null) {
            Matcher titleMatcher = titlePattern.matcher(readLine);

            while (titleMatcher.find()) {
                int titleLevel = titleMatcher.group(1).length() - 1;
                String title = titleMatcher.group(2);

                if (titleLevel + levelOffset > MAX_TITLE_LEVEL)
                    throw new IllegalArgumentException(String.format(
                            "Specified levelOffset (%d) set title '%s' level (%d) > max title level (%d)",
                            levelOffset, title, titleLevel, MAX_TITLE_LEVEL));
                if (titleLevel + levelOffset < 0)
                    throw new IllegalArgumentException(
                            String.format("Specified levelOffset (%d) set title '%s' level (%d) < 0",
                                    levelOffset, title, titleLevel));
                else
                    titleMatcher.appendReplacement(leveledText, Matcher.quoteReplacement(String.format("%s %s",
                            StringUtils.repeat(titlePrefix.toString(), 1 + titleLevel + levelOffset), title)));
            }
            titleMatcher.appendTail(leveledText);
            leveledText.append(newLine);
        }
    } catch (IOException e) {
        throw new RuntimeException("Failed to import Markup", e);
    }

    if (!StringUtils.isBlank(leveledText)) {
        documentBuilder.append(newLine);
        documentBuilder.append(convert(leveledText.toString(), markupLanguage));
        documentBuilder.append(newLine);
    }
}

From source file:com.atlassian.jira.bc.user.TestDefaultUserService.java

@Test
public void testValidateCreateJiraUserEmailExceeds255() {
    checkCreateUserValues("testuser543", "mypassword", "mypassword", StringUtils.repeat("a", 256),
            "Fred Flintstone", "signup.error.email.greater.than.max.chars", "email");
}

From source file:candr.yoclip.DefaultParserHelpFactoryTest.java

@Test
public void testWrap() {

    final ParserHelpFactory<TestCase> testCase = new DefaultParserHelpFactory<TestCase>();
    final int width = 30;

    assertThat("empty", StringUtils.isEmpty(testCase.wrap("", width)), is(true));
    assertThat("null", StringUtils.isEmpty(testCase.wrap(null, width)), is(true));

    StrBuilder builder = new StrBuilder();
    builder.appendln(StringUtils.repeat("abc", 10)).append(StringUtils.repeat("abc", 5));
    assertThat("!whitespace", testCase.wrap(StringUtils.repeat("abc", 15), width), is(builder.toString()));

    final String pangram = "The quick brown fox jumps over the lazy dog";
    builder.clear();//from w  ww  .j ava2  s .  com
    builder.appendln("The quick brown fox jumps over").append("the lazy dog");
    assertThat("pangram", testCase.wrap(pangram, width), is(builder.toString()));

    final String newLines = "\nExpected first line without indent.\n\nFollowed by more that are not indented.\n";
    builder.clear();
    builder.appendNewLine().appendln("Expected first line without").appendln("indent.").appendNewLine()
            .appendln("Followed by more that are not").appendln("indented.");
    assertThat("new lines", testCase.wrap(newLines, width), is(builder.toString()));

}

From source file:com.atlassian.jira.bc.user.TestDefaultUserService.java

@Test
public void testValidateCreateJiraUserUsernameExceeds255() {
    checkCreateUserValues(StringUtils.repeat("a", 256), "mypassword", "mypassword", "fred@flintstone.com",
            "Fred Flintstone", "signup.error.username.greater.than.max.chars", "username");
}

From source file:ac.core.ConfigLoader.java

/**
 * showConfigNodes(...) method is used to recursively scan the XML config
 * file and display the nodes in tree format.
 *
 * @param parent//from   www .j a  v a2  s .  com
 * @param level level of the node, increased for each child-node to allow
 * tabbed tree display output
 *
 */
protected void showConfigNodes(org.w3c.dom.Node parent, int level) {
    // create a local class to display node value/text and associated
    // node attributes
    class SubShowNode {

        // loop through the node attributes for the node passed
        String displayNodeAttributes(org.w3c.dom.Node node) {
            // create string build object to support string concatanation
            StringBuilder sb = new StringBuilder();

            // retrieve node attributes (if any)
            ArrayList nAttributes = _xmlr.getNodeAttributes(node);

            // loop through the attributes array and append them to the
            // string builder object
            for (Object na : nAttributes) {
                // append the attribute details (key/text) to the string
                // builder object
                sb.append(" [ATTR=").append(((org.w3c.dom.Node) na).getNodeName()).append("//")
                        .append(((org.w3c.dom.Node) na).getNodeValue()).append("]");

                // yield processing to other threads
                Thread.yield();
            }

            // return the string builder representation as a string
            return sb.toString();
        }
    }

    // declare the showNode class to allow methods to reference the display
    // method to prevent duplicaion in code
    SubShowNode showNode = new SubShowNode();

    // retrieve the child nodes for processing
    ArrayList nodes = _xmlr.getNodeChildren(parent);

    // if node level is 1, then this is root node, display it with no
    // indentation
    if (level == 1) {
        // display the parent node name
        String data = StringUtils.repeat('~', level) + parent.getNodeName();

        // use the sub function to extract node attributes
        data += showNode.displayNodeAttributes(parent);

        // display all collected data to the user output
        System.out.println(data);
    }

    // parse the list of child nodes for the node being processed
    for (Object node : nodes) {
        // display the parent node name
        String data = StringUtils.repeat('\t', level) + ((org.w3c.dom.Node) node).getNodeName();

        // use the sub function to extract node attributes
        data += showNode.displayNodeAttributes((org.w3c.dom.Node) node);

        // if node has a text value, display the text
        if (_xmlr.getNodeText((org.w3c.dom.Node) node) != null) {
            data += " (TEXT=" + _xmlr.getNodeText((org.w3c.dom.Node) node) + ")";
        }

        // display all collected data to the user output
        System.out.println(data);

        // recall the function (recursion) to see if the node has child 
        // nodes and preocess them in hierarchial level
        showConfigNodes((org.w3c.dom.Node) node, (level + 1));

        // yield processing to other threads
        Thread.yield();
    }
}

From source file:forge.game.spellability.AbilityManaPart.java

/**
 * <p>/*from w w w  . j a  va  2s .  co m*/
 * applyManaReplacement.
 * </p>
 * @return a String
 */
public static String applyManaReplacement(final SpellAbility sa, final String original) {
    final HashMap<String, String> repMap = new HashMap<String, String>();
    final Player act = sa != null ? sa.getActivatingPlayer() : null;
    final String manaReplace = sa != null ? sa.getManaPart().getManaReplaceType() : "";
    if (manaReplace.isEmpty()) {
        if (act != null && act.getLandsPlayedThisTurn() > 0 && sa.hasParam("ReplaceIfLandPlayed")) {
            return sa.getParam("ReplaceIfLandPlayed");
        }
        return original;
    }
    if (manaReplace.startsWith("Any")) {
        // Replace any type and amount
        String replaced = manaReplace.split("->")[1];
        if (replaced.equals("Any")) {
            byte rs = MagicColor.GREEN;
            if (act != null) {
                rs = act.getController().chooseColor("Choose a color", sa, ColorSet.ALL_COLORS);
            }
            replaced = MagicColor.toShortString(rs);
        }
        return replaced;
    }
    final Pattern splitter = Pattern.compile("->");
    // Replace any type
    for (String part : manaReplace.split(" & ")) {
        final String[] v = splitter.split(part, 2);
        if (v[0].equals("Colorless")) {
            repMap.put("[0-9][0-9]?", v.length > 1 ? v[1].trim() : "");
        } else {
            repMap.put(v[0], v.length > 1 ? v[1].trim() : "");
        }
    }
    // Handle different replacement simultaneously
    Pattern pattern = Pattern.compile(StringUtils.join(repMap.keySet().iterator(), "|"));
    Matcher m = pattern.matcher(original);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        if (m.group().matches("[0-9][0-9]?")) {
            final String rep = StringUtils.repeat(repMap.get("[0-9][0-9]?") + " ", Integer.parseInt(m.group()))
                    .trim();
            m.appendReplacement(sb, rep);
        } else {
            m.appendReplacement(sb, repMap.get(m.group()));
        }
    }
    m.appendTail(sb);
    String replaced = sb.toString();
    while (replaced.contains("Any")) {
        byte rs = MagicColor.GREEN;
        if (act != null) {
            rs = act.getController().chooseColor("Choose a color", sa, ColorSet.ALL_COLORS);
        }
        replaced = replaced.replaceFirst("Any", MagicColor.toShortString(rs));
    }
    return replaced;
}

From source file:fi.foyt.fni.gamelibrary.PublicationController.java

private String createUrlName(Publication publication, String name) {
    int maxLength = 20;
    int padding = 0;
    do {/*from  w ww .j  av a 2 s . c  om*/
        String urlName = RequestUtils.createUrlName(name, maxLength);
        if (padding > 0) {
            urlName = urlName.concat(StringUtils.repeat('_', padding));
        }

        Publication existingPublication = publicationDAO.findByUrlName(urlName);
        if (existingPublication == null) {
            return urlName;
        }

        if (publication != null && existingPublication.getId().equals(existingPublication.getId())) {
            return urlName;
        }

        if (maxLength < name.length()) {
            maxLength++;
        } else {
            padding++;
        }
    } while (true);
}

From source file:com.atlassian.jira.bc.user.TestDefaultUserService.java

@Test
public void testValidateCreateJiraUserFullnameExceeds255() {
    checkCreateUserValues("testuser654", "mypassword", "mypassword", "fred@flintstone.com",
            StringUtils.repeat("a", 256), "signup.error.full.name.greater.than.max.chars", "fullname");
}

From source file:edu.illinois.cs.cogcomp.transliteration.CSPTransliteration.java

public static double GetProbability(String word1, String word2, CSPModel model) {
    int paddingSize = Math.max(model.productionContextSize, model.segContextSize);
    String paddedWord = StringUtils.repeat('_', paddingSize) + word1 + StringUtils.repeat('_', paddingSize);

    if (model.segMode != CSPModel.SegMode.Best) {
        Pair<Double, Double> raw = GetProbability(paddingSize, paddedWord, word1, word2, model,
                new HashMap<Triple<Integer, String, String>, Pair<Double, Double>>());
        return raw.getFirst() / raw.getSecond(); //normalize the segmentation probabilities by dividing by the sum of probabilities for all segmentations
    } else/* w ww.j a  v  a2 s  . c om*/
        return GetBestProbability(paddingSize, paddedWord, word1, word2, model,
                new HashMap<Triple<Integer, String, String>, Double>());
}

From source file:com.netflix.imfutility.itunes.ITunesFormatBuilder.java

private String computeSilenceExprParameter(String channelsNum) {
    return StringUtils.repeat("0:", Integer.parseInt(channelsNum));
}